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 *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
284 SDValue ReduceLoadWidth(SDNode *N);
285 SDValue ReduceLoadOpStoreWidth(SDNode *N);
286 SDValue TransformFPLoadStorePair(SDNode *N);
287 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
288 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
290 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
292 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
293 /// looking for aliasing nodes and adding them to the Aliases vector.
294 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
295 SmallVectorImpl<SDValue> &Aliases);
297 /// isAlias - Return true if there is any possibility that the two addresses
299 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
300 const Value *SrcValue1, int SrcValueOffset1,
301 unsigned SrcValueAlign1,
302 const MDNode *TBAAInfo1,
303 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
304 const Value *SrcValue2, int SrcValueOffset2,
305 unsigned SrcValueAlign2,
306 const MDNode *TBAAInfo2) const;
308 /// isAlias - Return true if there is any possibility that the two addresses
310 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
312 /// FindAliasInfo - Extracts the relevant alias information from the memory
313 /// node. Returns true if the operand was a load.
314 bool FindAliasInfo(SDNode *N,
315 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
316 const Value *&SrcValue, int &SrcValueOffset,
317 unsigned &SrcValueAlignment,
318 const MDNode *&TBAAInfo) const;
320 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
321 /// looking for a better chain (aliasing node.)
322 SDValue FindBetterChain(SDNode *N, SDValue Chain);
324 /// Merge consecutive store operations into a wide store.
325 /// This optimization uses wide integers or vectors when possible.
326 /// \return True if some memory operations were changed.
327 bool MergeConsecutiveStores(StoreSDNode *N);
330 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
331 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
332 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
333 AttributeSet FnAttrs =
334 DAG.getMachineFunction().getFunction()->getAttributes();
336 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
337 Attribute::OptimizeForSize) ||
338 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
341 /// Run - runs the dag combiner on all nodes in the work list
342 void Run(CombineLevel AtLevel);
344 SelectionDAG &getDAG() const { return DAG; }
346 /// getShiftAmountTy - Returns a type large enough to hold any valid
347 /// shift amount - before type legalization these can be huge.
348 EVT getShiftAmountTy(EVT LHSTy) {
349 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
350 if (LHSTy.isVector())
352 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
353 : TLI.getPointerTy();
356 /// isTypeLegal - This method returns true if we are running before type
357 /// legalization or if the specified VT is legal.
358 bool isTypeLegal(const EVT &VT) {
359 if (!LegalTypes) return true;
360 return TLI.isTypeLegal(VT);
363 /// getSetCCResultType - Convenience wrapper around
364 /// TargetLowering::getSetCCResultType
365 EVT getSetCCResultType(EVT VT) const {
366 return TLI.getSetCCResultType(*DAG.getContext(), VT);
373 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
374 /// nodes from the worklist.
375 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
378 explicit WorkListRemover(DAGCombiner &dc)
379 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
381 virtual void NodeDeleted(SDNode *N, SDNode *E) {
382 DC.removeFromWorkList(N);
387 //===----------------------------------------------------------------------===//
388 // TargetLowering::DAGCombinerInfo implementation
389 //===----------------------------------------------------------------------===//
391 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
392 ((DAGCombiner*)DC)->AddToWorkList(N);
395 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
396 ((DAGCombiner*)DC)->removeFromWorkList(N);
399 SDValue TargetLowering::DAGCombinerInfo::
400 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
401 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
404 SDValue TargetLowering::DAGCombinerInfo::
405 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
406 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
412 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
415 void TargetLowering::DAGCombinerInfo::
416 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
417 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
420 //===----------------------------------------------------------------------===//
422 //===----------------------------------------------------------------------===//
424 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
425 /// specified expression for the same cost as the expression itself, or 2 if we
426 /// can compute the negated form more cheaply than the expression itself.
427 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
428 const TargetLowering &TLI,
429 const TargetOptions *Options,
430 unsigned Depth = 0) {
431 // fneg is removable even if it has multiple uses.
432 if (Op.getOpcode() == ISD::FNEG) return 2;
434 // Don't allow anything with multiple uses.
435 if (!Op.hasOneUse()) return 0;
437 // Don't recurse exponentially.
438 if (Depth > 6) return 0;
440 switch (Op.getOpcode()) {
441 default: return false;
442 case ISD::ConstantFP:
443 // Don't invert constant FP values after legalize. The negated constant
444 // isn't necessarily legal.
445 return LegalOperations ? 0 : 1;
447 // FIXME: determine better conditions for this xform.
448 if (!Options->UnsafeFPMath) return 0;
450 // After operation legalization, it might not be legal to create new FSUBs.
451 if (LegalOperations &&
452 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
455 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
456 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
459 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
460 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
463 // We can't turn -(A-B) into B-A when we honor signed zeros.
464 if (!Options->UnsafeFPMath) return 0;
466 // fold (fneg (fsub A, B)) -> (fsub B, A)
471 if (Options->HonorSignDependentRoundingFPMath()) return 0;
473 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
474 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
478 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
484 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
489 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
490 /// returns the newly negated expression.
491 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
492 bool LegalOperations, unsigned Depth = 0) {
493 // fneg is removable even if it has multiple uses.
494 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
496 // Don't allow anything with multiple uses.
497 assert(Op.hasOneUse() && "Unknown reuse!");
499 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
500 switch (Op.getOpcode()) {
501 default: llvm_unreachable("Unknown code");
502 case ISD::ConstantFP: {
503 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
505 return DAG.getConstantFP(V, Op.getValueType());
508 // FIXME: determine better conditions for this xform.
509 assert(DAG.getTarget().Options.UnsafeFPMath);
511 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
512 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513 DAG.getTargetLoweringInfo(),
514 &DAG.getTarget().Options, Depth+1))
515 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
516 GetNegatedExpression(Op.getOperand(0), DAG,
517 LegalOperations, Depth+1),
519 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
520 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
521 GetNegatedExpression(Op.getOperand(1), DAG,
522 LegalOperations, Depth+1),
525 // We can't turn -(A-B) into B-A when we honor signed zeros.
526 assert(DAG.getTarget().Options.UnsafeFPMath);
528 // fold (fneg (fsub 0, B)) -> B
529 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
530 if (N0CFP->getValueAPF().isZero())
531 return Op.getOperand(1);
533 // fold (fneg (fsub A, B)) -> (fsub B, A)
534 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
535 Op.getOperand(1), Op.getOperand(0));
539 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
541 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543 DAG.getTargetLoweringInfo(),
544 &DAG.getTarget().Options, Depth+1))
545 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
546 GetNegatedExpression(Op.getOperand(0), DAG,
547 LegalOperations, Depth+1),
550 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
551 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
553 GetNegatedExpression(Op.getOperand(1), DAG,
554 LegalOperations, Depth+1));
558 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
559 GetNegatedExpression(Op.getOperand(0), DAG,
560 LegalOperations, Depth+1));
562 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
563 GetNegatedExpression(Op.getOperand(0), DAG,
564 LegalOperations, Depth+1),
570 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
571 // that selects between the values 1 and 0, making it equivalent to a setcc.
572 // Also, set the incoming LHS, RHS, and CC references to the appropriate
573 // nodes based on the type of node we are checking. This simplifies life a
574 // bit for the callers.
575 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
577 if (N.getOpcode() == ISD::SETCC) {
578 LHS = N.getOperand(0);
579 RHS = N.getOperand(1);
580 CC = N.getOperand(2);
583 if (N.getOpcode() == ISD::SELECT_CC &&
584 N.getOperand(2).getOpcode() == ISD::Constant &&
585 N.getOperand(3).getOpcode() == ISD::Constant &&
586 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
587 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
588 LHS = N.getOperand(0);
589 RHS = N.getOperand(1);
590 CC = N.getOperand(4);
596 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
597 // one use. If this is true, it allows the users to invert the operation for
598 // free when it is profitable to do so.
599 static bool isOneUseSetCC(SDValue N) {
601 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
606 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
607 SDValue N0, SDValue N1) {
608 EVT VT = N0.getValueType();
609 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
610 if (isa<ConstantSDNode>(N1)) {
611 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
613 DAG.FoldConstantArithmetic(Opc, VT,
614 cast<ConstantSDNode>(N0.getOperand(1)),
615 cast<ConstantSDNode>(N1));
616 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
618 if (N0.hasOneUse()) {
619 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
620 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
621 N0.getOperand(0), N1);
622 AddToWorkList(OpNode.getNode());
623 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
627 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
628 if (isa<ConstantSDNode>(N0)) {
629 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
631 DAG.FoldConstantArithmetic(Opc, VT,
632 cast<ConstantSDNode>(N1.getOperand(1)),
633 cast<ConstantSDNode>(N0));
634 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
636 if (N1.hasOneUse()) {
637 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
638 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
639 N1.getOperand(0), N0);
640 AddToWorkList(OpNode.getNode());
641 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
648 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
650 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
652 DEBUG(dbgs() << "\nReplacing.1 ";
654 dbgs() << "\nWith: ";
655 To[0].getNode()->dump(&DAG);
656 dbgs() << " and " << NumTo-1 << " other values\n";
657 for (unsigned i = 0, e = NumTo; i != e; ++i)
658 assert((!To[i].getNode() ||
659 N->getValueType(i) == To[i].getValueType()) &&
660 "Cannot combine value to value of different type!"));
661 WorkListRemover DeadNodes(*this);
662 DAG.ReplaceAllUsesWith(N, To);
664 // Push the new nodes and any users onto the worklist
665 for (unsigned i = 0, e = NumTo; i != e; ++i) {
666 if (To[i].getNode()) {
667 AddToWorkList(To[i].getNode());
668 AddUsersToWorkList(To[i].getNode());
673 // Finally, if the node is now dead, remove it from the graph. The node
674 // may not be dead if the replacement process recursively simplified to
675 // something else needing this node.
676 if (N->use_empty()) {
677 // Nodes can be reintroduced into the worklist. Make sure we do not
678 // process a node that has been replaced.
679 removeFromWorkList(N);
681 // Finally, since the node is now dead, remove it from the graph.
684 return SDValue(N, 0);
688 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
689 // Replace all uses. If any nodes become isomorphic to other nodes and
690 // are deleted, make sure to remove them from our worklist.
691 WorkListRemover DeadNodes(*this);
692 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
694 // Push the new node and any (possibly new) users onto the worklist.
695 AddToWorkList(TLO.New.getNode());
696 AddUsersToWorkList(TLO.New.getNode());
698 // Finally, if the node is now dead, remove it from the graph. The node
699 // may not be dead if the replacement process recursively simplified to
700 // something else needing this node.
701 if (TLO.Old.getNode()->use_empty()) {
702 removeFromWorkList(TLO.Old.getNode());
704 // If the operands of this node are only used by the node, they will now
705 // be dead. Make sure to visit them first to delete dead nodes early.
706 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
707 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
708 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
710 DAG.DeleteNode(TLO.Old.getNode());
714 /// SimplifyDemandedBits - Check the specified integer node value to see if
715 /// it can be simplified or if things it uses can be simplified by bit
716 /// propagation. If so, return true.
717 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
718 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
719 APInt KnownZero, KnownOne;
720 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
724 AddToWorkList(Op.getNode());
726 // Replace the old value with the new one.
728 DEBUG(dbgs() << "\nReplacing.2 ";
729 TLO.Old.getNode()->dump(&DAG);
730 dbgs() << "\nWith: ";
731 TLO.New.getNode()->dump(&DAG);
734 CommitTargetLoweringOpt(TLO);
738 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
740 EVT VT = Load->getValueType(0);
741 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
743 DEBUG(dbgs() << "\nReplacing.9 ";
745 dbgs() << "\nWith: ";
746 Trunc.getNode()->dump(&DAG);
748 WorkListRemover DeadNodes(*this);
749 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
750 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
751 removeFromWorkList(Load);
752 DAG.DeleteNode(Load);
753 AddToWorkList(Trunc.getNode());
756 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
760 EVT MemVT = LD->getMemoryVT();
761 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
762 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
764 : LD->getExtensionType();
766 return DAG.getExtLoad(ExtType, dl, PVT,
767 LD->getChain(), LD->getBasePtr(),
768 MemVT, LD->getMemOperand());
771 unsigned Opc = Op.getOpcode();
774 case ISD::AssertSext:
775 return DAG.getNode(ISD::AssertSext, dl, PVT,
776 SExtPromoteOperand(Op.getOperand(0), PVT),
778 case ISD::AssertZext:
779 return DAG.getNode(ISD::AssertZext, dl, PVT,
780 ZExtPromoteOperand(Op.getOperand(0), PVT),
782 case ISD::Constant: {
784 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
785 return DAG.getNode(ExtOpc, dl, PVT, Op);
789 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
791 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
794 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
795 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
797 EVT OldVT = Op.getValueType();
799 bool Replace = false;
800 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
801 if (NewOp.getNode() == 0)
803 AddToWorkList(NewOp.getNode());
806 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
807 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
808 DAG.getValueType(OldVT));
811 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
812 EVT OldVT = Op.getValueType();
814 bool Replace = false;
815 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
816 if (NewOp.getNode() == 0)
818 AddToWorkList(NewOp.getNode());
821 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
822 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
825 /// PromoteIntBinOp - Promote the specified integer binary operation if the
826 /// target indicates it is beneficial. e.g. On x86, it's usually better to
827 /// promote i16 operations to i32 since i16 instructions are longer.
828 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
829 if (!LegalOperations)
832 EVT VT = Op.getValueType();
833 if (VT.isVector() || !VT.isInteger())
836 // If operation type is 'undesirable', e.g. i16 on x86, consider
838 unsigned Opc = Op.getOpcode();
839 if (TLI.isTypeDesirableForOp(Opc, VT))
843 // Consult target whether it is a good idea to promote this operation and
844 // what's the right type to promote it to.
845 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
846 assert(PVT != VT && "Don't know what type to promote to!");
848 bool Replace0 = false;
849 SDValue N0 = Op.getOperand(0);
850 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
851 if (NN0.getNode() == 0)
854 bool Replace1 = false;
855 SDValue N1 = Op.getOperand(1);
860 NN1 = PromoteOperand(N1, PVT, Replace1);
861 if (NN1.getNode() == 0)
865 AddToWorkList(NN0.getNode());
867 AddToWorkList(NN1.getNode());
870 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
872 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
874 DEBUG(dbgs() << "\nPromoting ";
875 Op.getNode()->dump(&DAG));
877 return DAG.getNode(ISD::TRUNCATE, dl, VT,
878 DAG.getNode(Opc, dl, PVT, NN0, NN1));
883 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
884 /// target indicates it is beneficial. e.g. On x86, it's usually better to
885 /// promote i16 operations to i32 since i16 instructions are longer.
886 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
887 if (!LegalOperations)
890 EVT VT = Op.getValueType();
891 if (VT.isVector() || !VT.isInteger())
894 // If operation type is 'undesirable', e.g. i16 on x86, consider
896 unsigned Opc = Op.getOpcode();
897 if (TLI.isTypeDesirableForOp(Opc, VT))
901 // Consult target whether it is a good idea to promote this operation and
902 // what's the right type to promote it to.
903 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
904 assert(PVT != VT && "Don't know what type to promote to!");
906 bool Replace = false;
907 SDValue N0 = Op.getOperand(0);
909 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
910 else if (Opc == ISD::SRL)
911 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
913 N0 = PromoteOperand(N0, PVT, Replace);
914 if (N0.getNode() == 0)
917 AddToWorkList(N0.getNode());
919 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
921 DEBUG(dbgs() << "\nPromoting ";
922 Op.getNode()->dump(&DAG));
924 return DAG.getNode(ISD::TRUNCATE, dl, VT,
925 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
930 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
931 if (!LegalOperations)
934 EVT VT = Op.getValueType();
935 if (VT.isVector() || !VT.isInteger())
938 // If operation type is 'undesirable', e.g. i16 on x86, consider
940 unsigned Opc = Op.getOpcode();
941 if (TLI.isTypeDesirableForOp(Opc, VT))
945 // Consult target whether it is a good idea to promote this operation and
946 // what's the right type to promote it to.
947 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
948 assert(PVT != VT && "Don't know what type to promote to!");
949 // fold (aext (aext x)) -> (aext x)
950 // fold (aext (zext x)) -> (zext x)
951 // fold (aext (sext x)) -> (sext x)
952 DEBUG(dbgs() << "\nPromoting ";
953 Op.getNode()->dump(&DAG));
954 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
959 bool DAGCombiner::PromoteLoad(SDValue Op) {
960 if (!LegalOperations)
963 EVT VT = Op.getValueType();
964 if (VT.isVector() || !VT.isInteger())
967 // If operation type is 'undesirable', e.g. i16 on x86, consider
969 unsigned Opc = Op.getOpcode();
970 if (TLI.isTypeDesirableForOp(Opc, VT))
974 // Consult target whether it is a good idea to promote this operation and
975 // what's the right type to promote it to.
976 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
977 assert(PVT != VT && "Don't know what type to promote to!");
980 SDNode *N = Op.getNode();
981 LoadSDNode *LD = cast<LoadSDNode>(N);
982 EVT MemVT = LD->getMemoryVT();
983 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
984 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
986 : LD->getExtensionType();
987 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
988 LD->getChain(), LD->getBasePtr(),
989 MemVT, LD->getMemOperand());
990 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
992 DEBUG(dbgs() << "\nPromoting ";
995 Result.getNode()->dump(&DAG);
997 WorkListRemover DeadNodes(*this);
998 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
999 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1000 removeFromWorkList(N);
1002 AddToWorkList(Result.getNode());
1009 //===----------------------------------------------------------------------===//
1010 // Main DAG Combiner implementation
1011 //===----------------------------------------------------------------------===//
1013 void DAGCombiner::Run(CombineLevel AtLevel) {
1014 // set the instance variables, so that the various visit routines may use it.
1016 LegalOperations = Level >= AfterLegalizeVectorOps;
1017 LegalTypes = Level >= AfterLegalizeTypes;
1019 // Add all the dag nodes to the worklist.
1020 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1021 E = DAG.allnodes_end(); I != E; ++I)
1024 // Create a dummy node (which is not added to allnodes), that adds a reference
1025 // to the root node, preventing it from being deleted, and tracking any
1026 // changes of the root.
1027 HandleSDNode Dummy(DAG.getRoot());
1029 // The root of the dag may dangle to deleted nodes until the dag combiner is
1030 // done. Set it to null to avoid confusion.
1031 DAG.setRoot(SDValue());
1033 // while the worklist isn't empty, find a node and
1034 // try and combine it.
1035 while (!WorkListContents.empty()) {
1037 // The WorkListOrder holds the SDNodes in order, but it may contain
1039 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1040 // worklist *should* contain, and check the node we want to visit is should
1041 // actually be visited.
1043 N = WorkListOrder.pop_back_val();
1044 } while (!WorkListContents.erase(N));
1046 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1047 // N is deleted from the DAG, since they too may now be dead or may have a
1048 // reduced number of uses, allowing other xforms.
1049 if (N->use_empty() && N != &Dummy) {
1050 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1051 AddToWorkList(N->getOperand(i).getNode());
1057 SDValue RV = combine(N);
1059 if (RV.getNode() == 0)
1064 // If we get back the same node we passed in, rather than a new node or
1065 // zero, we know that the node must have defined multiple values and
1066 // CombineTo was used. Since CombineTo takes care of the worklist
1067 // mechanics for us, we have no work to do in this case.
1068 if (RV.getNode() == N)
1071 assert(N->getOpcode() != ISD::DELETED_NODE &&
1072 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1073 "Node was deleted but visit returned new node!");
1075 DEBUG(dbgs() << "\nReplacing.3 ";
1077 dbgs() << "\nWith: ";
1078 RV.getNode()->dump(&DAG);
1081 // Transfer debug value.
1082 DAG.TransferDbgValues(SDValue(N, 0), RV);
1083 WorkListRemover DeadNodes(*this);
1084 if (N->getNumValues() == RV.getNode()->getNumValues())
1085 DAG.ReplaceAllUsesWith(N, RV.getNode());
1087 assert(N->getValueType(0) == RV.getValueType() &&
1088 N->getNumValues() == 1 && "Type mismatch");
1090 DAG.ReplaceAllUsesWith(N, &OpV);
1093 // Push the new node and any users onto the worklist
1094 AddToWorkList(RV.getNode());
1095 AddUsersToWorkList(RV.getNode());
1097 // Add any uses of the old node to the worklist in case this node is the
1098 // last one that uses them. They may become dead after this node is
1100 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1101 AddToWorkList(N->getOperand(i).getNode());
1103 // Finally, if the node is now dead, remove it from the graph. The node
1104 // may not be dead if the replacement process recursively simplified to
1105 // something else needing this node.
1106 if (N->use_empty()) {
1107 // Nodes can be reintroduced into the worklist. Make sure we do not
1108 // process a node that has been replaced.
1109 removeFromWorkList(N);
1111 // Finally, since the node is now dead, remove it from the graph.
1116 // If the root changed (e.g. it was a dead load, update the root).
1117 DAG.setRoot(Dummy.getValue());
1118 DAG.RemoveDeadNodes();
1121 SDValue DAGCombiner::visit(SDNode *N) {
1122 switch (N->getOpcode()) {
1124 case ISD::TokenFactor: return visitTokenFactor(N);
1125 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1126 case ISD::ADD: return visitADD(N);
1127 case ISD::SUB: return visitSUB(N);
1128 case ISD::ADDC: return visitADDC(N);
1129 case ISD::SUBC: return visitSUBC(N);
1130 case ISD::ADDE: return visitADDE(N);
1131 case ISD::SUBE: return visitSUBE(N);
1132 case ISD::MUL: return visitMUL(N);
1133 case ISD::SDIV: return visitSDIV(N);
1134 case ISD::UDIV: return visitUDIV(N);
1135 case ISD::SREM: return visitSREM(N);
1136 case ISD::UREM: return visitUREM(N);
1137 case ISD::MULHU: return visitMULHU(N);
1138 case ISD::MULHS: return visitMULHS(N);
1139 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1140 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1141 case ISD::SMULO: return visitSMULO(N);
1142 case ISD::UMULO: return visitUMULO(N);
1143 case ISD::SDIVREM: return visitSDIVREM(N);
1144 case ISD::UDIVREM: return visitUDIVREM(N);
1145 case ISD::AND: return visitAND(N);
1146 case ISD::OR: return visitOR(N);
1147 case ISD::XOR: return visitXOR(N);
1148 case ISD::SHL: return visitSHL(N);
1149 case ISD::SRA: return visitSRA(N);
1150 case ISD::SRL: return visitSRL(N);
1151 case ISD::CTLZ: return visitCTLZ(N);
1152 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1153 case ISD::CTTZ: return visitCTTZ(N);
1154 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1155 case ISD::CTPOP: return visitCTPOP(N);
1156 case ISD::SELECT: return visitSELECT(N);
1157 case ISD::VSELECT: return visitVSELECT(N);
1158 case ISD::SELECT_CC: return visitSELECT_CC(N);
1159 case ISD::SETCC: return visitSETCC(N);
1160 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1161 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1162 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1163 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1164 case ISD::TRUNCATE: return visitTRUNCATE(N);
1165 case ISD::BITCAST: return visitBITCAST(N);
1166 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1167 case ISD::FADD: return visitFADD(N);
1168 case ISD::FSUB: return visitFSUB(N);
1169 case ISD::FMUL: return visitFMUL(N);
1170 case ISD::FMA: return visitFMA(N);
1171 case ISD::FDIV: return visitFDIV(N);
1172 case ISD::FREM: return visitFREM(N);
1173 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1174 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1175 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1176 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1177 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1178 case ISD::FP_ROUND: return visitFP_ROUND(N);
1179 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1180 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1181 case ISD::FNEG: return visitFNEG(N);
1182 case ISD::FABS: return visitFABS(N);
1183 case ISD::FFLOOR: return visitFFLOOR(N);
1184 case ISD::FCEIL: return visitFCEIL(N);
1185 case ISD::FTRUNC: return visitFTRUNC(N);
1186 case ISD::BRCOND: return visitBRCOND(N);
1187 case ISD::BR_CC: return visitBR_CC(N);
1188 case ISD::LOAD: return visitLOAD(N);
1189 case ISD::STORE: return visitSTORE(N);
1190 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1191 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1192 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1193 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1194 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1195 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1200 SDValue DAGCombiner::combine(SDNode *N) {
1201 SDValue RV = visit(N);
1203 // If nothing happened, try a target-specific DAG combine.
1204 if (RV.getNode() == 0) {
1205 assert(N->getOpcode() != ISD::DELETED_NODE &&
1206 "Node was deleted but visit returned NULL!");
1208 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1209 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1211 // Expose the DAG combiner to the target combiner impls.
1212 TargetLowering::DAGCombinerInfo
1213 DagCombineInfo(DAG, Level, false, this);
1215 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1219 // If nothing happened still, try promoting the operation.
1220 if (RV.getNode() == 0) {
1221 switch (N->getOpcode()) {
1229 RV = PromoteIntBinOp(SDValue(N, 0));
1234 RV = PromoteIntShiftOp(SDValue(N, 0));
1236 case ISD::SIGN_EXTEND:
1237 case ISD::ZERO_EXTEND:
1238 case ISD::ANY_EXTEND:
1239 RV = PromoteExtend(SDValue(N, 0));
1242 if (PromoteLoad(SDValue(N, 0)))
1248 // If N is a commutative binary node, try commuting it to enable more
1250 if (RV.getNode() == 0 &&
1251 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1252 N->getNumValues() == 1) {
1253 SDValue N0 = N->getOperand(0);
1254 SDValue N1 = N->getOperand(1);
1256 // Constant operands are canonicalized to RHS.
1257 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1258 SDValue Ops[] = { N1, N0 };
1259 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1262 return SDValue(CSENode, 0);
1269 /// getInputChainForNode - Given a node, return its input chain if it has one,
1270 /// otherwise return a null sd operand.
1271 static SDValue getInputChainForNode(SDNode *N) {
1272 if (unsigned NumOps = N->getNumOperands()) {
1273 if (N->getOperand(0).getValueType() == MVT::Other)
1274 return N->getOperand(0);
1275 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1276 return N->getOperand(NumOps-1);
1277 for (unsigned i = 1; i < NumOps-1; ++i)
1278 if (N->getOperand(i).getValueType() == MVT::Other)
1279 return N->getOperand(i);
1284 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1285 // If N has two operands, where one has an input chain equal to the other,
1286 // the 'other' chain is redundant.
1287 if (N->getNumOperands() == 2) {
1288 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1289 return N->getOperand(0);
1290 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1291 return N->getOperand(1);
1294 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1295 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1296 SmallPtrSet<SDNode*, 16> SeenOps;
1297 bool Changed = false; // If we should replace this token factor.
1299 // Start out with this token factor.
1302 // Iterate through token factors. The TFs grows when new token factors are
1304 for (unsigned i = 0; i < TFs.size(); ++i) {
1305 SDNode *TF = TFs[i];
1307 // Check each of the operands.
1308 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1309 SDValue Op = TF->getOperand(i);
1311 switch (Op.getOpcode()) {
1312 case ISD::EntryToken:
1313 // Entry tokens don't need to be added to the list. They are
1318 case ISD::TokenFactor:
1319 if (Op.hasOneUse() &&
1320 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1321 // Queue up for processing.
1322 TFs.push_back(Op.getNode());
1323 // Clean up in case the token factor is removed.
1324 AddToWorkList(Op.getNode());
1331 // Only add if it isn't already in the list.
1332 if (SeenOps.insert(Op.getNode()))
1343 // If we've change things around then replace token factor.
1346 // The entry token is the only possible outcome.
1347 Result = DAG.getEntryNode();
1349 // New and improved token factor.
1350 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1351 MVT::Other, &Ops[0], Ops.size());
1354 // Don't add users to work list.
1355 return CombineTo(N, Result, false);
1361 /// MERGE_VALUES can always be eliminated.
1362 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1363 WorkListRemover DeadNodes(*this);
1364 // Replacing results may cause a different MERGE_VALUES to suddenly
1365 // be CSE'd with N, and carry its uses with it. Iterate until no
1366 // uses remain, to ensure that the node can be safely deleted.
1367 // First add the users of this node to the work list so that they
1368 // can be tried again once they have new operands.
1369 AddUsersToWorkList(N);
1371 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1372 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1373 } while (!N->use_empty());
1374 removeFromWorkList(N);
1376 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1380 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1381 SelectionDAG &DAG) {
1382 EVT VT = N0.getValueType();
1383 SDValue N00 = N0.getOperand(0);
1384 SDValue N01 = N0.getOperand(1);
1385 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1387 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1388 isa<ConstantSDNode>(N00.getOperand(1))) {
1389 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1390 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1391 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1392 N00.getOperand(0), N01),
1393 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1394 N00.getOperand(1), N01));
1395 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1401 SDValue DAGCombiner::visitADD(SDNode *N) {
1402 SDValue N0 = N->getOperand(0);
1403 SDValue N1 = N->getOperand(1);
1404 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1405 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1406 EVT VT = N0.getValueType();
1409 if (VT.isVector()) {
1410 SDValue FoldedVOp = SimplifyVBinOp(N);
1411 if (FoldedVOp.getNode()) return FoldedVOp;
1413 // fold (add x, 0) -> x, vector edition
1414 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1416 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1420 // fold (add x, undef) -> undef
1421 if (N0.getOpcode() == ISD::UNDEF)
1423 if (N1.getOpcode() == ISD::UNDEF)
1425 // fold (add c1, c2) -> c1+c2
1427 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1428 // canonicalize constant to RHS
1430 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1431 // fold (add x, 0) -> x
1432 if (N1C && N1C->isNullValue())
1434 // fold (add Sym, c) -> Sym+c
1435 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1436 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1437 GA->getOpcode() == ISD::GlobalAddress)
1438 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1440 (uint64_t)N1C->getSExtValue());
1441 // fold ((c1-A)+c2) -> (c1+c2)-A
1442 if (N1C && N0.getOpcode() == ISD::SUB)
1443 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1444 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1445 DAG.getConstant(N1C->getAPIntValue()+
1446 N0C->getAPIntValue(), VT),
1449 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1450 if (RADD.getNode() != 0)
1452 // fold ((0-A) + B) -> B-A
1453 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1454 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1455 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1456 // fold (A + (0-B)) -> A-B
1457 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1458 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1459 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1460 // fold (A+(B-A)) -> B
1461 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1462 return N1.getOperand(0);
1463 // fold ((B-A)+A) -> B
1464 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1465 return N0.getOperand(0);
1466 // fold (A+(B-(A+C))) to (B-C)
1467 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1468 N0 == N1.getOperand(1).getOperand(0))
1469 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1470 N1.getOperand(1).getOperand(1));
1471 // fold (A+(B-(C+A))) to (B-C)
1472 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1473 N0 == N1.getOperand(1).getOperand(1))
1474 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1475 N1.getOperand(1).getOperand(0));
1476 // fold (A+((B-A)+or-C)) to (B+or-C)
1477 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1478 N1.getOperand(0).getOpcode() == ISD::SUB &&
1479 N0 == N1.getOperand(0).getOperand(1))
1480 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1481 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1483 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1484 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1485 SDValue N00 = N0.getOperand(0);
1486 SDValue N01 = N0.getOperand(1);
1487 SDValue N10 = N1.getOperand(0);
1488 SDValue N11 = N1.getOperand(1);
1490 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1491 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1492 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1493 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1496 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1497 return SDValue(N, 0);
1499 // fold (a+b) -> (a|b) iff a and b share no bits.
1500 if (VT.isInteger() && !VT.isVector()) {
1501 APInt LHSZero, LHSOne;
1502 APInt RHSZero, RHSOne;
1503 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1505 if (LHSZero.getBoolValue()) {
1506 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1508 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1509 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1510 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1511 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1515 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1516 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1517 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1518 if (Result.getNode()) return Result;
1520 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1521 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1522 if (Result.getNode()) return Result;
1525 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1526 if (N1.getOpcode() == ISD::SHL &&
1527 N1.getOperand(0).getOpcode() == ISD::SUB)
1528 if (ConstantSDNode *C =
1529 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1530 if (C->getAPIntValue() == 0)
1531 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1532 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1533 N1.getOperand(0).getOperand(1),
1535 if (N0.getOpcode() == ISD::SHL &&
1536 N0.getOperand(0).getOpcode() == ISD::SUB)
1537 if (ConstantSDNode *C =
1538 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1539 if (C->getAPIntValue() == 0)
1540 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1541 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1542 N0.getOperand(0).getOperand(1),
1545 if (N1.getOpcode() == ISD::AND) {
1546 SDValue AndOp0 = N1.getOperand(0);
1547 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1548 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1549 unsigned DestBits = VT.getScalarType().getSizeInBits();
1551 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1552 // and similar xforms where the inner op is either ~0 or 0.
1553 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1555 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1559 // add (sext i1), X -> sub X, (zext i1)
1560 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1561 N0.getOperand(0).getValueType() == MVT::i1 &&
1562 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1564 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1565 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1571 SDValue DAGCombiner::visitADDC(SDNode *N) {
1572 SDValue N0 = N->getOperand(0);
1573 SDValue N1 = N->getOperand(1);
1574 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1575 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1576 EVT VT = N0.getValueType();
1578 // If the flag result is dead, turn this into an ADD.
1579 if (!N->hasAnyUseOfValue(1))
1580 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1581 DAG.getNode(ISD::CARRY_FALSE,
1582 SDLoc(N), MVT::Glue));
1584 // canonicalize constant to RHS.
1586 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1588 // fold (addc x, 0) -> x + no carry out
1589 if (N1C && N1C->isNullValue())
1590 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1591 SDLoc(N), MVT::Glue));
1593 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1594 APInt LHSZero, LHSOne;
1595 APInt RHSZero, RHSOne;
1596 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1598 if (LHSZero.getBoolValue()) {
1599 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1601 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1602 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1603 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1604 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1605 DAG.getNode(ISD::CARRY_FALSE,
1606 SDLoc(N), MVT::Glue));
1612 SDValue DAGCombiner::visitADDE(SDNode *N) {
1613 SDValue N0 = N->getOperand(0);
1614 SDValue N1 = N->getOperand(1);
1615 SDValue CarryIn = N->getOperand(2);
1616 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1617 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1619 // canonicalize constant to RHS
1621 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1624 // fold (adde x, y, false) -> (addc x, y)
1625 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1626 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1631 // Since it may not be valid to emit a fold to zero for vector initializers
1632 // check if we can before folding.
1633 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1635 bool LegalOperations, bool LegalTypes) {
1637 return DAG.getConstant(0, VT);
1638 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1639 // Produce a vector of zeros.
1640 EVT ElemTy = VT.getVectorElementType();
1641 if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1642 TargetLowering::TypePromoteInteger)
1643 ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1644 assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1645 "Type for zero vector elements is not legal");
1646 SDValue El = DAG.getConstant(0, ElemTy);
1647 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1648 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1649 &Ops[0], Ops.size());
1654 SDValue DAGCombiner::visitSUB(SDNode *N) {
1655 SDValue N0 = N->getOperand(0);
1656 SDValue N1 = N->getOperand(1);
1657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1659 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1660 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1661 EVT VT = N0.getValueType();
1664 if (VT.isVector()) {
1665 SDValue FoldedVOp = SimplifyVBinOp(N);
1666 if (FoldedVOp.getNode()) return FoldedVOp;
1668 // fold (sub x, 0) -> x, vector edition
1669 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1673 // fold (sub x, x) -> 0
1674 // FIXME: Refactor this and xor and other similar operations together.
1676 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1677 // fold (sub c1, c2) -> c1-c2
1679 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1680 // fold (sub x, c) -> (add x, -c)
1682 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1683 DAG.getConstant(-N1C->getAPIntValue(), VT));
1684 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1685 if (N0C && N0C->isAllOnesValue())
1686 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1687 // fold A-(A-B) -> B
1688 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1689 return N1.getOperand(1);
1690 // fold (A+B)-A -> B
1691 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1692 return N0.getOperand(1);
1693 // fold (A+B)-B -> A
1694 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1695 return N0.getOperand(0);
1696 // fold C2-(A+C1) -> (C2-C1)-A
1697 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1698 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1703 // fold ((A+(B+or-C))-B) -> A+or-C
1704 if (N0.getOpcode() == ISD::ADD &&
1705 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1706 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1707 N0.getOperand(1).getOperand(0) == N1)
1708 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1709 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1710 // fold ((A+(C+B))-B) -> A+C
1711 if (N0.getOpcode() == ISD::ADD &&
1712 N0.getOperand(1).getOpcode() == ISD::ADD &&
1713 N0.getOperand(1).getOperand(1) == N1)
1714 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1715 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1716 // fold ((A-(B-C))-C) -> A-B
1717 if (N0.getOpcode() == ISD::SUB &&
1718 N0.getOperand(1).getOpcode() == ISD::SUB &&
1719 N0.getOperand(1).getOperand(1) == N1)
1720 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1721 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1723 // If either operand of a sub is undef, the result is undef
1724 if (N0.getOpcode() == ISD::UNDEF)
1726 if (N1.getOpcode() == ISD::UNDEF)
1729 // If the relocation model supports it, consider symbol offsets.
1730 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1731 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1732 // fold (sub Sym, c) -> Sym-c
1733 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1734 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1736 (uint64_t)N1C->getSExtValue());
1737 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1738 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1739 if (GA->getGlobal() == GB->getGlobal())
1740 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1747 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1748 SDValue N0 = N->getOperand(0);
1749 SDValue N1 = N->getOperand(1);
1750 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1751 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1752 EVT VT = N0.getValueType();
1754 // If the flag result is dead, turn this into an SUB.
1755 if (!N->hasAnyUseOfValue(1))
1756 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1757 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1760 // fold (subc x, x) -> 0 + no borrow
1762 return CombineTo(N, DAG.getConstant(0, VT),
1763 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1766 // fold (subc x, 0) -> x + no borrow
1767 if (N1C && N1C->isNullValue())
1768 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1771 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1772 if (N0C && N0C->isAllOnesValue())
1773 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1774 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1780 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1781 SDValue N0 = N->getOperand(0);
1782 SDValue N1 = N->getOperand(1);
1783 SDValue CarryIn = N->getOperand(2);
1785 // fold (sube x, y, false) -> (subc x, y)
1786 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1787 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1792 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1793 /// elements are all the same constant or undefined.
1794 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1795 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1800 unsigned SplatBitSize;
1802 EVT EltVT = N->getValueType(0).getVectorElementType();
1803 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1805 EltVT.getSizeInBits() >= SplatBitSize);
1808 SDValue DAGCombiner::visitMUL(SDNode *N) {
1809 SDValue N0 = N->getOperand(0);
1810 SDValue N1 = N->getOperand(1);
1811 EVT VT = N0.getValueType();
1813 // fold (mul x, undef) -> 0
1814 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1815 return DAG.getConstant(0, VT);
1817 bool N0IsConst = false;
1818 bool N1IsConst = false;
1819 APInt ConstValue0, ConstValue1;
1821 if (VT.isVector()) {
1822 SDValue FoldedVOp = SimplifyVBinOp(N);
1823 if (FoldedVOp.getNode()) return FoldedVOp;
1825 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1826 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1828 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1829 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1831 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1832 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1836 // fold (mul c1, c2) -> c1*c2
1837 if (N0IsConst && N1IsConst)
1838 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1840 // canonicalize constant to RHS
1841 if (N0IsConst && !N1IsConst)
1842 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1843 // fold (mul x, 0) -> 0
1844 if (N1IsConst && ConstValue1 == 0)
1846 // We require a splat of the entire scalar bit width for non-contiguous
1849 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1850 // fold (mul x, 1) -> x
1851 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1853 // fold (mul x, -1) -> 0-x
1854 if (N1IsConst && ConstValue1.isAllOnesValue())
1855 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1856 DAG.getConstant(0, VT), N0);
1857 // fold (mul x, (1 << c)) -> x << c
1858 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1859 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1860 DAG.getConstant(ConstValue1.logBase2(),
1861 getShiftAmountTy(N0.getValueType())));
1862 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1863 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1864 unsigned Log2Val = (-ConstValue1).logBase2();
1865 // FIXME: If the input is something that is easily negated (e.g. a
1866 // single-use add), we should put the negate there.
1867 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1868 DAG.getConstant(0, VT),
1869 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1870 DAG.getConstant(Log2Val,
1871 getShiftAmountTy(N0.getValueType()))));
1875 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1876 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1877 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1878 isa<ConstantSDNode>(N0.getOperand(1)))) {
1879 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1880 N1, N0.getOperand(1));
1881 AddToWorkList(C3.getNode());
1882 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1883 N0.getOperand(0), C3);
1886 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1889 SDValue Sh(0,0), Y(0,0);
1890 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1891 if (N0.getOpcode() == ISD::SHL &&
1892 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1893 isa<ConstantSDNode>(N0.getOperand(1))) &&
1894 N0.getNode()->hasOneUse()) {
1896 } else if (N1.getOpcode() == ISD::SHL &&
1897 isa<ConstantSDNode>(N1.getOperand(1)) &&
1898 N1.getNode()->hasOneUse()) {
1903 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1904 Sh.getOperand(0), Y);
1905 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1906 Mul, Sh.getOperand(1));
1910 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1911 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1912 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1913 isa<ConstantSDNode>(N0.getOperand(1))))
1914 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1915 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1916 N0.getOperand(0), N1),
1917 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1918 N0.getOperand(1), N1));
1921 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1922 if (RMUL.getNode() != 0)
1928 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1929 SDValue N0 = N->getOperand(0);
1930 SDValue N1 = N->getOperand(1);
1931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1932 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1933 EVT VT = N->getValueType(0);
1936 if (VT.isVector()) {
1937 SDValue FoldedVOp = SimplifyVBinOp(N);
1938 if (FoldedVOp.getNode()) return FoldedVOp;
1941 // fold (sdiv c1, c2) -> c1/c2
1942 if (N0C && N1C && !N1C->isNullValue())
1943 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1944 // fold (sdiv X, 1) -> X
1945 if (N1C && N1C->getAPIntValue() == 1LL)
1947 // fold (sdiv X, -1) -> 0-X
1948 if (N1C && N1C->isAllOnesValue())
1949 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1950 DAG.getConstant(0, VT), N0);
1951 // If we know the sign bits of both operands are zero, strength reduce to a
1952 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1953 if (!VT.isVector()) {
1954 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1955 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1958 // fold (sdiv X, pow2) -> simple ops after legalize
1959 if (N1C && !N1C->isNullValue() &&
1960 (N1C->getAPIntValue().isPowerOf2() ||
1961 (-N1C->getAPIntValue()).isPowerOf2())) {
1962 // If dividing by powers of two is cheap, then don't perform the following
1964 if (TLI.isPow2DivCheap())
1967 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1969 // Splat the sign bit into the register
1970 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1971 DAG.getConstant(VT.getSizeInBits()-1,
1972 getShiftAmountTy(N0.getValueType())));
1973 AddToWorkList(SGN.getNode());
1975 // Add (N0 < 0) ? abs2 - 1 : 0;
1976 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1977 DAG.getConstant(VT.getSizeInBits() - lg2,
1978 getShiftAmountTy(SGN.getValueType())));
1979 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1980 AddToWorkList(SRL.getNode());
1981 AddToWorkList(ADD.getNode()); // Divide by pow2
1982 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1983 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1985 // If we're dividing by a positive value, we're done. Otherwise, we must
1986 // negate the result.
1987 if (N1C->getAPIntValue().isNonNegative())
1990 AddToWorkList(SRA.getNode());
1991 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1992 DAG.getConstant(0, VT), SRA);
1995 // if integer divide is expensive and we satisfy the requirements, emit an
1996 // alternate sequence.
1997 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1998 SDValue Op = BuildSDIV(N);
1999 if (Op.getNode()) return Op;
2003 if (N0.getOpcode() == ISD::UNDEF)
2004 return DAG.getConstant(0, VT);
2005 // X / undef -> undef
2006 if (N1.getOpcode() == ISD::UNDEF)
2012 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2013 SDValue N0 = N->getOperand(0);
2014 SDValue N1 = N->getOperand(1);
2015 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2016 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2017 EVT VT = N->getValueType(0);
2020 if (VT.isVector()) {
2021 SDValue FoldedVOp = SimplifyVBinOp(N);
2022 if (FoldedVOp.getNode()) return FoldedVOp;
2025 // fold (udiv c1, c2) -> c1/c2
2026 if (N0C && N1C && !N1C->isNullValue())
2027 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2028 // fold (udiv x, (1 << c)) -> x >>u c
2029 if (N1C && N1C->getAPIntValue().isPowerOf2())
2030 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2031 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2032 getShiftAmountTy(N0.getValueType())));
2033 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2034 if (N1.getOpcode() == ISD::SHL) {
2035 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2036 if (SHC->getAPIntValue().isPowerOf2()) {
2037 EVT ADDVT = N1.getOperand(1).getValueType();
2038 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2040 DAG.getConstant(SHC->getAPIntValue()
2043 AddToWorkList(Add.getNode());
2044 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2048 // fold (udiv x, c) -> alternate
2049 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2050 SDValue Op = BuildUDIV(N);
2051 if (Op.getNode()) return Op;
2055 if (N0.getOpcode() == ISD::UNDEF)
2056 return DAG.getConstant(0, VT);
2057 // X / undef -> undef
2058 if (N1.getOpcode() == ISD::UNDEF)
2064 SDValue DAGCombiner::visitSREM(SDNode *N) {
2065 SDValue N0 = N->getOperand(0);
2066 SDValue N1 = N->getOperand(1);
2067 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2068 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2069 EVT VT = N->getValueType(0);
2071 // fold (srem c1, c2) -> c1%c2
2072 if (N0C && N1C && !N1C->isNullValue())
2073 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2074 // If we know the sign bits of both operands are zero, strength reduce to a
2075 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2076 if (!VT.isVector()) {
2077 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2078 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2081 // If X/C can be simplified by the division-by-constant logic, lower
2082 // X%C to the equivalent of X-X/C*C.
2083 if (N1C && !N1C->isNullValue()) {
2084 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2085 AddToWorkList(Div.getNode());
2086 SDValue OptimizedDiv = combine(Div.getNode());
2087 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2088 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2090 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2091 AddToWorkList(Mul.getNode());
2097 if (N0.getOpcode() == ISD::UNDEF)
2098 return DAG.getConstant(0, VT);
2099 // X % undef -> undef
2100 if (N1.getOpcode() == ISD::UNDEF)
2106 SDValue DAGCombiner::visitUREM(SDNode *N) {
2107 SDValue N0 = N->getOperand(0);
2108 SDValue N1 = N->getOperand(1);
2109 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2110 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2111 EVT VT = N->getValueType(0);
2113 // fold (urem c1, c2) -> c1%c2
2114 if (N0C && N1C && !N1C->isNullValue())
2115 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2116 // fold (urem x, pow2) -> (and x, pow2-1)
2117 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2118 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2119 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2120 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2121 if (N1.getOpcode() == ISD::SHL) {
2122 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2123 if (SHC->getAPIntValue().isPowerOf2()) {
2125 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2126 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2128 AddToWorkList(Add.getNode());
2129 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2134 // If X/C can be simplified by the division-by-constant logic, lower
2135 // X%C to the equivalent of X-X/C*C.
2136 if (N1C && !N1C->isNullValue()) {
2137 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2138 AddToWorkList(Div.getNode());
2139 SDValue OptimizedDiv = combine(Div.getNode());
2140 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2141 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2143 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2144 AddToWorkList(Mul.getNode());
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X % undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2159 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
2162 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2163 EVT VT = N->getValueType(0);
2166 // fold (mulhs x, 0) -> 0
2167 if (N1C && N1C->isNullValue())
2169 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2170 if (N1C && N1C->getAPIntValue() == 1)
2171 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2172 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2173 getShiftAmountTy(N0.getValueType())));
2174 // fold (mulhs x, undef) -> 0
2175 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2176 return DAG.getConstant(0, VT);
2178 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2180 if (VT.isSimple() && !VT.isVector()) {
2181 MVT Simple = VT.getSimpleVT();
2182 unsigned SimpleSize = Simple.getSizeInBits();
2183 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2184 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2185 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2186 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2187 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2188 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2189 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2190 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2197 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2198 SDValue N0 = N->getOperand(0);
2199 SDValue N1 = N->getOperand(1);
2200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2201 EVT VT = N->getValueType(0);
2204 // fold (mulhu x, 0) -> 0
2205 if (N1C && N1C->isNullValue())
2207 // fold (mulhu x, 1) -> 0
2208 if (N1C && N1C->getAPIntValue() == 1)
2209 return DAG.getConstant(0, N0.getValueType());
2210 // fold (mulhu x, undef) -> 0
2211 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2212 return DAG.getConstant(0, VT);
2214 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2216 if (VT.isSimple() && !VT.isVector()) {
2217 MVT Simple = VT.getSimpleVT();
2218 unsigned SimpleSize = Simple.getSizeInBits();
2219 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2220 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2221 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2222 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2223 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2224 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2225 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2226 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2233 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2234 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2235 /// that are being performed. Return true if a simplification was made.
2237 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2239 // If the high half is not needed, just compute the low half.
2240 bool HiExists = N->hasAnyUseOfValue(1);
2242 (!LegalOperations ||
2243 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2244 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2245 N->op_begin(), N->getNumOperands());
2246 return CombineTo(N, Res, Res);
2249 // If the low half is not needed, just compute the high half.
2250 bool LoExists = N->hasAnyUseOfValue(0);
2252 (!LegalOperations ||
2253 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2254 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2255 N->op_begin(), N->getNumOperands());
2256 return CombineTo(N, Res, Res);
2259 // If both halves are used, return as it is.
2260 if (LoExists && HiExists)
2263 // If the two computed results can be simplified separately, separate them.
2265 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2266 N->op_begin(), N->getNumOperands());
2267 AddToWorkList(Lo.getNode());
2268 SDValue LoOpt = combine(Lo.getNode());
2269 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2270 (!LegalOperations ||
2271 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2272 return CombineTo(N, LoOpt, LoOpt);
2276 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2277 N->op_begin(), N->getNumOperands());
2278 AddToWorkList(Hi.getNode());
2279 SDValue HiOpt = combine(Hi.getNode());
2280 if (HiOpt.getNode() && HiOpt != Hi &&
2281 (!LegalOperations ||
2282 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2283 return CombineTo(N, HiOpt, HiOpt);
2289 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2290 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2291 if (Res.getNode()) return Res;
2293 EVT VT = N->getValueType(0);
2296 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2298 if (VT.isSimple() && !VT.isVector()) {
2299 MVT Simple = VT.getSimpleVT();
2300 unsigned SimpleSize = Simple.getSizeInBits();
2301 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2302 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2303 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2304 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2305 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2306 // Compute the high part as N1.
2307 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2308 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2309 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2310 // Compute the low part as N0.
2311 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2312 return CombineTo(N, Lo, Hi);
2319 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2321 if (Res.getNode()) return Res;
2323 EVT VT = N->getValueType(0);
2326 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2328 if (VT.isSimple() && !VT.isVector()) {
2329 MVT Simple = VT.getSimpleVT();
2330 unsigned SimpleSize = Simple.getSizeInBits();
2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2334 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336 // Compute the high part as N1.
2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340 // Compute the low part as N0.
2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342 return CombineTo(N, Lo, Hi);
2349 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2350 // (smulo x, 2) -> (saddo x, x)
2351 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2352 if (C2->getAPIntValue() == 2)
2353 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2354 N->getOperand(0), N->getOperand(0));
2359 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2360 // (umulo x, 2) -> (uaddo x, x)
2361 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2362 if (C2->getAPIntValue() == 2)
2363 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2364 N->getOperand(0), N->getOperand(0));
2369 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2370 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2371 if (Res.getNode()) return Res;
2376 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2377 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2378 if (Res.getNode()) return Res;
2383 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2384 /// two operands of the same opcode, try to simplify it.
2385 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2386 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2387 EVT VT = N0.getValueType();
2388 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2390 // Bail early if none of these transforms apply.
2391 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2393 // For each of OP in AND/OR/XOR:
2394 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2395 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2396 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2397 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2399 // do not sink logical op inside of a vector extend, since it may combine
2401 EVT Op0VT = N0.getOperand(0).getValueType();
2402 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2403 N0.getOpcode() == ISD::SIGN_EXTEND ||
2404 // Avoid infinite looping with PromoteIntBinOp.
2405 (N0.getOpcode() == ISD::ANY_EXTEND &&
2406 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2407 (N0.getOpcode() == ISD::TRUNCATE &&
2408 (!TLI.isZExtFree(VT, Op0VT) ||
2409 !TLI.isTruncateFree(Op0VT, VT)) &&
2410 TLI.isTypeLegal(Op0VT))) &&
2412 Op0VT == N1.getOperand(0).getValueType() &&
2413 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2414 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2415 N0.getOperand(0).getValueType(),
2416 N0.getOperand(0), N1.getOperand(0));
2417 AddToWorkList(ORNode.getNode());
2418 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2421 // For each of OP in SHL/SRL/SRA/AND...
2422 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2423 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2424 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2425 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2426 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2427 N0.getOperand(1) == N1.getOperand(1)) {
2428 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2429 N0.getOperand(0).getValueType(),
2430 N0.getOperand(0), N1.getOperand(0));
2431 AddToWorkList(ORNode.getNode());
2432 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2433 ORNode, N0.getOperand(1));
2436 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2437 // Only perform this optimization after type legalization and before
2438 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2439 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2440 // we don't want to undo this promotion.
2441 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2443 if ((N0.getOpcode() == ISD::BITCAST ||
2444 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2445 Level == AfterLegalizeTypes) {
2446 SDValue In0 = N0.getOperand(0);
2447 SDValue In1 = N1.getOperand(0);
2448 EVT In0Ty = In0.getValueType();
2449 EVT In1Ty = In1.getValueType();
2451 // If both incoming values are integers, and the original types are the
2453 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2454 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2455 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2456 AddToWorkList(Op.getNode());
2461 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2462 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2463 // If both shuffles use the same mask, and both shuffle within a single
2464 // vector, then it is worthwhile to move the swizzle after the operation.
2465 // The type-legalizer generates this pattern when loading illegal
2466 // vector types from memory. In many cases this allows additional shuffle
2468 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2469 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2470 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2471 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2472 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2474 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2475 "Inputs to shuffles are not the same type");
2477 unsigned NumElts = VT.getVectorNumElements();
2479 // Check that both shuffles use the same mask. The masks are known to be of
2480 // the same length because the result vector type is the same.
2481 bool SameMask = true;
2482 for (unsigned i = 0; i != NumElts; ++i) {
2483 int Idx0 = SVN0->getMaskElt(i);
2484 int Idx1 = SVN1->getMaskElt(i);
2492 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2493 N0.getOperand(0), N1.getOperand(0));
2494 AddToWorkList(Op.getNode());
2495 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2496 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2503 SDValue DAGCombiner::visitAND(SDNode *N) {
2504 SDValue N0 = N->getOperand(0);
2505 SDValue N1 = N->getOperand(1);
2506 SDValue LL, LR, RL, RR, CC0, CC1;
2507 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2508 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2509 EVT VT = N1.getValueType();
2510 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2513 if (VT.isVector()) {
2514 SDValue FoldedVOp = SimplifyVBinOp(N);
2515 if (FoldedVOp.getNode()) return FoldedVOp;
2517 // fold (and x, 0) -> 0, vector edition
2518 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2520 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2523 // fold (and x, -1) -> x, vector edition
2524 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2526 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2530 // fold (and x, undef) -> 0
2531 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2532 return DAG.getConstant(0, VT);
2533 // fold (and c1, c2) -> c1&c2
2535 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2536 // canonicalize constant to RHS
2538 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2539 // fold (and x, -1) -> x
2540 if (N1C && N1C->isAllOnesValue())
2542 // if (and x, c) is known to be zero, return 0
2543 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2544 APInt::getAllOnesValue(BitWidth)))
2545 return DAG.getConstant(0, VT);
2547 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2548 if (RAND.getNode() != 0)
2550 // fold (and (or x, C), D) -> D if (C & D) == D
2551 if (N1C && N0.getOpcode() == ISD::OR)
2552 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2553 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2555 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2556 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2557 SDValue N0Op0 = N0.getOperand(0);
2558 APInt Mask = ~N1C->getAPIntValue();
2559 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2560 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2561 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2562 N0.getValueType(), N0Op0);
2564 // Replace uses of the AND with uses of the Zero extend node.
2567 // We actually want to replace all uses of the any_extend with the
2568 // zero_extend, to avoid duplicating things. This will later cause this
2569 // AND to be folded.
2570 CombineTo(N0.getNode(), Zext);
2571 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2574 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2575 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2576 // already be zero by virtue of the width of the base type of the load.
2578 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2580 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2581 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2582 N0.getOpcode() == ISD::LOAD) {
2583 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2584 N0 : N0.getOperand(0) );
2586 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2587 // This can be a pure constant or a vector splat, in which case we treat the
2588 // vector as a scalar and use the splat value.
2589 APInt Constant = APInt::getNullValue(1);
2590 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2591 Constant = C->getAPIntValue();
2592 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2593 APInt SplatValue, SplatUndef;
2594 unsigned SplatBitSize;
2596 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2597 SplatBitSize, HasAnyUndefs);
2599 // Undef bits can contribute to a possible optimisation if set, so
2601 SplatValue |= SplatUndef;
2603 // The splat value may be something like "0x00FFFFFF", which means 0 for
2604 // the first vector value and FF for the rest, repeating. We need a mask
2605 // that will apply equally to all members of the vector, so AND all the
2606 // lanes of the constant together.
2607 EVT VT = Vector->getValueType(0);
2608 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2610 // If the splat value has been compressed to a bitlength lower
2611 // than the size of the vector lane, we need to re-expand it to
2613 if (BitWidth > SplatBitSize)
2614 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2615 SplatBitSize < BitWidth;
2616 SplatBitSize = SplatBitSize * 2)
2617 SplatValue |= SplatValue.shl(SplatBitSize);
2619 Constant = APInt::getAllOnesValue(BitWidth);
2620 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2621 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2625 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2626 // actually legal and isn't going to get expanded, else this is a false
2628 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2629 Load->getMemoryVT());
2631 // Resize the constant to the same size as the original memory access before
2632 // extension. If it is still the AllOnesValue then this AND is completely
2635 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2638 switch (Load->getExtensionType()) {
2639 default: B = false; break;
2640 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2642 case ISD::NON_EXTLOAD: B = true; break;
2645 if (B && Constant.isAllOnesValue()) {
2646 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2647 // preserve semantics once we get rid of the AND.
2648 SDValue NewLoad(Load, 0);
2649 if (Load->getExtensionType() == ISD::EXTLOAD) {
2650 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2651 Load->getValueType(0), SDLoc(Load),
2652 Load->getChain(), Load->getBasePtr(),
2653 Load->getOffset(), Load->getMemoryVT(),
2654 Load->getMemOperand());
2655 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2656 if (Load->getNumValues() == 3) {
2657 // PRE/POST_INC loads have 3 values.
2658 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2659 NewLoad.getValue(2) };
2660 CombineTo(Load, To, 3, true);
2662 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2666 // Fold the AND away, taking care not to fold to the old load node if we
2668 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2670 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2673 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2674 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2675 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2676 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2678 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2679 LL.getValueType().isInteger()) {
2680 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2681 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2682 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2683 LR.getValueType(), LL, RL);
2684 AddToWorkList(ORNode.getNode());
2685 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2687 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2688 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2689 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2690 LR.getValueType(), LL, RL);
2691 AddToWorkList(ANDNode.getNode());
2692 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2694 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2695 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2696 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2697 LR.getValueType(), LL, RL);
2698 AddToWorkList(ORNode.getNode());
2699 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2702 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2703 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2704 Op0 == Op1 && LL.getValueType().isInteger() &&
2705 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2706 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2707 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2708 cast<ConstantSDNode>(RR)->isNullValue()))) {
2709 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2710 LL, DAG.getConstant(1, LL.getValueType()));
2711 AddToWorkList(ADDNode.getNode());
2712 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2713 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2715 // canonicalize equivalent to ll == rl
2716 if (LL == RR && LR == RL) {
2717 Op1 = ISD::getSetCCSwappedOperands(Op1);
2720 if (LL == RL && LR == RR) {
2721 bool isInteger = LL.getValueType().isInteger();
2722 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2723 if (Result != ISD::SETCC_INVALID &&
2724 (!LegalOperations ||
2725 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2726 TLI.isOperationLegal(ISD::SETCC,
2727 getSetCCResultType(N0.getSimpleValueType())))))
2728 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2733 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2734 if (N0.getOpcode() == N1.getOpcode()) {
2735 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2736 if (Tmp.getNode()) return Tmp;
2739 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2740 // fold (and (sra)) -> (and (srl)) when possible.
2741 if (!VT.isVector() &&
2742 SimplifyDemandedBits(SDValue(N, 0)))
2743 return SDValue(N, 0);
2745 // fold (zext_inreg (extload x)) -> (zextload x)
2746 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2747 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2748 EVT MemVT = LN0->getMemoryVT();
2749 // If we zero all the possible extended bits, then we can turn this into
2750 // a zextload if we are running before legalize or the operation is legal.
2751 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2752 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2753 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2754 ((!LegalOperations && !LN0->isVolatile()) ||
2755 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2756 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2757 LN0->getChain(), LN0->getBasePtr(),
2758 MemVT, LN0->getMemOperand());
2760 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2761 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2764 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2765 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2767 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2768 EVT MemVT = LN0->getMemoryVT();
2769 // If we zero all the possible extended bits, then we can turn this into
2770 // a zextload if we are running before legalize or the operation is legal.
2771 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2772 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2773 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2774 ((!LegalOperations && !LN0->isVolatile()) ||
2775 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2776 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2777 LN0->getChain(), LN0->getBasePtr(),
2778 MemVT, LN0->getMemOperand());
2780 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2781 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2785 // fold (and (load x), 255) -> (zextload x, i8)
2786 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2787 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2788 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2789 (N0.getOpcode() == ISD::ANY_EXTEND &&
2790 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2791 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2792 LoadSDNode *LN0 = HasAnyExt
2793 ? cast<LoadSDNode>(N0.getOperand(0))
2794 : cast<LoadSDNode>(N0);
2795 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2796 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2797 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2798 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2799 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2800 EVT LoadedVT = LN0->getMemoryVT();
2802 if (ExtVT == LoadedVT &&
2803 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2804 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2807 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2808 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2809 LN0->getMemOperand());
2811 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2812 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2815 // Do not change the width of a volatile load.
2816 // Do not generate loads of non-round integer types since these can
2817 // be expensive (and would be wrong if the type is not byte sized).
2818 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2819 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2820 EVT PtrType = LN0->getOperand(1).getValueType();
2822 unsigned Alignment = LN0->getAlignment();
2823 SDValue NewPtr = LN0->getBasePtr();
2825 // For big endian targets, we need to add an offset to the pointer
2826 // to load the correct bytes. For little endian systems, we merely
2827 // need to read fewer bytes from the same pointer.
2828 if (TLI.isBigEndian()) {
2829 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2830 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2831 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2832 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2833 NewPtr, DAG.getConstant(PtrOff, PtrType));
2834 Alignment = MinAlign(Alignment, PtrOff);
2837 AddToWorkList(NewPtr.getNode());
2839 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2841 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2842 LN0->getChain(), NewPtr,
2843 LN0->getPointerInfo(),
2844 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2845 Alignment, LN0->getTBAAInfo());
2847 CombineTo(LN0, Load, Load.getValue(1));
2848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2854 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2855 VT.getSizeInBits() <= 64) {
2856 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2857 APInt ADDC = ADDI->getAPIntValue();
2858 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2859 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2860 // immediate for an add, but it is legal if its top c2 bits are set,
2861 // transform the ADD so the immediate doesn't need to be materialized
2863 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2864 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2865 SRLI->getZExtValue());
2866 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2868 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2870 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2871 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2872 CombineTo(N0.getNode(), NewAdd);
2873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2881 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2882 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2883 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2884 N0.getOperand(1), false);
2885 if (BSwap.getNode())
2892 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2894 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2895 bool DemandHighBits) {
2896 if (!LegalOperations)
2899 EVT VT = N->getValueType(0);
2900 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2902 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2905 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2906 bool LookPassAnd0 = false;
2907 bool LookPassAnd1 = false;
2908 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2910 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2912 if (N0.getOpcode() == ISD::AND) {
2913 if (!N0.getNode()->hasOneUse())
2915 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2916 if (!N01C || N01C->getZExtValue() != 0xFF00)
2918 N0 = N0.getOperand(0);
2919 LookPassAnd0 = true;
2922 if (N1.getOpcode() == ISD::AND) {
2923 if (!N1.getNode()->hasOneUse())
2925 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2926 if (!N11C || N11C->getZExtValue() != 0xFF)
2928 N1 = N1.getOperand(0);
2929 LookPassAnd1 = true;
2932 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2934 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2936 if (!N0.getNode()->hasOneUse() ||
2937 !N1.getNode()->hasOneUse())
2940 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2941 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2944 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2947 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2948 SDValue N00 = N0->getOperand(0);
2949 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2950 if (!N00.getNode()->hasOneUse())
2952 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2953 if (!N001C || N001C->getZExtValue() != 0xFF)
2955 N00 = N00.getOperand(0);
2956 LookPassAnd0 = true;
2959 SDValue N10 = N1->getOperand(0);
2960 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2961 if (!N10.getNode()->hasOneUse())
2963 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2964 if (!N101C || N101C->getZExtValue() != 0xFF00)
2966 N10 = N10.getOperand(0);
2967 LookPassAnd1 = true;
2973 // Make sure everything beyond the low halfword gets set to zero since the SRL
2974 // 16 will clear the top bits.
2975 unsigned OpSizeInBits = VT.getSizeInBits();
2976 if (DemandHighBits && OpSizeInBits > 16) {
2977 // If the left-shift isn't masked out then the only way this is a bswap is
2978 // if all bits beyond the low 8 are 0. In that case the entire pattern
2979 // reduces to a left shift anyway: leave it for other parts of the combiner.
2983 // However, if the right shift isn't masked out then it might be because
2984 // it's not needed. See if we can spot that too.
2985 if (!LookPassAnd1 &&
2986 !DAG.MaskedValueIsZero(
2987 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2991 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2992 if (OpSizeInBits > 16)
2993 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2994 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2998 /// isBSwapHWordElement - Return true if the specified node is an element
2999 /// that makes up a 32-bit packed halfword byteswap. i.e.
3000 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3001 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3002 if (!N.getNode()->hasOneUse())
3005 unsigned Opc = N.getOpcode();
3006 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3014 switch (N1C->getZExtValue()) {
3017 case 0xFF: Num = 0; break;
3018 case 0xFF00: Num = 1; break;
3019 case 0xFF0000: Num = 2; break;
3020 case 0xFF000000: Num = 3; break;
3023 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3024 SDValue N0 = N.getOperand(0);
3025 if (Opc == ISD::AND) {
3026 if (Num == 0 || Num == 2) {
3028 // (x >> 8) & 0xff0000
3029 if (N0.getOpcode() != ISD::SRL)
3031 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3032 if (!C || C->getZExtValue() != 8)
3035 // (x << 8) & 0xff00
3036 // (x << 8) & 0xff000000
3037 if (N0.getOpcode() != ISD::SHL)
3039 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3040 if (!C || C->getZExtValue() != 8)
3043 } else if (Opc == ISD::SHL) {
3045 // (x & 0xff0000) << 8
3046 if (Num != 0 && Num != 2)
3048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3049 if (!C || C->getZExtValue() != 8)
3051 } else { // Opc == ISD::SRL
3052 // (x & 0xff00) >> 8
3053 // (x & 0xff000000) >> 8
3054 if (Num != 1 && Num != 3)
3056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3057 if (!C || C->getZExtValue() != 8)
3064 Parts[Num] = N0.getOperand(0).getNode();
3068 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3069 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3070 /// => (rotl (bswap x), 16)
3071 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3072 if (!LegalOperations)
3075 EVT VT = N->getValueType(0);
3078 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3081 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3083 // (or (or (and), (and)), (or (and), (and)))
3084 // (or (or (or (and), (and)), (and)), (and))
3085 if (N0.getOpcode() != ISD::OR)
3087 SDValue N00 = N0.getOperand(0);
3088 SDValue N01 = N0.getOperand(1);
3090 if (N1.getOpcode() == ISD::OR &&
3091 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3092 // (or (or (and), (and)), (or (and), (and)))
3093 SDValue N000 = N00.getOperand(0);
3094 if (!isBSwapHWordElement(N000, Parts))
3097 SDValue N001 = N00.getOperand(1);
3098 if (!isBSwapHWordElement(N001, Parts))
3100 SDValue N010 = N01.getOperand(0);
3101 if (!isBSwapHWordElement(N010, Parts))
3103 SDValue N011 = N01.getOperand(1);
3104 if (!isBSwapHWordElement(N011, Parts))
3107 // (or (or (or (and), (and)), (and)), (and))
3108 if (!isBSwapHWordElement(N1, Parts))
3110 if (!isBSwapHWordElement(N01, Parts))
3112 if (N00.getOpcode() != ISD::OR)
3114 SDValue N000 = N00.getOperand(0);
3115 if (!isBSwapHWordElement(N000, Parts))
3117 SDValue N001 = N00.getOperand(1);
3118 if (!isBSwapHWordElement(N001, Parts))
3122 // Make sure the parts are all coming from the same node.
3123 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3126 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3127 SDValue(Parts[0],0));
3129 // Result of the bswap should be rotated by 16. If it's not legal, then
3130 // do (x << 16) | (x >> 16).
3131 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3132 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3133 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3134 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3135 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3136 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3137 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3138 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3141 SDValue DAGCombiner::visitOR(SDNode *N) {
3142 SDValue N0 = N->getOperand(0);
3143 SDValue N1 = N->getOperand(1);
3144 SDValue LL, LR, RL, RR, CC0, CC1;
3145 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3147 EVT VT = N1.getValueType();
3150 if (VT.isVector()) {
3151 SDValue FoldedVOp = SimplifyVBinOp(N);
3152 if (FoldedVOp.getNode()) return FoldedVOp;
3154 // fold (or x, 0) -> x, vector edition
3155 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3157 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3160 // fold (or x, -1) -> -1, vector edition
3161 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3163 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3167 // fold (or x, undef) -> -1
3168 if (!LegalOperations &&
3169 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3170 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3171 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3173 // fold (or c1, c2) -> c1|c2
3175 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3176 // canonicalize constant to RHS
3178 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3179 // fold (or x, 0) -> x
3180 if (N1C && N1C->isNullValue())
3182 // fold (or x, -1) -> -1
3183 if (N1C && N1C->isAllOnesValue())
3185 // fold (or x, c) -> c iff (x & ~c) == 0
3186 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3189 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3190 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3191 if (BSwap.getNode() != 0)
3193 BSwap = MatchBSwapHWordLow(N, N0, N1);
3194 if (BSwap.getNode() != 0)
3198 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3199 if (ROR.getNode() != 0)
3201 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3202 // iff (c1 & c2) == 0.
3203 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3204 isa<ConstantSDNode>(N0.getOperand(1))) {
3205 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3206 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3207 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3208 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3209 N0.getOperand(0), N1),
3210 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3212 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3213 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3214 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3215 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3217 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3218 LL.getValueType().isInteger()) {
3219 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3220 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3221 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3222 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3223 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3224 LR.getValueType(), LL, RL);
3225 AddToWorkList(ORNode.getNode());
3226 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3228 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3229 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3230 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3231 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3232 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3233 LR.getValueType(), LL, RL);
3234 AddToWorkList(ANDNode.getNode());
3235 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3238 // canonicalize equivalent to ll == rl
3239 if (LL == RR && LR == RL) {
3240 Op1 = ISD::getSetCCSwappedOperands(Op1);
3243 if (LL == RL && LR == RR) {
3244 bool isInteger = LL.getValueType().isInteger();
3245 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3246 if (Result != ISD::SETCC_INVALID &&
3247 (!LegalOperations ||
3248 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3249 TLI.isOperationLegal(ISD::SETCC,
3250 getSetCCResultType(N0.getValueType())))))
3251 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3256 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3257 if (N0.getOpcode() == N1.getOpcode()) {
3258 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3259 if (Tmp.getNode()) return Tmp;
3262 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3263 if (N0.getOpcode() == ISD::AND &&
3264 N1.getOpcode() == ISD::AND &&
3265 N0.getOperand(1).getOpcode() == ISD::Constant &&
3266 N1.getOperand(1).getOpcode() == ISD::Constant &&
3267 // Don't increase # computations.
3268 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3269 // We can only do this xform if we know that bits from X that are set in C2
3270 // but not in C1 are already zero. Likewise for Y.
3271 const APInt &LHSMask =
3272 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3273 const APInt &RHSMask =
3274 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3276 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3277 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3278 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3279 N0.getOperand(0), N1.getOperand(0));
3280 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3281 DAG.getConstant(LHSMask | RHSMask, VT));
3285 // See if this is some rotate idiom.
3286 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3287 return SDValue(Rot, 0);
3289 // Simplify the operands using demanded-bits information.
3290 if (!VT.isVector() &&
3291 SimplifyDemandedBits(SDValue(N, 0)))
3292 return SDValue(N, 0);
3297 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3298 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3299 if (Op.getOpcode() == ISD::AND) {
3300 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3301 Mask = Op.getOperand(1);
3302 Op = Op.getOperand(0);
3308 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3316 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3317 // idioms for rotate, and if the target supports rotation instructions, generate
3319 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3320 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3321 EVT VT = LHS.getValueType();
3322 if (!TLI.isTypeLegal(VT)) return 0;
3324 // The target must have at least one rotate flavor.
3325 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3326 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3327 if (!HasROTL && !HasROTR) return 0;
3329 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3330 SDValue LHSShift; // The shift.
3331 SDValue LHSMask; // AND value if any.
3332 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3333 return 0; // Not part of a rotate.
3335 SDValue RHSShift; // The shift.
3336 SDValue RHSMask; // AND value if any.
3337 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3338 return 0; // Not part of a rotate.
3340 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3341 return 0; // Not shifting the same value.
3343 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3344 return 0; // Shifts must disagree.
3346 // Canonicalize shl to left side in a shl/srl pair.
3347 if (RHSShift.getOpcode() == ISD::SHL) {
3348 std::swap(LHS, RHS);
3349 std::swap(LHSShift, RHSShift);
3350 std::swap(LHSMask , RHSMask );
3353 unsigned OpSizeInBits = VT.getSizeInBits();
3354 SDValue LHSShiftArg = LHSShift.getOperand(0);
3355 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3356 SDValue RHSShiftArg = RHSShift.getOperand(0);
3357 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3359 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3360 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3361 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3362 RHSShiftAmt.getOpcode() == ISD::Constant) {
3363 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3364 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3365 if ((LShVal + RShVal) != OpSizeInBits)
3368 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3369 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3371 // If there is an AND of either shifted operand, apply it to the result.
3372 if (LHSMask.getNode() || RHSMask.getNode()) {
3373 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3375 if (LHSMask.getNode()) {
3376 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3377 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3379 if (RHSMask.getNode()) {
3380 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3381 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3384 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3387 return Rot.getNode();
3390 // If there is a mask here, and we have a variable shift, we can't be sure
3391 // that we're masking out the right stuff.
3392 if (LHSMask.getNode() || RHSMask.getNode())
3395 // If the shift amount is sign/zext/any-extended just peel it off.
3396 SDValue LExtOp0 = LHSShiftAmt;
3397 SDValue RExtOp0 = RHSShiftAmt;
3398 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3399 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3400 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3401 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3402 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3403 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3404 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3405 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3406 LExtOp0 = LHSShiftAmt.getOperand(0);
3407 RExtOp0 = RHSShiftAmt.getOperand(0);
3410 if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3411 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3413 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3414 // (rotr x, (sub 32, y))
3415 if (ConstantSDNode *SUBC =
3416 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3417 if (SUBC->getAPIntValue() == OpSizeInBits) {
3418 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3419 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3420 } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3421 LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3422 // fold (or (shl (*ext x), (*ext y)),
3423 // (srl (*ext x), (*ext (sub 32, y)))) ->
3424 // (*ext (rotl x, y))
3425 // fold (or (shl (*ext x), (*ext y)),
3426 // (srl (*ext x), (*ext (sub 32, y)))) ->
3427 // (*ext (rotr x, (sub 32, y)))
3428 SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3429 EVT LArgVT = LArgExtOp0.getValueType();
3430 bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT);
3431 bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT);
3432 if (HasROTRWithLArg || HasROTLWithLArg) {
3433 if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3435 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3436 LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3437 return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3442 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3443 RExtOp0 == LExtOp0.getOperand(1)) {
3444 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3446 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3447 // (rotl x, (sub 32, y))
3448 if (ConstantSDNode *SUBC =
3449 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3450 if (SUBC->getAPIntValue() == OpSizeInBits) {
3451 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3452 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3453 } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3454 RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3455 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3456 // (srl (*ext x), (*ext y))) ->
3457 // (*ext (rotl x, y))
3458 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3459 // (srl (*ext x), (*ext y))) ->
3460 // (*ext (rotr x, (sub 32, y)))
3461 SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3462 EVT RArgVT = RArgExtOp0.getValueType();
3463 bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT);
3464 bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT);
3465 if (HasROTRWithRArg || HasROTLWithRArg) {
3466 if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3468 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3469 RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3470 return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3480 SDValue DAGCombiner::visitXOR(SDNode *N) {
3481 SDValue N0 = N->getOperand(0);
3482 SDValue N1 = N->getOperand(1);
3483 SDValue LHS, RHS, CC;
3484 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3486 EVT VT = N0.getValueType();
3489 if (VT.isVector()) {
3490 SDValue FoldedVOp = SimplifyVBinOp(N);
3491 if (FoldedVOp.getNode()) return FoldedVOp;
3493 // fold (xor x, 0) -> x, vector edition
3494 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3496 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3500 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3501 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3502 return DAG.getConstant(0, VT);
3503 // fold (xor x, undef) -> undef
3504 if (N0.getOpcode() == ISD::UNDEF)
3506 if (N1.getOpcode() == ISD::UNDEF)
3508 // fold (xor c1, c2) -> c1^c2
3510 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3511 // canonicalize constant to RHS
3513 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3514 // fold (xor x, 0) -> x
3515 if (N1C && N1C->isNullValue())
3518 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3519 if (RXOR.getNode() != 0)
3522 // fold !(x cc y) -> (x !cc y)
3523 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3524 bool isInt = LHS.getValueType().isInteger();
3525 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3528 if (!LegalOperations ||
3529 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3530 switch (N0.getOpcode()) {
3532 llvm_unreachable("Unhandled SetCC Equivalent!");
3534 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3535 case ISD::SELECT_CC:
3536 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3537 N0.getOperand(3), NotCC);
3542 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3543 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3544 N0.getNode()->hasOneUse() &&
3545 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3546 SDValue V = N0.getOperand(0);
3547 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3548 DAG.getConstant(1, V.getValueType()));
3549 AddToWorkList(V.getNode());
3550 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3553 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3554 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3555 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3556 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3557 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3558 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3559 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3560 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3561 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3562 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3565 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3566 if (N1C && N1C->isAllOnesValue() &&
3567 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3568 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3569 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3570 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3571 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3572 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3573 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3574 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3577 // fold (xor (and x, y), y) -> (and (not x), y)
3578 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3579 N0->getOperand(1) == N1 && isTypeLegal(VT.getScalarType())) {
3580 SDValue X = N0->getOperand(0);
3581 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3582 AddToWorkList(NotX.getNode());
3583 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3585 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3586 if (N1C && N0.getOpcode() == ISD::XOR) {
3587 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3588 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3590 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3591 DAG.getConstant(N1C->getAPIntValue() ^
3592 N00C->getAPIntValue(), VT));
3594 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3595 DAG.getConstant(N1C->getAPIntValue() ^
3596 N01C->getAPIntValue(), VT));
3598 // fold (xor x, x) -> 0
3600 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3602 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3603 if (N0.getOpcode() == N1.getOpcode()) {
3604 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3605 if (Tmp.getNode()) return Tmp;
3608 // Simplify the expression using non-local knowledge.
3609 if (!VT.isVector() &&
3610 SimplifyDemandedBits(SDValue(N, 0)))
3611 return SDValue(N, 0);
3616 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3617 /// the shift amount is a constant.
3618 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3619 SDNode *LHS = N->getOperand(0).getNode();
3620 if (!LHS->hasOneUse()) return SDValue();
3622 // We want to pull some binops through shifts, so that we have (and (shift))
3623 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3624 // thing happens with address calculations, so it's important to canonicalize
3626 bool HighBitSet = false; // Can we transform this if the high bit is set?
3628 switch (LHS->getOpcode()) {
3629 default: return SDValue();
3632 HighBitSet = false; // We can only transform sra if the high bit is clear.
3635 HighBitSet = true; // We can only transform sra if the high bit is set.
3638 if (N->getOpcode() != ISD::SHL)
3639 return SDValue(); // only shl(add) not sr[al](add).
3640 HighBitSet = false; // We can only transform sra if the high bit is clear.
3644 // We require the RHS of the binop to be a constant as well.
3645 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3646 if (!BinOpCst) return SDValue();
3648 // FIXME: disable this unless the input to the binop is a shift by a constant.
3649 // If it is not a shift, it pessimizes some common cases like:
3651 // void foo(int *X, int i) { X[i & 1235] = 1; }
3652 // int bar(int *X, int i) { return X[i & 255]; }
3653 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3654 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3655 BinOpLHSVal->getOpcode() != ISD::SRA &&
3656 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3657 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3660 EVT VT = N->getValueType(0);
3662 // If this is a signed shift right, and the high bit is modified by the
3663 // logical operation, do not perform the transformation. The highBitSet
3664 // boolean indicates the value of the high bit of the constant which would
3665 // cause it to be modified for this operation.
3666 if (N->getOpcode() == ISD::SRA) {
3667 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3668 if (BinOpRHSSignSet != HighBitSet)
3672 // Fold the constants, shifting the binop RHS by the shift amount.
3673 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3675 LHS->getOperand(1), N->getOperand(1));
3677 // Create the new shift.
3678 SDValue NewShift = DAG.getNode(N->getOpcode(),
3679 SDLoc(LHS->getOperand(0)),
3680 VT, LHS->getOperand(0), N->getOperand(1));
3682 // Create the new binop.
3683 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3686 SDValue DAGCombiner::visitSHL(SDNode *N) {
3687 SDValue N0 = N->getOperand(0);
3688 SDValue N1 = N->getOperand(1);
3689 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3691 EVT VT = N0.getValueType();
3692 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3694 // fold (shl c1, c2) -> c1<<c2
3696 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3697 // fold (shl 0, x) -> 0
3698 if (N0C && N0C->isNullValue())
3700 // fold (shl x, c >= size(x)) -> undef
3701 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3702 return DAG.getUNDEF(VT);
3703 // fold (shl x, 0) -> x
3704 if (N1C && N1C->isNullValue())
3706 // fold (shl undef, x) -> 0
3707 if (N0.getOpcode() == ISD::UNDEF)
3708 return DAG.getConstant(0, VT);
3709 // if (shl x, c) is known to be zero, return 0
3710 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3711 APInt::getAllOnesValue(OpSizeInBits)))
3712 return DAG.getConstant(0, VT);
3713 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3714 if (N1.getOpcode() == ISD::TRUNCATE &&
3715 N1.getOperand(0).getOpcode() == ISD::AND &&
3716 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3717 SDValue N101 = N1.getOperand(0).getOperand(1);
3718 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3719 EVT TruncVT = N1.getValueType();
3720 SDValue N100 = N1.getOperand(0).getOperand(0);
3721 APInt TruncC = N101C->getAPIntValue();
3722 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3723 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3724 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3725 DAG.getNode(ISD::TRUNCATE,
3728 DAG.getConstant(TruncC, TruncVT)));
3732 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3733 return SDValue(N, 0);
3735 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3736 if (N1C && N0.getOpcode() == ISD::SHL &&
3737 N0.getOperand(1).getOpcode() == ISD::Constant) {
3738 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3739 uint64_t c2 = N1C->getZExtValue();
3740 if (c1 + c2 >= OpSizeInBits)
3741 return DAG.getConstant(0, VT);
3742 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3743 DAG.getConstant(c1 + c2, N1.getValueType()));
3746 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3747 // For this to be valid, the second form must not preserve any of the bits
3748 // that are shifted out by the inner shift in the first form. This means
3749 // the outer shift size must be >= the number of bits added by the ext.
3750 // As a corollary, we don't care what kind of ext it is.
3751 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3752 N0.getOpcode() == ISD::ANY_EXTEND ||
3753 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3754 N0.getOperand(0).getOpcode() == ISD::SHL &&
3755 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3757 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3758 uint64_t c2 = N1C->getZExtValue();
3759 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3760 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3761 if (c2 >= OpSizeInBits - InnerShiftSize) {
3762 if (c1 + c2 >= OpSizeInBits)
3763 return DAG.getConstant(0, VT);
3764 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3765 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3766 N0.getOperand(0)->getOperand(0)),
3767 DAG.getConstant(c1 + c2, N1.getValueType()));
3771 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3772 // Only fold this if the inner zext has no other uses to avoid increasing
3773 // the total number of instructions.
3774 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3775 N0.getOperand(0).getOpcode() == ISD::SRL &&
3776 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3778 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3779 if (c1 < VT.getSizeInBits()) {
3780 uint64_t c2 = N1C->getZExtValue();
3782 SDValue NewOp0 = N0.getOperand(0);
3783 EVT CountVT = NewOp0.getOperand(1).getValueType();
3784 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3785 NewOp0, DAG.getConstant(c2, CountVT));
3786 AddToWorkList(NewSHL.getNode());
3787 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3792 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3793 // (and (srl x, (sub c1, c2), MASK)
3794 // Only fold this if the inner shift has no other uses -- if it does, folding
3795 // this will increase the total number of instructions.
3796 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3797 N0.getOperand(1).getOpcode() == ISD::Constant) {
3798 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3799 if (c1 < VT.getSizeInBits()) {
3800 uint64_t c2 = N1C->getZExtValue();
3801 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3802 VT.getSizeInBits() - c1);
3805 Mask = Mask.shl(c2-c1);
3806 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3807 DAG.getConstant(c2-c1, N1.getValueType()));
3809 Mask = Mask.lshr(c1-c2);
3810 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3811 DAG.getConstant(c1-c2, N1.getValueType()));
3813 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3814 DAG.getConstant(Mask, VT));
3817 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3818 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3819 SDValue HiBitsMask =
3820 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3821 VT.getSizeInBits() -
3822 N1C->getZExtValue()),
3824 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3829 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3830 if (NewSHL.getNode())
3837 SDValue DAGCombiner::visitSRA(SDNode *N) {
3838 SDValue N0 = N->getOperand(0);
3839 SDValue N1 = N->getOperand(1);
3840 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3841 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3842 EVT VT = N0.getValueType();
3843 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3845 // fold (sra c1, c2) -> (sra c1, c2)
3847 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3848 // fold (sra 0, x) -> 0
3849 if (N0C && N0C->isNullValue())
3851 // fold (sra -1, x) -> -1
3852 if (N0C && N0C->isAllOnesValue())
3854 // fold (sra x, (setge c, size(x))) -> undef
3855 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3856 return DAG.getUNDEF(VT);
3857 // fold (sra x, 0) -> x
3858 if (N1C && N1C->isNullValue())
3860 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3862 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3863 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3864 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3866 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3867 ExtVT, VT.getVectorNumElements());
3868 if ((!LegalOperations ||
3869 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3870 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3871 N0.getOperand(0), DAG.getValueType(ExtVT));
3874 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3875 if (N1C && N0.getOpcode() == ISD::SRA) {
3876 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3877 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3878 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3879 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3880 DAG.getConstant(Sum, N1C->getValueType(0)));
3884 // fold (sra (shl X, m), (sub result_size, n))
3885 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3886 // result_size - n != m.
3887 // If truncate is free for the target sext(shl) is likely to result in better
3889 if (N0.getOpcode() == ISD::SHL) {
3890 // Get the two constanst of the shifts, CN0 = m, CN = n.
3891 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3893 // Determine what the truncate's result bitsize and type would be.
3895 EVT::getIntegerVT(*DAG.getContext(),
3896 OpSizeInBits - N1C->getZExtValue());
3897 // Determine the residual right-shift amount.
3898 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3900 // If the shift is not a no-op (in which case this should be just a sign
3901 // extend already), the truncated to type is legal, sign_extend is legal
3902 // on that type, and the truncate to that type is both legal and free,
3903 // perform the transform.
3904 if ((ShiftAmt > 0) &&
3905 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3906 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3907 TLI.isTruncateFree(VT, TruncVT)) {
3909 SDValue Amt = DAG.getConstant(ShiftAmt,
3910 getShiftAmountTy(N0.getOperand(0).getValueType()));
3911 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3912 N0.getOperand(0), Amt);
3913 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3915 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3916 N->getValueType(0), Trunc);
3921 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3922 if (N1.getOpcode() == ISD::TRUNCATE &&
3923 N1.getOperand(0).getOpcode() == ISD::AND &&
3924 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3925 SDValue N101 = N1.getOperand(0).getOperand(1);
3926 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3927 EVT TruncVT = N1.getValueType();
3928 SDValue N100 = N1.getOperand(0).getOperand(0);
3929 APInt TruncC = N101C->getAPIntValue();
3930 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3931 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3932 DAG.getNode(ISD::AND, SDLoc(N),
3934 DAG.getNode(ISD::TRUNCATE,
3937 DAG.getConstant(TruncC, TruncVT)));
3941 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3942 // if c1 is equal to the number of bits the trunc removes
3943 if (N0.getOpcode() == ISD::TRUNCATE &&
3944 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3945 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3946 N0.getOperand(0).hasOneUse() &&
3947 N0.getOperand(0).getOperand(1).hasOneUse() &&
3948 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3949 EVT LargeVT = N0.getOperand(0).getValueType();
3950 ConstantSDNode *LargeShiftAmt =
3951 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3953 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3954 LargeShiftAmt->getZExtValue()) {
3956 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3957 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3958 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3959 N0.getOperand(0).getOperand(0), Amt);
3960 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3964 // Simplify, based on bits shifted out of the LHS.
3965 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3966 return SDValue(N, 0);
3969 // If the sign bit is known to be zero, switch this to a SRL.
3970 if (DAG.SignBitIsZero(N0))
3971 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3974 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3975 if (NewSRA.getNode())
3982 SDValue DAGCombiner::visitSRL(SDNode *N) {
3983 SDValue N0 = N->getOperand(0);
3984 SDValue N1 = N->getOperand(1);
3985 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3986 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3987 EVT VT = N0.getValueType();
3988 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3990 // fold (srl c1, c2) -> c1 >>u c2
3992 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3993 // fold (srl 0, x) -> 0
3994 if (N0C && N0C->isNullValue())
3996 // fold (srl x, c >= size(x)) -> undef
3997 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3998 return DAG.getUNDEF(VT);
3999 // fold (srl x, 0) -> x
4000 if (N1C && N1C->isNullValue())
4002 // if (srl x, c) is known to be zero, return 0
4003 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4004 APInt::getAllOnesValue(OpSizeInBits)))
4005 return DAG.getConstant(0, VT);
4007 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4008 if (N1C && N0.getOpcode() == ISD::SRL &&
4009 N0.getOperand(1).getOpcode() == ISD::Constant) {
4010 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4011 uint64_t c2 = N1C->getZExtValue();
4012 if (c1 + c2 >= OpSizeInBits)
4013 return DAG.getConstant(0, VT);
4014 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4015 DAG.getConstant(c1 + c2, N1.getValueType()));
4018 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4019 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4020 N0.getOperand(0).getOpcode() == ISD::SRL &&
4021 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4023 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4024 uint64_t c2 = N1C->getZExtValue();
4025 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4026 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4027 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4028 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4029 if (c1 + OpSizeInBits == InnerShiftSize) {
4030 if (c1 + c2 >= InnerShiftSize)
4031 return DAG.getConstant(0, VT);
4032 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4033 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4034 N0.getOperand(0)->getOperand(0),
4035 DAG.getConstant(c1 + c2, ShiftCountVT)));
4039 // fold (srl (shl x, c), c) -> (and x, cst2)
4040 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4041 N0.getValueSizeInBits() <= 64) {
4042 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4043 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4044 DAG.getConstant(~0ULL >> ShAmt, VT));
4047 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4048 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4049 // Shifting in all undef bits?
4050 EVT SmallVT = N0.getOperand(0).getValueType();
4051 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4052 return DAG.getUNDEF(VT);
4054 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4055 uint64_t ShiftAmt = N1C->getZExtValue();
4056 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4058 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4059 AddToWorkList(SmallShift.getNode());
4060 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4061 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4062 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4063 DAG.getConstant(Mask, VT));
4067 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4068 // bit, which is unmodified by sra.
4069 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4070 if (N0.getOpcode() == ISD::SRA)
4071 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4074 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4075 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4076 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4077 APInt KnownZero, KnownOne;
4078 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4080 // If any of the input bits are KnownOne, then the input couldn't be all
4081 // zeros, thus the result of the srl will always be zero.
4082 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4084 // If all of the bits input the to ctlz node are known to be zero, then
4085 // the result of the ctlz is "32" and the result of the shift is one.
4086 APInt UnknownBits = ~KnownZero;
4087 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4089 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4090 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4091 // Okay, we know that only that the single bit specified by UnknownBits
4092 // could be set on input to the CTLZ node. If this bit is set, the SRL
4093 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4094 // to an SRL/XOR pair, which is likely to simplify more.
4095 unsigned ShAmt = UnknownBits.countTrailingZeros();
4096 SDValue Op = N0.getOperand(0);
4099 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4100 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4101 AddToWorkList(Op.getNode());
4104 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4105 Op, DAG.getConstant(1, VT));
4109 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4110 if (N1.getOpcode() == ISD::TRUNCATE &&
4111 N1.getOperand(0).getOpcode() == ISD::AND &&
4112 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4113 SDValue N101 = N1.getOperand(0).getOperand(1);
4114 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4115 EVT TruncVT = N1.getValueType();
4116 SDValue N100 = N1.getOperand(0).getOperand(0);
4117 APInt TruncC = N101C->getAPIntValue();
4118 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4119 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4120 DAG.getNode(ISD::AND, SDLoc(N),
4122 DAG.getNode(ISD::TRUNCATE,
4125 DAG.getConstant(TruncC, TruncVT)));
4129 // fold operands of srl based on knowledge that the low bits are not
4131 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4132 return SDValue(N, 0);
4135 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4136 if (NewSRL.getNode())
4140 // Attempt to convert a srl of a load into a narrower zero-extending load.
4141 SDValue NarrowLoad = ReduceLoadWidth(N);
4142 if (NarrowLoad.getNode())
4145 // Here is a common situation. We want to optimize:
4148 // %b = and i32 %a, 2
4149 // %c = srl i32 %b, 1
4150 // brcond i32 %c ...
4156 // %c = setcc eq %b, 0
4159 // However when after the source operand of SRL is optimized into AND, the SRL
4160 // itself may not be optimized further. Look for it and add the BRCOND into
4162 if (N->hasOneUse()) {
4163 SDNode *Use = *N->use_begin();
4164 if (Use->getOpcode() == ISD::BRCOND)
4166 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4167 // Also look pass the truncate.
4168 Use = *Use->use_begin();
4169 if (Use->getOpcode() == ISD::BRCOND)
4177 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4178 SDValue N0 = N->getOperand(0);
4179 EVT VT = N->getValueType(0);
4181 // fold (ctlz c1) -> c2
4182 if (isa<ConstantSDNode>(N0))
4183 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4187 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4188 SDValue N0 = N->getOperand(0);
4189 EVT VT = N->getValueType(0);
4191 // fold (ctlz_zero_undef c1) -> c2
4192 if (isa<ConstantSDNode>(N0))
4193 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4197 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4198 SDValue N0 = N->getOperand(0);
4199 EVT VT = N->getValueType(0);
4201 // fold (cttz c1) -> c2
4202 if (isa<ConstantSDNode>(N0))
4203 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4207 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4208 SDValue N0 = N->getOperand(0);
4209 EVT VT = N->getValueType(0);
4211 // fold (cttz_zero_undef c1) -> c2
4212 if (isa<ConstantSDNode>(N0))
4213 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4217 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4218 SDValue N0 = N->getOperand(0);
4219 EVT VT = N->getValueType(0);
4221 // fold (ctpop c1) -> c2
4222 if (isa<ConstantSDNode>(N0))
4223 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4227 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4228 SDValue N0 = N->getOperand(0);
4229 SDValue N1 = N->getOperand(1);
4230 SDValue N2 = N->getOperand(2);
4231 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4232 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4233 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4234 EVT VT = N->getValueType(0);
4235 EVT VT0 = N0.getValueType();
4237 // fold (select C, X, X) -> X
4240 // fold (select true, X, Y) -> X
4241 if (N0C && !N0C->isNullValue())
4243 // fold (select false, X, Y) -> Y
4244 if (N0C && N0C->isNullValue())
4246 // fold (select C, 1, X) -> (or C, X)
4247 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4248 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4249 // fold (select C, 0, 1) -> (xor C, 1)
4250 if (VT.isInteger() &&
4253 TLI.getBooleanContents(false) ==
4254 TargetLowering::ZeroOrOneBooleanContent)) &&
4255 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4258 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4259 N0, DAG.getConstant(1, VT0));
4260 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4261 N0, DAG.getConstant(1, VT0));
4262 AddToWorkList(XORNode.getNode());
4264 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4265 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4267 // fold (select C, 0, X) -> (and (not C), X)
4268 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4269 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4270 AddToWorkList(NOTNode.getNode());
4271 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4273 // fold (select C, X, 1) -> (or (not C), X)
4274 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4275 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4276 AddToWorkList(NOTNode.getNode());
4277 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4279 // fold (select C, X, 0) -> (and C, X)
4280 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4281 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4282 // fold (select X, X, Y) -> (or X, Y)
4283 // fold (select X, 1, Y) -> (or X, Y)
4284 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4285 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4286 // fold (select X, Y, X) -> (and X, Y)
4287 // fold (select X, Y, 0) -> (and X, Y)
4288 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4289 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4291 // If we can fold this based on the true/false value, do so.
4292 if (SimplifySelectOps(N, N1, N2))
4293 return SDValue(N, 0); // Don't revisit N.
4295 // fold selects based on a setcc into other things, such as min/max/abs
4296 if (N0.getOpcode() == ISD::SETCC) {
4298 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4299 // having to say they don't support SELECT_CC on every type the DAG knows
4300 // about, since there is no way to mark an opcode illegal at all value types
4301 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4302 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4303 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4304 N0.getOperand(0), N0.getOperand(1),
4305 N1, N2, N0.getOperand(2));
4306 return SimplifySelect(SDLoc(N), N0, N1, N2);
4312 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4313 SDValue N0 = N->getOperand(0);
4314 SDValue N1 = N->getOperand(1);
4315 SDValue N2 = N->getOperand(2);
4318 // Canonicalize integer abs.
4319 // vselect (setg[te] X, 0), X, -X ->
4320 // vselect (setgt X, -1), X, -X ->
4321 // vselect (setl[te] X, 0), -X, X ->
4322 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4323 if (N0.getOpcode() == ISD::SETCC) {
4324 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4325 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4327 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4329 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4330 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4331 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4332 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4333 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4334 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4335 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4338 EVT VT = LHS.getValueType();
4339 SDValue Shift = DAG.getNode(
4340 ISD::SRA, DL, VT, LHS,
4341 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4342 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4343 AddToWorkList(Shift.getNode());
4344 AddToWorkList(Add.getNode());
4345 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4349 // Treat SETCC as a vector mask and promote the result type based on the
4350 // targets expected SETCC result type. This will ensure that SETCC and VSELECT
4351 // are both split by the type legalizer. This is done to prevent the type
4352 // legalizer from unrolling SETCC into scalar comparions.
4353 EVT SelectVT = N->getValueType(0);
4354 EVT MaskVT = getSetCCResultType(SelectVT);
4355 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() != MaskVT) {
4358 // Extend the mask to the desired value type.
4359 ISD::NodeType ExtendCode =
4360 TargetLowering::getExtendForContent(TLI.getBooleanContents(true));
4361 SDValue Mask = DAG.getNode(ExtendCode, MaskDL, MaskVT, N0);
4363 AddToWorkList(Mask.getNode());
4365 SDValue LHS = N->getOperand(1);
4366 SDValue RHS = N->getOperand(2);
4368 return DAG.getNode(ISD::VSELECT, DL, SelectVT, Mask, LHS, RHS);
4374 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4375 SDValue N0 = N->getOperand(0);
4376 SDValue N1 = N->getOperand(1);
4377 SDValue N2 = N->getOperand(2);
4378 SDValue N3 = N->getOperand(3);
4379 SDValue N4 = N->getOperand(4);
4380 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4382 // fold select_cc lhs, rhs, x, x, cc -> x
4386 // Determine if the condition we're dealing with is constant
4387 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4388 N0, N1, CC, SDLoc(N), false);
4389 if (SCC.getNode()) {
4390 AddToWorkList(SCC.getNode());
4392 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4393 if (!SCCC->isNullValue())
4394 return N2; // cond always true -> true val
4396 return N3; // cond always false -> false val
4399 // Fold to a simpler select_cc
4400 if (SCC.getOpcode() == ISD::SETCC)
4401 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4402 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4406 // If we can fold this based on the true/false value, do so.
4407 if (SimplifySelectOps(N, N2, N3))
4408 return SDValue(N, 0); // Don't revisit N.
4410 // fold select_cc into other things, such as min/max/abs
4411 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4414 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4415 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4416 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4420 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4421 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4422 // transformation. Returns true if extension are possible and the above
4423 // mentioned transformation is profitable.
4424 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4426 SmallVectorImpl<SDNode *> &ExtendNodes,
4427 const TargetLowering &TLI) {
4428 bool HasCopyToRegUses = false;
4429 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4430 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4431 UE = N0.getNode()->use_end();
4436 if (UI.getUse().getResNo() != N0.getResNo())
4438 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4439 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4440 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4441 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4442 // Sign bits will be lost after a zext.
4445 for (unsigned i = 0; i != 2; ++i) {
4446 SDValue UseOp = User->getOperand(i);
4449 if (!isa<ConstantSDNode>(UseOp))
4454 ExtendNodes.push_back(User);
4457 // If truncates aren't free and there are users we can't
4458 // extend, it isn't worthwhile.
4461 // Remember if this value is live-out.
4462 if (User->getOpcode() == ISD::CopyToReg)
4463 HasCopyToRegUses = true;
4466 if (HasCopyToRegUses) {
4467 bool BothLiveOut = false;
4468 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4470 SDUse &Use = UI.getUse();
4471 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4477 // Both unextended and extended values are live out. There had better be
4478 // a good reason for the transformation.
4479 return ExtendNodes.size();
4484 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4485 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4486 ISD::NodeType ExtType) {
4487 // Extend SetCC uses if necessary.
4488 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4489 SDNode *SetCC = SetCCs[i];
4490 SmallVector<SDValue, 4> Ops;
4492 for (unsigned j = 0; j != 2; ++j) {
4493 SDValue SOp = SetCC->getOperand(j);
4495 Ops.push_back(ExtLoad);
4497 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4500 Ops.push_back(SetCC->getOperand(2));
4501 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4502 &Ops[0], Ops.size()));
4506 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4507 SDValue N0 = N->getOperand(0);
4508 EVT VT = N->getValueType(0);
4510 // fold (sext c1) -> c1
4511 if (isa<ConstantSDNode>(N0))
4512 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4514 // fold (sext (sext x)) -> (sext x)
4515 // fold (sext (aext x)) -> (sext x)
4516 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4517 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4520 if (N0.getOpcode() == ISD::TRUNCATE) {
4521 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4522 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4523 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4524 if (NarrowLoad.getNode()) {
4525 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4526 if (NarrowLoad.getNode() != N0.getNode()) {
4527 CombineTo(N0.getNode(), NarrowLoad);
4528 // CombineTo deleted the truncate, if needed, but not what's under it.
4531 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4534 // See if the value being truncated is already sign extended. If so, just
4535 // eliminate the trunc/sext pair.
4536 SDValue Op = N0.getOperand(0);
4537 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4538 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4539 unsigned DestBits = VT.getScalarType().getSizeInBits();
4540 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4542 if (OpBits == DestBits) {
4543 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4544 // bits, it is already ready.
4545 if (NumSignBits > DestBits-MidBits)
4547 } else if (OpBits < DestBits) {
4548 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4549 // bits, just sext from i32.
4550 if (NumSignBits > OpBits-MidBits)
4551 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4553 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4554 // bits, just truncate to i32.
4555 if (NumSignBits > OpBits-MidBits)
4556 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4559 // fold (sext (truncate x)) -> (sextinreg x).
4560 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4561 N0.getValueType())) {
4562 if (OpBits < DestBits)
4563 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4564 else if (OpBits > DestBits)
4565 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4566 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4567 DAG.getValueType(N0.getValueType()));
4571 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4572 // None of the supported targets knows how to perform load and sign extend
4573 // on vectors in one instruction. We only perform this transformation on
4575 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4576 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4577 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4578 bool DoXform = true;
4579 SmallVector<SDNode*, 4> SetCCs;
4580 if (!N0.hasOneUse())
4581 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4583 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4584 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4586 LN0->getBasePtr(), N0.getValueType(),
4587 LN0->getMemOperand());
4588 CombineTo(N, ExtLoad);
4589 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4590 N0.getValueType(), ExtLoad);
4591 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4592 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4594 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4598 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4599 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4600 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4601 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4602 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4603 EVT MemVT = LN0->getMemoryVT();
4604 if ((!LegalOperations && !LN0->isVolatile()) ||
4605 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4606 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4608 LN0->getBasePtr(), MemVT,
4609 LN0->getMemOperand());
4610 CombineTo(N, ExtLoad);
4611 CombineTo(N0.getNode(),
4612 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4613 N0.getValueType(), ExtLoad),
4614 ExtLoad.getValue(1));
4615 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4619 // fold (sext (and/or/xor (load x), cst)) ->
4620 // (and/or/xor (sextload x), (sext cst))
4621 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4622 N0.getOpcode() == ISD::XOR) &&
4623 isa<LoadSDNode>(N0.getOperand(0)) &&
4624 N0.getOperand(1).getOpcode() == ISD::Constant &&
4625 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4626 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4627 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4628 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4629 bool DoXform = true;
4630 SmallVector<SDNode*, 4> SetCCs;
4631 if (!N0.hasOneUse())
4632 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4635 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4636 LN0->getChain(), LN0->getBasePtr(),
4638 LN0->getMemOperand());
4639 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4640 Mask = Mask.sext(VT.getSizeInBits());
4641 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4642 ExtLoad, DAG.getConstant(Mask, VT));
4643 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4644 SDLoc(N0.getOperand(0)),
4645 N0.getOperand(0).getValueType(), ExtLoad);
4647 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4648 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4650 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4655 if (N0.getOpcode() == ISD::SETCC) {
4656 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4657 // Only do this before legalize for now.
4658 if (VT.isVector() && !LegalOperations &&
4659 TLI.getBooleanContents(true) ==
4660 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4661 EVT N0VT = N0.getOperand(0).getValueType();
4662 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4663 // of the same size as the compared operands. Only optimize sext(setcc())
4664 // if this is the case.
4665 EVT SVT = getSetCCResultType(N0VT);
4667 // We know that the # elements of the results is the same as the
4668 // # elements of the compare (and the # elements of the compare result
4669 // for that matter). Check to see that they are the same size. If so,
4670 // we know that the element size of the sext'd result matches the
4671 // element size of the compare operands.
4672 if (VT.getSizeInBits() == SVT.getSizeInBits())
4673 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4675 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4677 // If the desired elements are smaller or larger than the source
4678 // elements we can use a matching integer vector type and then
4679 // truncate/sign extend
4680 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4681 if (SVT == MatchingVectorType) {
4682 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4683 N0.getOperand(0), N0.getOperand(1),
4684 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4685 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4689 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4690 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4692 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4694 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4695 NegOne, DAG.getConstant(0, VT),
4696 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4697 if (SCC.getNode()) return SCC;
4698 if (!VT.isVector() &&
4699 (!LegalOperations ||
4700 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4701 return DAG.getSelect(SDLoc(N), VT,
4702 DAG.getSetCC(SDLoc(N),
4703 getSetCCResultType(VT),
4704 N0.getOperand(0), N0.getOperand(1),
4705 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4706 NegOne, DAG.getConstant(0, VT));
4710 // fold (sext x) -> (zext x) if the sign bit is known zero.
4711 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4712 DAG.SignBitIsZero(N0))
4713 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4718 // isTruncateOf - If N is a truncate of some other value, return true, record
4719 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4720 // This function computes KnownZero to avoid a duplicated call to
4721 // ComputeMaskedBits in the caller.
4722 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4725 if (N->getOpcode() == ISD::TRUNCATE) {
4726 Op = N->getOperand(0);
4727 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4731 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4732 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4735 SDValue Op0 = N->getOperand(0);
4736 SDValue Op1 = N->getOperand(1);
4737 assert(Op0.getValueType() == Op1.getValueType());
4739 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4740 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4741 if (COp0 && COp0->isNullValue())
4743 else if (COp1 && COp1->isNullValue())
4748 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4750 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4756 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4757 SDValue N0 = N->getOperand(0);
4758 EVT VT = N->getValueType(0);
4760 // fold (zext c1) -> c1
4761 if (isa<ConstantSDNode>(N0))
4762 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4763 // fold (zext (zext x)) -> (zext x)
4764 // fold (zext (aext x)) -> (zext x)
4765 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4766 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4769 // fold (zext (truncate x)) -> (zext x) or
4770 // (zext (truncate x)) -> (truncate x)
4771 // This is valid when the truncated bits of x are already zero.
4772 // FIXME: We should extend this to work for vectors too.
4775 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4776 APInt TruncatedBits =
4777 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4778 APInt(Op.getValueSizeInBits(), 0) :
4779 APInt::getBitsSet(Op.getValueSizeInBits(),
4780 N0.getValueSizeInBits(),
4781 std::min(Op.getValueSizeInBits(),
4782 VT.getSizeInBits()));
4783 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4784 if (VT.bitsGT(Op.getValueType()))
4785 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4786 if (VT.bitsLT(Op.getValueType()))
4787 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4793 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4794 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4795 if (N0.getOpcode() == ISD::TRUNCATE) {
4796 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4797 if (NarrowLoad.getNode()) {
4798 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4799 if (NarrowLoad.getNode() != N0.getNode()) {
4800 CombineTo(N0.getNode(), NarrowLoad);
4801 // CombineTo deleted the truncate, if needed, but not what's under it.
4804 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4808 // fold (zext (truncate x)) -> (and x, mask)
4809 if (N0.getOpcode() == ISD::TRUNCATE &&
4810 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4812 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4813 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4814 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4815 if (NarrowLoad.getNode()) {
4816 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4817 if (NarrowLoad.getNode() != N0.getNode()) {
4818 CombineTo(N0.getNode(), NarrowLoad);
4819 // CombineTo deleted the truncate, if needed, but not what's under it.
4822 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4825 SDValue Op = N0.getOperand(0);
4826 if (Op.getValueType().bitsLT(VT)) {
4827 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4828 AddToWorkList(Op.getNode());
4829 } else if (Op.getValueType().bitsGT(VT)) {
4830 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4831 AddToWorkList(Op.getNode());
4833 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4834 N0.getValueType().getScalarType());
4837 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4838 // if either of the casts is not free.
4839 if (N0.getOpcode() == ISD::AND &&
4840 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4841 N0.getOperand(1).getOpcode() == ISD::Constant &&
4842 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4843 N0.getValueType()) ||
4844 !TLI.isZExtFree(N0.getValueType(), VT))) {
4845 SDValue X = N0.getOperand(0).getOperand(0);
4846 if (X.getValueType().bitsLT(VT)) {
4847 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4848 } else if (X.getValueType().bitsGT(VT)) {
4849 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4851 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4852 Mask = Mask.zext(VT.getSizeInBits());
4853 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4854 X, DAG.getConstant(Mask, VT));
4857 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4858 // None of the supported targets knows how to perform load and vector_zext
4859 // on vectors in one instruction. We only perform this transformation on
4861 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4862 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4863 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4864 bool DoXform = true;
4865 SmallVector<SDNode*, 4> SetCCs;
4866 if (!N0.hasOneUse())
4867 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4869 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4870 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4872 LN0->getBasePtr(), N0.getValueType(),
4873 LN0->getMemOperand());
4874 CombineTo(N, ExtLoad);
4875 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4876 N0.getValueType(), ExtLoad);
4877 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4879 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4881 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4885 // fold (zext (and/or/xor (load x), cst)) ->
4886 // (and/or/xor (zextload x), (zext cst))
4887 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4888 N0.getOpcode() == ISD::XOR) &&
4889 isa<LoadSDNode>(N0.getOperand(0)) &&
4890 N0.getOperand(1).getOpcode() == ISD::Constant &&
4891 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4892 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4893 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4894 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4895 bool DoXform = true;
4896 SmallVector<SDNode*, 4> SetCCs;
4897 if (!N0.hasOneUse())
4898 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4901 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4902 LN0->getChain(), LN0->getBasePtr(),
4904 LN0->getMemOperand());
4905 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4906 Mask = Mask.zext(VT.getSizeInBits());
4907 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4908 ExtLoad, DAG.getConstant(Mask, VT));
4909 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4910 SDLoc(N0.getOperand(0)),
4911 N0.getOperand(0).getValueType(), ExtLoad);
4913 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4914 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4916 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4921 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4922 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4923 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4924 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4925 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4926 EVT MemVT = LN0->getMemoryVT();
4927 if ((!LegalOperations && !LN0->isVolatile()) ||
4928 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4929 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4931 LN0->getBasePtr(), MemVT,
4932 LN0->getMemOperand());
4933 CombineTo(N, ExtLoad);
4934 CombineTo(N0.getNode(),
4935 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4937 ExtLoad.getValue(1));
4938 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4942 if (N0.getOpcode() == ISD::SETCC) {
4943 if (!LegalOperations && VT.isVector()) {
4944 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4945 // Only do this before legalize for now.
4946 EVT N0VT = N0.getOperand(0).getValueType();
4947 EVT EltVT = VT.getVectorElementType();
4948 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4949 DAG.getConstant(1, EltVT));
4950 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4951 // We know that the # elements of the results is the same as the
4952 // # elements of the compare (and the # elements of the compare result
4953 // for that matter). Check to see that they are the same size. If so,
4954 // we know that the element size of the sext'd result matches the
4955 // element size of the compare operands.
4956 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4957 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4959 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4960 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4961 &OneOps[0], OneOps.size()));
4963 // If the desired elements are smaller or larger than the source
4964 // elements we can use a matching integer vector type and then
4965 // truncate/sign extend
4966 EVT MatchingElementType =
4967 EVT::getIntegerVT(*DAG.getContext(),
4968 N0VT.getScalarType().getSizeInBits());
4969 EVT MatchingVectorType =
4970 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4971 N0VT.getVectorNumElements());
4973 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4975 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4976 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4977 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4978 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4979 &OneOps[0], OneOps.size()));
4982 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4984 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4985 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4986 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4987 if (SCC.getNode()) return SCC;
4990 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4991 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4992 isa<ConstantSDNode>(N0.getOperand(1)) &&
4993 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4995 SDValue ShAmt = N0.getOperand(1);
4996 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4997 if (N0.getOpcode() == ISD::SHL) {
4998 SDValue InnerZExt = N0.getOperand(0);
4999 // If the original shl may be shifting out bits, do not perform this
5001 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5002 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5003 if (ShAmtVal > KnownZeroBits)
5009 // Ensure that the shift amount is wide enough for the shifted value.
5010 if (VT.getSizeInBits() >= 256)
5011 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5013 return DAG.getNode(N0.getOpcode(), DL, VT,
5014 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5021 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5022 SDValue N0 = N->getOperand(0);
5023 EVT VT = N->getValueType(0);
5025 // fold (aext c1) -> c1
5026 if (isa<ConstantSDNode>(N0))
5027 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5028 // fold (aext (aext x)) -> (aext x)
5029 // fold (aext (zext x)) -> (zext x)
5030 // fold (aext (sext x)) -> (sext x)
5031 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5032 N0.getOpcode() == ISD::ZERO_EXTEND ||
5033 N0.getOpcode() == ISD::SIGN_EXTEND)
5034 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5036 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5037 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5038 if (N0.getOpcode() == ISD::TRUNCATE) {
5039 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5040 if (NarrowLoad.getNode()) {
5041 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5042 if (NarrowLoad.getNode() != N0.getNode()) {
5043 CombineTo(N0.getNode(), NarrowLoad);
5044 // CombineTo deleted the truncate, if needed, but not what's under it.
5047 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5051 // fold (aext (truncate x))
5052 if (N0.getOpcode() == ISD::TRUNCATE) {
5053 SDValue TruncOp = N0.getOperand(0);
5054 if (TruncOp.getValueType() == VT)
5055 return TruncOp; // x iff x size == zext size.
5056 if (TruncOp.getValueType().bitsGT(VT))
5057 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5058 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5061 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5062 // if the trunc is not free.
5063 if (N0.getOpcode() == ISD::AND &&
5064 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5065 N0.getOperand(1).getOpcode() == ISD::Constant &&
5066 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5067 N0.getValueType())) {
5068 SDValue X = N0.getOperand(0).getOperand(0);
5069 if (X.getValueType().bitsLT(VT)) {
5070 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5071 } else if (X.getValueType().bitsGT(VT)) {
5072 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5074 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5075 Mask = Mask.zext(VT.getSizeInBits());
5076 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5077 X, DAG.getConstant(Mask, VT));
5080 // fold (aext (load x)) -> (aext (truncate (extload x)))
5081 // None of the supported targets knows how to perform load and any_ext
5082 // on vectors in one instruction. We only perform this transformation on
5084 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5085 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5086 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5087 bool DoXform = true;
5088 SmallVector<SDNode*, 4> SetCCs;
5089 if (!N0.hasOneUse())
5090 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5092 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5093 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5095 LN0->getBasePtr(), N0.getValueType(),
5096 LN0->getMemOperand());
5097 CombineTo(N, ExtLoad);
5098 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5099 N0.getValueType(), ExtLoad);
5100 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5101 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5103 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5107 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5108 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5109 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5110 if (N0.getOpcode() == ISD::LOAD &&
5111 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5113 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5114 EVT MemVT = LN0->getMemoryVT();
5115 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5116 VT, LN0->getChain(), LN0->getBasePtr(),
5117 MemVT, LN0->getMemOperand());
5118 CombineTo(N, ExtLoad);
5119 CombineTo(N0.getNode(),
5120 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5121 N0.getValueType(), ExtLoad),
5122 ExtLoad.getValue(1));
5123 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5126 if (N0.getOpcode() == ISD::SETCC) {
5127 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5128 // Only do this before legalize for now.
5129 if (VT.isVector() && !LegalOperations) {
5130 EVT N0VT = N0.getOperand(0).getValueType();
5131 // We know that the # elements of the results is the same as the
5132 // # elements of the compare (and the # elements of the compare result
5133 // for that matter). Check to see that they are the same size. If so,
5134 // we know that the element size of the sext'd result matches the
5135 // element size of the compare operands.
5136 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5137 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5139 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5140 // If the desired elements are smaller or larger than the source
5141 // elements we can use a matching integer vector type and then
5142 // truncate/sign extend
5144 EVT MatchingElementType =
5145 EVT::getIntegerVT(*DAG.getContext(),
5146 N0VT.getScalarType().getSizeInBits());
5147 EVT MatchingVectorType =
5148 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5149 N0VT.getVectorNumElements());
5151 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5153 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5154 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5158 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5160 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5161 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5162 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5170 /// GetDemandedBits - See if the specified operand can be simplified with the
5171 /// knowledge that only the bits specified by Mask are used. If so, return the
5172 /// simpler operand, otherwise return a null SDValue.
5173 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5174 switch (V.getOpcode()) {
5176 case ISD::Constant: {
5177 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5178 assert(CV != 0 && "Const value should be ConstSDNode.");
5179 const APInt &CVal = CV->getAPIntValue();
5180 APInt NewVal = CVal & Mask;
5182 return DAG.getConstant(NewVal, V.getValueType());
5187 // If the LHS or RHS don't contribute bits to the or, drop them.
5188 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5189 return V.getOperand(1);
5190 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5191 return V.getOperand(0);
5194 // Only look at single-use SRLs.
5195 if (!V.getNode()->hasOneUse())
5197 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5198 // See if we can recursively simplify the LHS.
5199 unsigned Amt = RHSC->getZExtValue();
5201 // Watch out for shift count overflow though.
5202 if (Amt >= Mask.getBitWidth()) break;
5203 APInt NewMask = Mask << Amt;
5204 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5205 if (SimplifyLHS.getNode())
5206 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5207 SimplifyLHS, V.getOperand(1));
5213 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5214 /// bits and then truncated to a narrower type and where N is a multiple
5215 /// of number of bits of the narrower type, transform it to a narrower load
5216 /// from address + N / num of bits of new type. If the result is to be
5217 /// extended, also fold the extension to form a extending load.
5218 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5219 unsigned Opc = N->getOpcode();
5221 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5222 SDValue N0 = N->getOperand(0);
5223 EVT VT = N->getValueType(0);
5226 // This transformation isn't valid for vector loads.
5230 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5232 if (Opc == ISD::SIGN_EXTEND_INREG) {
5233 ExtType = ISD::SEXTLOAD;
5234 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5235 } else if (Opc == ISD::SRL) {
5236 // Another special-case: SRL is basically zero-extending a narrower value.
5237 ExtType = ISD::ZEXTLOAD;
5239 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5240 if (!N01) return SDValue();
5241 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5242 VT.getSizeInBits() - N01->getZExtValue());
5244 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5247 unsigned EVTBits = ExtVT.getSizeInBits();
5249 // Do not generate loads of non-round integer types since these can
5250 // be expensive (and would be wrong if the type is not byte sized).
5251 if (!ExtVT.isRound())
5255 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5256 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5257 ShAmt = N01->getZExtValue();
5258 // Is the shift amount a multiple of size of VT?
5259 if ((ShAmt & (EVTBits-1)) == 0) {
5260 N0 = N0.getOperand(0);
5261 // Is the load width a multiple of size of VT?
5262 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5266 // At this point, we must have a load or else we can't do the transform.
5267 if (!isa<LoadSDNode>(N0)) return SDValue();
5269 // Because a SRL must be assumed to *need* to zero-extend the high bits
5270 // (as opposed to anyext the high bits), we can't combine the zextload
5271 // lowering of SRL and an sextload.
5272 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5275 // If the shift amount is larger than the input type then we're not
5276 // accessing any of the loaded bytes. If the load was a zextload/extload
5277 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5278 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5283 // If the load is shifted left (and the result isn't shifted back right),
5284 // we can fold the truncate through the shift.
5285 unsigned ShLeftAmt = 0;
5286 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5287 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5288 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5289 ShLeftAmt = N01->getZExtValue();
5290 N0 = N0.getOperand(0);
5294 // If we haven't found a load, we can't narrow it. Don't transform one with
5295 // multiple uses, this would require adding a new load.
5296 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5299 // Don't change the width of a volatile load.
5300 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5301 if (LN0->isVolatile())
5304 // Verify that we are actually reducing a load width here.
5305 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5308 // For the transform to be legal, the load must produce only two values
5309 // (the value loaded and the chain). Don't transform a pre-increment
5310 // load, for example, which produces an extra value. Otherwise the
5311 // transformation is not equivalent, and the downstream logic to replace
5312 // uses gets things wrong.
5313 if (LN0->getNumValues() > 2)
5316 // If the load that we're shrinking is an extload and we're not just
5317 // discarding the extension we can't simply shrink the load. Bail.
5318 // TODO: It would be possible to merge the extensions in some cases.
5319 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5320 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5323 EVT PtrType = N0.getOperand(1).getValueType();
5325 if (PtrType == MVT::Untyped || PtrType.isExtended())
5326 // It's not possible to generate a constant of extended or untyped type.
5329 // For big endian targets, we need to adjust the offset to the pointer to
5330 // load the correct bytes.
5331 if (TLI.isBigEndian()) {
5332 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5333 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5334 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5337 uint64_t PtrOff = ShAmt / 8;
5338 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5339 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5340 PtrType, LN0->getBasePtr(),
5341 DAG.getConstant(PtrOff, PtrType));
5342 AddToWorkList(NewPtr.getNode());
5345 if (ExtType == ISD::NON_EXTLOAD)
5346 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5347 LN0->getPointerInfo().getWithOffset(PtrOff),
5348 LN0->isVolatile(), LN0->isNonTemporal(),
5349 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5351 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5352 LN0->getPointerInfo().getWithOffset(PtrOff),
5353 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5354 NewAlign, LN0->getTBAAInfo());
5356 // Replace the old load's chain with the new load's chain.
5357 WorkListRemover DeadNodes(*this);
5358 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5360 // Shift the result left, if we've swallowed a left shift.
5361 SDValue Result = Load;
5362 if (ShLeftAmt != 0) {
5363 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5364 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5366 // If the shift amount is as large as the result size (but, presumably,
5367 // no larger than the source) then the useful bits of the result are
5368 // zero; we can't simply return the shortened shift, because the result
5369 // of that operation is undefined.
5370 if (ShLeftAmt >= VT.getSizeInBits())
5371 Result = DAG.getConstant(0, VT);
5373 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5374 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5377 // Return the new loaded value.
5381 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5382 SDValue N0 = N->getOperand(0);
5383 SDValue N1 = N->getOperand(1);
5384 EVT VT = N->getValueType(0);
5385 EVT EVT = cast<VTSDNode>(N1)->getVT();
5386 unsigned VTBits = VT.getScalarType().getSizeInBits();
5387 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5389 // fold (sext_in_reg c1) -> c1
5390 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5391 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5393 // If the input is already sign extended, just drop the extension.
5394 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5397 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5398 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5399 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5400 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5401 N0.getOperand(0), N1);
5403 // fold (sext_in_reg (sext x)) -> (sext x)
5404 // fold (sext_in_reg (aext x)) -> (sext x)
5405 // if x is small enough.
5406 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5407 SDValue N00 = N0.getOperand(0);
5408 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5409 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5410 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5413 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5414 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5415 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5417 // fold operands of sext_in_reg based on knowledge that the top bits are not
5419 if (SimplifyDemandedBits(SDValue(N, 0)))
5420 return SDValue(N, 0);
5422 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5423 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5424 SDValue NarrowLoad = ReduceLoadWidth(N);
5425 if (NarrowLoad.getNode())
5428 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5429 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5430 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5431 if (N0.getOpcode() == ISD::SRL) {
5432 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5433 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5434 // We can turn this into an SRA iff the input to the SRL is already sign
5436 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5437 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5438 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5439 N0.getOperand(0), N0.getOperand(1));
5443 // fold (sext_inreg (extload x)) -> (sextload x)
5444 if (ISD::isEXTLoad(N0.getNode()) &&
5445 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5446 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5447 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5448 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5449 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5450 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5452 LN0->getBasePtr(), EVT,
5453 LN0->getMemOperand());
5454 CombineTo(N, ExtLoad);
5455 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5456 AddToWorkList(ExtLoad.getNode());
5457 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5459 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5460 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5462 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5463 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5464 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5465 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5466 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5468 LN0->getBasePtr(), EVT,
5469 LN0->getMemOperand());
5470 CombineTo(N, ExtLoad);
5471 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5472 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5475 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5476 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5477 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5478 N0.getOperand(1), false);
5479 if (BSwap.getNode() != 0)
5480 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5487 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5488 SDValue N0 = N->getOperand(0);
5489 EVT VT = N->getValueType(0);
5490 bool isLE = TLI.isLittleEndian();
5493 if (N0.getValueType() == N->getValueType(0))
5495 // fold (truncate c1) -> c1
5496 if (isa<ConstantSDNode>(N0))
5497 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5498 // fold (truncate (truncate x)) -> (truncate x)
5499 if (N0.getOpcode() == ISD::TRUNCATE)
5500 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5501 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5502 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5503 N0.getOpcode() == ISD::SIGN_EXTEND ||
5504 N0.getOpcode() == ISD::ANY_EXTEND) {
5505 if (N0.getOperand(0).getValueType().bitsLT(VT))
5506 // if the source is smaller than the dest, we still need an extend
5507 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5509 if (N0.getOperand(0).getValueType().bitsGT(VT))
5510 // if the source is larger than the dest, than we just need the truncate
5511 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5512 // if the source and dest are the same type, we can drop both the extend
5513 // and the truncate.
5514 return N0.getOperand(0);
5517 // Fold extract-and-trunc into a narrow extract. For example:
5518 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5519 // i32 y = TRUNCATE(i64 x)
5521 // v16i8 b = BITCAST (v2i64 val)
5522 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5524 // Note: We only run this optimization after type legalization (which often
5525 // creates this pattern) and before operation legalization after which
5526 // we need to be more careful about the vector instructions that we generate.
5527 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5528 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5530 EVT VecTy = N0.getOperand(0).getValueType();
5531 EVT ExTy = N0.getValueType();
5532 EVT TrTy = N->getValueType(0);
5534 unsigned NumElem = VecTy.getVectorNumElements();
5535 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5537 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5538 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5540 SDValue EltNo = N0->getOperand(1);
5541 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5542 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5543 EVT IndexTy = TLI.getVectorIdxTy();
5544 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5546 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5547 NVT, N0.getOperand(0));
5549 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5551 DAG.getConstant(Index, IndexTy));
5555 // Fold a series of buildvector, bitcast, and truncate if possible.
5557 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5558 // (2xi32 (buildvector x, y)).
5559 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5560 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5561 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5562 N0.getOperand(0).hasOneUse()) {
5564 SDValue BuildVect = N0.getOperand(0);
5565 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5566 EVT TruncVecEltTy = VT.getVectorElementType();
5568 // Check that the element types match.
5569 if (BuildVectEltTy == TruncVecEltTy) {
5570 // Now we only need to compute the offset of the truncated elements.
5571 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5572 unsigned TruncVecNumElts = VT.getVectorNumElements();
5573 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5575 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5576 "Invalid number of elements");
5578 SmallVector<SDValue, 8> Opnds;
5579 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5580 Opnds.push_back(BuildVect.getOperand(i));
5582 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5587 // See if we can simplify the input to this truncate through knowledge that
5588 // only the low bits are being used.
5589 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5590 // Currently we only perform this optimization on scalars because vectors
5591 // may have different active low bits.
5592 if (!VT.isVector()) {
5594 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5595 VT.getSizeInBits()));
5596 if (Shorter.getNode())
5597 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5599 // fold (truncate (load x)) -> (smaller load x)
5600 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5601 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5602 SDValue Reduced = ReduceLoadWidth(N);
5603 if (Reduced.getNode())
5606 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5607 // where ... are all 'undef'.
5608 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5609 SmallVector<EVT, 8> VTs;
5612 unsigned NumDefs = 0;
5614 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5615 SDValue X = N0.getOperand(i);
5616 if (X.getOpcode() != ISD::UNDEF) {
5621 // Stop if more than one members are non-undef.
5624 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5625 VT.getVectorElementType(),
5626 X.getValueType().getVectorNumElements()));
5630 return DAG.getUNDEF(VT);
5633 assert(V.getNode() && "The single defined operand is empty!");
5634 SmallVector<SDValue, 8> Opnds;
5635 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5637 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5640 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5641 AddToWorkList(NV.getNode());
5642 Opnds.push_back(NV);
5644 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5645 &Opnds[0], Opnds.size());
5649 // Simplify the operands using demanded-bits information.
5650 if (!VT.isVector() &&
5651 SimplifyDemandedBits(SDValue(N, 0)))
5652 return SDValue(N, 0);
5657 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5658 SDValue Elt = N->getOperand(i);
5659 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5660 return Elt.getNode();
5661 return Elt.getOperand(Elt.getResNo()).getNode();
5664 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5665 /// if load locations are consecutive.
5666 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5667 assert(N->getOpcode() == ISD::BUILD_PAIR);
5669 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5670 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5671 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5672 LD1->getPointerInfo().getAddrSpace() !=
5673 LD2->getPointerInfo().getAddrSpace())
5675 EVT LD1VT = LD1->getValueType(0);
5677 if (ISD::isNON_EXTLoad(LD2) &&
5679 // If both are volatile this would reduce the number of volatile loads.
5680 // If one is volatile it might be ok, but play conservative and bail out.
5681 !LD1->isVolatile() &&
5682 !LD2->isVolatile() &&
5683 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5684 unsigned Align = LD1->getAlignment();
5685 unsigned NewAlign = TLI.getDataLayout()->
5686 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5688 if (NewAlign <= Align &&
5689 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5690 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5691 LD1->getBasePtr(), LD1->getPointerInfo(),
5692 false, false, false, Align);
5698 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5699 SDValue N0 = N->getOperand(0);
5700 EVT VT = N->getValueType(0);
5702 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5703 // Only do this before legalize, since afterward the target may be depending
5704 // on the bitconvert.
5705 // First check to see if this is all constant.
5707 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5709 bool isSimple = true;
5710 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5711 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5712 N0.getOperand(i).getOpcode() != ISD::Constant &&
5713 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5718 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5719 assert(!DestEltVT.isVector() &&
5720 "Element type of vector ValueType must not be vector!");
5722 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5725 // If the input is a constant, let getNode fold it.
5726 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5727 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5728 if (Res.getNode() != N) {
5729 if (!LegalOperations ||
5730 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5733 // Folding it resulted in an illegal node, and it's too late to
5734 // do that. Clean up the old node and forego the transformation.
5735 // Ideally this won't happen very often, because instcombine
5736 // and the earlier dagcombine runs (where illegal nodes are
5737 // permitted) should have folded most of them already.
5738 DAG.DeleteNode(Res.getNode());
5742 // (conv (conv x, t1), t2) -> (conv x, t2)
5743 if (N0.getOpcode() == ISD::BITCAST)
5744 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5747 // fold (conv (load x)) -> (load (conv*)x)
5748 // If the resultant load doesn't need a higher alignment than the original!
5749 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5750 // Do not change the width of a volatile load.
5751 !cast<LoadSDNode>(N0)->isVolatile() &&
5752 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5753 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5754 unsigned Align = TLI.getDataLayout()->
5755 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5756 unsigned OrigAlign = LN0->getAlignment();
5758 if (Align <= OrigAlign) {
5759 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5760 LN0->getBasePtr(), LN0->getPointerInfo(),
5761 LN0->isVolatile(), LN0->isNonTemporal(),
5762 LN0->isInvariant(), OrigAlign,
5763 LN0->getTBAAInfo());
5765 CombineTo(N0.getNode(),
5766 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5767 N0.getValueType(), Load),
5773 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5774 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5775 // This often reduces constant pool loads.
5776 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5777 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5778 N0.getNode()->hasOneUse() && VT.isInteger() &&
5779 !VT.isVector() && !N0.getValueType().isVector()) {
5780 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5782 AddToWorkList(NewConv.getNode());
5784 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5785 if (N0.getOpcode() == ISD::FNEG)
5786 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5787 NewConv, DAG.getConstant(SignBit, VT));
5788 assert(N0.getOpcode() == ISD::FABS);
5789 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5790 NewConv, DAG.getConstant(~SignBit, VT));
5793 // fold (bitconvert (fcopysign cst, x)) ->
5794 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5795 // Note that we don't handle (copysign x, cst) because this can always be
5796 // folded to an fneg or fabs.
5797 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5798 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5799 VT.isInteger() && !VT.isVector()) {
5800 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5801 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5802 if (isTypeLegal(IntXVT)) {
5803 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5804 IntXVT, N0.getOperand(1));
5805 AddToWorkList(X.getNode());
5807 // If X has a different width than the result/lhs, sext it or truncate it.
5808 unsigned VTWidth = VT.getSizeInBits();
5809 if (OrigXWidth < VTWidth) {
5810 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5811 AddToWorkList(X.getNode());
5812 } else if (OrigXWidth > VTWidth) {
5813 // To get the sign bit in the right place, we have to shift it right
5814 // before truncating.
5815 X = DAG.getNode(ISD::SRL, SDLoc(X),
5816 X.getValueType(), X,
5817 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5818 AddToWorkList(X.getNode());
5819 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5820 AddToWorkList(X.getNode());
5823 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5824 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5825 X, DAG.getConstant(SignBit, VT));
5826 AddToWorkList(X.getNode());
5828 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5829 VT, N0.getOperand(0));
5830 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5831 Cst, DAG.getConstant(~SignBit, VT));
5832 AddToWorkList(Cst.getNode());
5834 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5838 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5839 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5840 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5841 if (CombineLD.getNode())
5848 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5849 EVT VT = N->getValueType(0);
5850 return CombineConsecutiveLoads(N, VT);
5853 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5854 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5855 /// destination element value type.
5856 SDValue DAGCombiner::
5857 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5858 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5860 // If this is already the right type, we're done.
5861 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5863 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5864 unsigned DstBitSize = DstEltVT.getSizeInBits();
5866 // If this is a conversion of N elements of one type to N elements of another
5867 // type, convert each element. This handles FP<->INT cases.
5868 if (SrcBitSize == DstBitSize) {
5869 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5870 BV->getValueType(0).getVectorNumElements());
5872 // Due to the FP element handling below calling this routine recursively,
5873 // we can end up with a scalar-to-vector node here.
5874 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5875 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5876 DAG.getNode(ISD::BITCAST, SDLoc(BV),
5877 DstEltVT, BV->getOperand(0)));
5879 SmallVector<SDValue, 8> Ops;
5880 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5881 SDValue Op = BV->getOperand(i);
5882 // If the vector element type is not legal, the BUILD_VECTOR operands
5883 // are promoted and implicitly truncated. Make that explicit here.
5884 if (Op.getValueType() != SrcEltVT)
5885 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5886 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5888 AddToWorkList(Ops.back().getNode());
5890 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5891 &Ops[0], Ops.size());
5894 // Otherwise, we're growing or shrinking the elements. To avoid having to
5895 // handle annoying details of growing/shrinking FP values, we convert them to
5897 if (SrcEltVT.isFloatingPoint()) {
5898 // Convert the input float vector to a int vector where the elements are the
5900 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5901 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5902 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5906 // Now we know the input is an integer vector. If the output is a FP type,
5907 // convert to integer first, then to FP of the right size.
5908 if (DstEltVT.isFloatingPoint()) {
5909 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5910 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5911 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5913 // Next, convert to FP elements of the same size.
5914 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5917 // Okay, we know the src/dst types are both integers of differing types.
5918 // Handling growing first.
5919 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5920 if (SrcBitSize < DstBitSize) {
5921 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5923 SmallVector<SDValue, 8> Ops;
5924 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5925 i += NumInputsPerOutput) {
5926 bool isLE = TLI.isLittleEndian();
5927 APInt NewBits = APInt(DstBitSize, 0);
5928 bool EltIsUndef = true;
5929 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5930 // Shift the previously computed bits over.
5931 NewBits <<= SrcBitSize;
5932 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5933 if (Op.getOpcode() == ISD::UNDEF) continue;
5936 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5937 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5941 Ops.push_back(DAG.getUNDEF(DstEltVT));
5943 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5946 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5947 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5948 &Ops[0], Ops.size());
5951 // Finally, this must be the case where we are shrinking elements: each input
5952 // turns into multiple outputs.
5953 bool isS2V = ISD::isScalarToVector(BV);
5954 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5955 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5956 NumOutputsPerInput*BV->getNumOperands());
5957 SmallVector<SDValue, 8> Ops;
5959 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5960 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5961 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5962 Ops.push_back(DAG.getUNDEF(DstEltVT));
5966 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5967 getAPIntValue().zextOrTrunc(SrcBitSize);
5969 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5970 APInt ThisVal = OpVal.trunc(DstBitSize);
5971 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5972 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5973 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5974 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5976 OpVal = OpVal.lshr(DstBitSize);
5979 // For big endian targets, swap the order of the pieces of each element.
5980 if (TLI.isBigEndian())
5981 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5984 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5985 &Ops[0], Ops.size());
5988 SDValue DAGCombiner::visitFADD(SDNode *N) {
5989 SDValue N0 = N->getOperand(0);
5990 SDValue N1 = N->getOperand(1);
5991 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5992 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5993 EVT VT = N->getValueType(0);
5996 if (VT.isVector()) {
5997 SDValue FoldedVOp = SimplifyVBinOp(N);
5998 if (FoldedVOp.getNode()) return FoldedVOp;
6001 // fold (fadd c1, c2) -> c1 + c2
6003 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6004 // canonicalize constant to RHS
6005 if (N0CFP && !N1CFP)
6006 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6007 // fold (fadd A, 0) -> A
6008 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6009 N1CFP->getValueAPF().isZero())
6011 // fold (fadd A, (fneg B)) -> (fsub A, B)
6012 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6013 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6014 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6015 GetNegatedExpression(N1, DAG, LegalOperations));
6016 // fold (fadd (fneg A), B) -> (fsub B, A)
6017 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6018 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6019 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6020 GetNegatedExpression(N0, DAG, LegalOperations));
6022 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6023 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6024 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6025 isa<ConstantFPSDNode>(N0.getOperand(1)))
6026 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6027 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6028 N0.getOperand(1), N1));
6030 // No FP constant should be created after legalization as Instruction
6031 // Selection pass has hard time in dealing with FP constant.
6033 // We don't need test this condition for transformation like following, as
6034 // the DAG being transformed implies it is legal to take FP constant as
6037 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6039 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6041 // If allow, fold (fadd (fneg x), x) -> 0.0
6042 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6043 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6044 return DAG.getConstantFP(0.0, VT);
6046 // If allow, fold (fadd x, (fneg x)) -> 0.0
6047 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6048 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6049 return DAG.getConstantFP(0.0, VT);
6051 // In unsafe math mode, we can fold chains of FADD's of the same value
6052 // into multiplications. This transform is not safe in general because
6053 // we are reducing the number of rounding steps.
6054 if (DAG.getTarget().Options.UnsafeFPMath &&
6055 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6057 if (N0.getOpcode() == ISD::FMUL) {
6058 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6059 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6061 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6062 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6063 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6065 DAG.getConstantFP(1.0, VT));
6066 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6070 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6071 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6072 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6074 DAG.getConstantFP(1.0, VT));
6075 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6079 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6080 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6081 N1.getOperand(0) == N1.getOperand(1) &&
6082 N0.getOperand(1) == N1.getOperand(0)) {
6083 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6085 DAG.getConstantFP(2.0, VT));
6086 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6087 N0.getOperand(1), NewCFP);
6090 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6091 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6092 N1.getOperand(0) == N1.getOperand(1) &&
6093 N0.getOperand(0) == N1.getOperand(0)) {
6094 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6096 DAG.getConstantFP(2.0, VT));
6097 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6098 N0.getOperand(0), NewCFP);
6102 if (N1.getOpcode() == ISD::FMUL) {
6103 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6104 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6106 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6107 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6108 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6110 DAG.getConstantFP(1.0, VT));
6111 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6115 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6116 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6117 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6119 DAG.getConstantFP(1.0, VT));
6120 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6125 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6126 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6127 N0.getOperand(0) == N0.getOperand(1) &&
6128 N1.getOperand(1) == N0.getOperand(0)) {
6129 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6131 DAG.getConstantFP(2.0, VT));
6132 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6133 N1.getOperand(1), NewCFP);
6136 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6137 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6138 N0.getOperand(0) == N0.getOperand(1) &&
6139 N1.getOperand(0) == N0.getOperand(0)) {
6140 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6142 DAG.getConstantFP(2.0, VT));
6143 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6144 N1.getOperand(0), NewCFP);
6148 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6149 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6150 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6151 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6152 (N0.getOperand(0) == N1))
6153 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6154 N1, DAG.getConstantFP(3.0, VT));
6157 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6158 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6159 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6160 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6161 N1.getOperand(0) == N0)
6162 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6163 N0, DAG.getConstantFP(3.0, VT));
6166 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6167 if (AllowNewFpConst &&
6168 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6169 N0.getOperand(0) == N0.getOperand(1) &&
6170 N1.getOperand(0) == N1.getOperand(1) &&
6171 N0.getOperand(0) == N1.getOperand(0))
6172 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6174 DAG.getConstantFP(4.0, VT));
6177 // FADD -> FMA combines:
6178 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6179 DAG.getTarget().Options.UnsafeFPMath) &&
6180 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6181 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6183 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6184 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6185 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6186 N0.getOperand(0), N0.getOperand(1), N1);
6188 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6189 // Note: Commutes FADD operands.
6190 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6191 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6192 N1.getOperand(0), N1.getOperand(1), N0);
6198 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6199 SDValue N0 = N->getOperand(0);
6200 SDValue N1 = N->getOperand(1);
6201 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6202 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6203 EVT VT = N->getValueType(0);
6207 if (VT.isVector()) {
6208 SDValue FoldedVOp = SimplifyVBinOp(N);
6209 if (FoldedVOp.getNode()) return FoldedVOp;
6212 // fold (fsub c1, c2) -> c1-c2
6214 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6215 // fold (fsub A, 0) -> A
6216 if (DAG.getTarget().Options.UnsafeFPMath &&
6217 N1CFP && N1CFP->getValueAPF().isZero())
6219 // fold (fsub 0, B) -> -B
6220 if (DAG.getTarget().Options.UnsafeFPMath &&
6221 N0CFP && N0CFP->getValueAPF().isZero()) {
6222 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6223 return GetNegatedExpression(N1, DAG, LegalOperations);
6224 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6225 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6227 // fold (fsub A, (fneg B)) -> (fadd A, B)
6228 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6229 return DAG.getNode(ISD::FADD, dl, VT, N0,
6230 GetNegatedExpression(N1, DAG, LegalOperations));
6232 // If 'unsafe math' is enabled, fold
6233 // (fsub x, x) -> 0.0 &
6234 // (fsub x, (fadd x, y)) -> (fneg y) &
6235 // (fsub x, (fadd y, x)) -> (fneg y)
6236 if (DAG.getTarget().Options.UnsafeFPMath) {
6238 return DAG.getConstantFP(0.0f, VT);
6240 if (N1.getOpcode() == ISD::FADD) {
6241 SDValue N10 = N1->getOperand(0);
6242 SDValue N11 = N1->getOperand(1);
6244 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6245 &DAG.getTarget().Options))
6246 return GetNegatedExpression(N11, DAG, LegalOperations);
6248 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6249 &DAG.getTarget().Options))
6250 return GetNegatedExpression(N10, DAG, LegalOperations);
6254 // FSUB -> FMA combines:
6255 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6256 DAG.getTarget().Options.UnsafeFPMath) &&
6257 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6258 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6260 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6261 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6262 return DAG.getNode(ISD::FMA, dl, VT,
6263 N0.getOperand(0), N0.getOperand(1),
6264 DAG.getNode(ISD::FNEG, dl, VT, N1));
6266 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6267 // Note: Commutes FSUB operands.
6268 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6269 return DAG.getNode(ISD::FMA, dl, VT,
6270 DAG.getNode(ISD::FNEG, dl, VT,
6272 N1.getOperand(1), N0);
6274 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6275 if (N0.getOpcode() == ISD::FNEG &&
6276 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6277 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6278 SDValue N00 = N0.getOperand(0).getOperand(0);
6279 SDValue N01 = N0.getOperand(0).getOperand(1);
6280 return DAG.getNode(ISD::FMA, dl, VT,
6281 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6282 DAG.getNode(ISD::FNEG, dl, VT, N1));
6289 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6290 SDValue N0 = N->getOperand(0);
6291 SDValue N1 = N->getOperand(1);
6292 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6293 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6294 EVT VT = N->getValueType(0);
6295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6298 if (VT.isVector()) {
6299 SDValue FoldedVOp = SimplifyVBinOp(N);
6300 if (FoldedVOp.getNode()) return FoldedVOp;
6303 // fold (fmul c1, c2) -> c1*c2
6305 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6306 // canonicalize constant to RHS
6307 if (N0CFP && !N1CFP)
6308 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6309 // fold (fmul A, 0) -> 0
6310 if (DAG.getTarget().Options.UnsafeFPMath &&
6311 N1CFP && N1CFP->getValueAPF().isZero())
6313 // fold (fmul A, 0) -> 0, vector edition.
6314 if (DAG.getTarget().Options.UnsafeFPMath &&
6315 ISD::isBuildVectorAllZeros(N1.getNode()))
6317 // fold (fmul A, 1.0) -> A
6318 if (N1CFP && N1CFP->isExactlyValue(1.0))
6320 // fold (fmul X, 2.0) -> (fadd X, X)
6321 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6322 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6323 // fold (fmul X, -1.0) -> (fneg X)
6324 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6325 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6326 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6328 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6329 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6330 &DAG.getTarget().Options)) {
6331 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6332 &DAG.getTarget().Options)) {
6333 // Both can be negated for free, check to see if at least one is cheaper
6335 if (LHSNeg == 2 || RHSNeg == 2)
6336 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6337 GetNegatedExpression(N0, DAG, LegalOperations),
6338 GetNegatedExpression(N1, DAG, LegalOperations));
6342 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6343 if (DAG.getTarget().Options.UnsafeFPMath &&
6344 N1CFP && N0.getOpcode() == ISD::FMUL &&
6345 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6346 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6347 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6348 N0.getOperand(1), N1));
6353 SDValue DAGCombiner::visitFMA(SDNode *N) {
6354 SDValue N0 = N->getOperand(0);
6355 SDValue N1 = N->getOperand(1);
6356 SDValue N2 = N->getOperand(2);
6357 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6358 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6359 EVT VT = N->getValueType(0);
6362 if (DAG.getTarget().Options.UnsafeFPMath) {
6363 if (N0CFP && N0CFP->isZero())
6365 if (N1CFP && N1CFP->isZero())
6368 if (N0CFP && N0CFP->isExactlyValue(1.0))
6369 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6370 if (N1CFP && N1CFP->isExactlyValue(1.0))
6371 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6373 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6374 if (N0CFP && !N1CFP)
6375 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6377 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6378 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6379 N2.getOpcode() == ISD::FMUL &&
6380 N0 == N2.getOperand(0) &&
6381 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6382 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6383 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6387 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6388 if (DAG.getTarget().Options.UnsafeFPMath &&
6389 N0.getOpcode() == ISD::FMUL && N1CFP &&
6390 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6391 return DAG.getNode(ISD::FMA, dl, VT,
6393 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6397 // (fma x, 1, y) -> (fadd x, y)
6398 // (fma x, -1, y) -> (fadd (fneg x), y)
6400 if (N1CFP->isExactlyValue(1.0))
6401 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6403 if (N1CFP->isExactlyValue(-1.0) &&
6404 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6405 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6406 AddToWorkList(RHSNeg.getNode());
6407 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6411 // (fma x, c, x) -> (fmul x, (c+1))
6412 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6413 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6414 DAG.getNode(ISD::FADD, dl, VT,
6415 N1, DAG.getConstantFP(1.0, VT)));
6417 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6418 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6419 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6420 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6421 DAG.getNode(ISD::FADD, dl, VT,
6422 N1, DAG.getConstantFP(-1.0, VT)));
6428 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6429 SDValue N0 = N->getOperand(0);
6430 SDValue N1 = N->getOperand(1);
6431 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6432 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6433 EVT VT = N->getValueType(0);
6434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6437 if (VT.isVector()) {
6438 SDValue FoldedVOp = SimplifyVBinOp(N);
6439 if (FoldedVOp.getNode()) return FoldedVOp;
6442 // fold (fdiv c1, c2) -> c1/c2
6444 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6446 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6447 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6448 // Compute the reciprocal 1.0 / c2.
6449 APFloat N1APF = N1CFP->getValueAPF();
6450 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6451 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6452 // Only do the transform if the reciprocal is a legal fp immediate that
6453 // isn't too nasty (eg NaN, denormal, ...).
6454 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6455 (!LegalOperations ||
6456 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6457 // backend)... we should handle this gracefully after Legalize.
6458 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6459 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6460 TLI.isFPImmLegal(Recip, VT)))
6461 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6462 DAG.getConstantFP(Recip, VT));
6465 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6466 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6467 &DAG.getTarget().Options)) {
6468 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6469 &DAG.getTarget().Options)) {
6470 // Both can be negated for free, check to see if at least one is cheaper
6472 if (LHSNeg == 2 || RHSNeg == 2)
6473 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6474 GetNegatedExpression(N0, DAG, LegalOperations),
6475 GetNegatedExpression(N1, DAG, LegalOperations));
6482 SDValue DAGCombiner::visitFREM(SDNode *N) {
6483 SDValue N0 = N->getOperand(0);
6484 SDValue N1 = N->getOperand(1);
6485 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6486 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6487 EVT VT = N->getValueType(0);
6489 // fold (frem c1, c2) -> fmod(c1,c2)
6491 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6496 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6497 SDValue N0 = N->getOperand(0);
6498 SDValue N1 = N->getOperand(1);
6499 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6500 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6501 EVT VT = N->getValueType(0);
6503 if (N0CFP && N1CFP) // Constant fold
6504 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6507 const APFloat& V = N1CFP->getValueAPF();
6508 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6509 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6510 if (!V.isNegative()) {
6511 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6512 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6514 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6515 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6516 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6520 // copysign(fabs(x), y) -> copysign(x, y)
6521 // copysign(fneg(x), y) -> copysign(x, y)
6522 // copysign(copysign(x,z), y) -> copysign(x, y)
6523 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6524 N0.getOpcode() == ISD::FCOPYSIGN)
6525 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6526 N0.getOperand(0), N1);
6528 // copysign(x, abs(y)) -> abs(x)
6529 if (N1.getOpcode() == ISD::FABS)
6530 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6532 // copysign(x, copysign(y,z)) -> copysign(x, z)
6533 if (N1.getOpcode() == ISD::FCOPYSIGN)
6534 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6535 N0, N1.getOperand(1));
6537 // copysign(x, fp_extend(y)) -> copysign(x, y)
6538 // copysign(x, fp_round(y)) -> copysign(x, y)
6539 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6540 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6541 N0, N1.getOperand(0));
6546 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6547 SDValue N0 = N->getOperand(0);
6548 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6549 EVT VT = N->getValueType(0);
6550 EVT OpVT = N0.getValueType();
6552 // fold (sint_to_fp c1) -> c1fp
6554 // ...but only if the target supports immediate floating-point values
6555 (!LegalOperations ||
6556 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6557 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6559 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6560 // but UINT_TO_FP is legal on this target, try to convert.
6561 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6562 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6563 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6564 if (DAG.SignBitIsZero(N0))
6565 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6568 // The next optimizations are desireable only if SELECT_CC can be lowered.
6569 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6570 // having to say they don't support SELECT_CC on every type the DAG knows
6571 // about, since there is no way to mark an opcode illegal at all value types
6572 // (See also visitSELECT)
6573 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6574 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6575 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6577 (!LegalOperations ||
6578 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6580 { N0.getOperand(0), N0.getOperand(1),
6581 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6583 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6586 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6587 // (select_cc x, y, 1.0, 0.0,, cc)
6588 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6589 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6590 (!LegalOperations ||
6591 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6593 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6594 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6595 N0.getOperand(0).getOperand(2) };
6596 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6603 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6604 SDValue N0 = N->getOperand(0);
6605 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6606 EVT VT = N->getValueType(0);
6607 EVT OpVT = N0.getValueType();
6609 // fold (uint_to_fp c1) -> c1fp
6611 // ...but only if the target supports immediate floating-point values
6612 (!LegalOperations ||
6613 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6614 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6616 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6617 // but SINT_TO_FP is legal on this target, try to convert.
6618 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6619 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6620 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6621 if (DAG.SignBitIsZero(N0))
6622 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6625 // The next optimizations are desireable only if SELECT_CC can be lowered.
6626 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6627 // having to say they don't support SELECT_CC on every type the DAG knows
6628 // about, since there is no way to mark an opcode illegal at all value types
6629 // (See also visitSELECT)
6630 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6631 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6633 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6634 (!LegalOperations ||
6635 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6637 { N0.getOperand(0), N0.getOperand(1),
6638 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6640 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6647 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6648 SDValue N0 = N->getOperand(0);
6649 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6650 EVT VT = N->getValueType(0);
6652 // fold (fp_to_sint c1fp) -> c1
6654 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6659 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6660 SDValue N0 = N->getOperand(0);
6661 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6662 EVT VT = N->getValueType(0);
6664 // fold (fp_to_uint c1fp) -> c1
6666 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6671 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6672 SDValue N0 = N->getOperand(0);
6673 SDValue N1 = N->getOperand(1);
6674 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6675 EVT VT = N->getValueType(0);
6677 // fold (fp_round c1fp) -> c1fp
6679 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6681 // fold (fp_round (fp_extend x)) -> x
6682 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6683 return N0.getOperand(0);
6685 // fold (fp_round (fp_round x)) -> (fp_round x)
6686 if (N0.getOpcode() == ISD::FP_ROUND) {
6687 // This is a value preserving truncation if both round's are.
6688 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6689 N0.getNode()->getConstantOperandVal(1) == 1;
6690 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6691 DAG.getIntPtrConstant(IsTrunc));
6694 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6695 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6696 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6697 N0.getOperand(0), N1);
6698 AddToWorkList(Tmp.getNode());
6699 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6700 Tmp, N0.getOperand(1));
6706 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6707 SDValue N0 = N->getOperand(0);
6708 EVT VT = N->getValueType(0);
6709 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6712 // fold (fp_round_inreg c1fp) -> c1fp
6713 if (N0CFP && isTypeLegal(EVT)) {
6714 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6715 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6721 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6722 SDValue N0 = N->getOperand(0);
6723 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6724 EVT VT = N->getValueType(0);
6726 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6727 if (N->hasOneUse() &&
6728 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6731 // fold (fp_extend c1fp) -> c1fp
6733 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6735 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6737 if (N0.getOpcode() == ISD::FP_ROUND
6738 && N0.getNode()->getConstantOperandVal(1) == 1) {
6739 SDValue In = N0.getOperand(0);
6740 if (In.getValueType() == VT) return In;
6741 if (VT.bitsLT(In.getValueType()))
6742 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6743 In, N0.getOperand(1));
6744 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6747 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6748 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6749 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6750 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6751 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6752 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6754 LN0->getBasePtr(), N0.getValueType(),
6755 LN0->getMemOperand());
6756 CombineTo(N, ExtLoad);
6757 CombineTo(N0.getNode(),
6758 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6759 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6760 ExtLoad.getValue(1));
6761 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6767 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6768 SDValue N0 = N->getOperand(0);
6769 EVT VT = N->getValueType(0);
6771 if (VT.isVector()) {
6772 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6773 if (FoldedVOp.getNode()) return FoldedVOp;
6776 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6777 &DAG.getTarget().Options))
6778 return GetNegatedExpression(N0, DAG, LegalOperations);
6780 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6781 // constant pool values.
6782 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6784 N0.getNode()->hasOneUse() &&
6785 N0.getOperand(0).getValueType().isInteger()) {
6786 SDValue Int = N0.getOperand(0);
6787 EVT IntVT = Int.getValueType();
6788 if (IntVT.isInteger() && !IntVT.isVector()) {
6789 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6790 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6791 AddToWorkList(Int.getNode());
6792 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6797 // (fneg (fmul c, x)) -> (fmul -c, x)
6798 if (N0.getOpcode() == ISD::FMUL) {
6799 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6801 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6803 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6810 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6811 SDValue N0 = N->getOperand(0);
6812 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6813 EVT VT = N->getValueType(0);
6815 // fold (fceil c1) -> fceil(c1)
6817 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6822 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6823 SDValue N0 = N->getOperand(0);
6824 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6825 EVT VT = N->getValueType(0);
6827 // fold (ftrunc c1) -> ftrunc(c1)
6829 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6834 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6835 SDValue N0 = N->getOperand(0);
6836 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837 EVT VT = N->getValueType(0);
6839 // fold (ffloor c1) -> ffloor(c1)
6841 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6846 SDValue DAGCombiner::visitFABS(SDNode *N) {
6847 SDValue N0 = N->getOperand(0);
6848 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6849 EVT VT = N->getValueType(0);
6851 if (VT.isVector()) {
6852 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6853 if (FoldedVOp.getNode()) return FoldedVOp;
6856 // fold (fabs c1) -> fabs(c1)
6858 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6859 // fold (fabs (fabs x)) -> (fabs x)
6860 if (N0.getOpcode() == ISD::FABS)
6861 return N->getOperand(0);
6862 // fold (fabs (fneg x)) -> (fabs x)
6863 // fold (fabs (fcopysign x, y)) -> (fabs x)
6864 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6865 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6867 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6868 // constant pool values.
6869 if (!TLI.isFAbsFree(VT) &&
6870 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6871 N0.getOperand(0).getValueType().isInteger() &&
6872 !N0.getOperand(0).getValueType().isVector()) {
6873 SDValue Int = N0.getOperand(0);
6874 EVT IntVT = Int.getValueType();
6875 if (IntVT.isInteger() && !IntVT.isVector()) {
6876 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6877 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6878 AddToWorkList(Int.getNode());
6879 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6880 N->getValueType(0), Int);
6887 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6888 SDValue Chain = N->getOperand(0);
6889 SDValue N1 = N->getOperand(1);
6890 SDValue N2 = N->getOperand(2);
6892 // If N is a constant we could fold this into a fallthrough or unconditional
6893 // branch. However that doesn't happen very often in normal code, because
6894 // Instcombine/SimplifyCFG should have handled the available opportunities.
6895 // If we did this folding here, it would be necessary to update the
6896 // MachineBasicBlock CFG, which is awkward.
6898 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6900 if (N1.getOpcode() == ISD::SETCC &&
6901 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6902 N1.getOperand(0).getValueType())) {
6903 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6904 Chain, N1.getOperand(2),
6905 N1.getOperand(0), N1.getOperand(1), N2);
6908 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6909 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6910 (N1.getOperand(0).hasOneUse() &&
6911 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6913 if (N1.getOpcode() == ISD::TRUNCATE) {
6914 // Look pass the truncate.
6915 Trunc = N1.getNode();
6916 N1 = N1.getOperand(0);
6919 // Match this pattern so that we can generate simpler code:
6922 // %b = and i32 %a, 2
6923 // %c = srl i32 %b, 1
6924 // brcond i32 %c ...
6929 // %b = and i32 %a, 2
6930 // %c = setcc eq %b, 0
6933 // This applies only when the AND constant value has one bit set and the
6934 // SRL constant is equal to the log2 of the AND constant. The back-end is
6935 // smart enough to convert the result into a TEST/JMP sequence.
6936 SDValue Op0 = N1.getOperand(0);
6937 SDValue Op1 = N1.getOperand(1);
6939 if (Op0.getOpcode() == ISD::AND &&
6940 Op1.getOpcode() == ISD::Constant) {
6941 SDValue AndOp1 = Op0.getOperand(1);
6943 if (AndOp1.getOpcode() == ISD::Constant) {
6944 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6946 if (AndConst.isPowerOf2() &&
6947 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6949 DAG.getSetCC(SDLoc(N),
6950 getSetCCResultType(Op0.getValueType()),
6951 Op0, DAG.getConstant(0, Op0.getValueType()),
6954 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6955 MVT::Other, Chain, SetCC, N2);
6956 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6957 // will convert it back to (X & C1) >> C2.
6958 CombineTo(N, NewBRCond, false);
6959 // Truncate is dead.
6961 removeFromWorkList(Trunc);
6962 DAG.DeleteNode(Trunc);
6964 // Replace the uses of SRL with SETCC
6965 WorkListRemover DeadNodes(*this);
6966 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6967 removeFromWorkList(N1.getNode());
6968 DAG.DeleteNode(N1.getNode());
6969 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6975 // Restore N1 if the above transformation doesn't match.
6976 N1 = N->getOperand(1);
6979 // Transform br(xor(x, y)) -> br(x != y)
6980 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6981 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6982 SDNode *TheXor = N1.getNode();
6983 SDValue Op0 = TheXor->getOperand(0);
6984 SDValue Op1 = TheXor->getOperand(1);
6985 if (Op0.getOpcode() == Op1.getOpcode()) {
6986 // Avoid missing important xor optimizations.
6987 SDValue Tmp = visitXOR(TheXor);
6988 if (Tmp.getNode()) {
6989 if (Tmp.getNode() != TheXor) {
6990 DEBUG(dbgs() << "\nReplacing.8 ";
6992 dbgs() << "\nWith: ";
6993 Tmp.getNode()->dump(&DAG);
6995 WorkListRemover DeadNodes(*this);
6996 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6997 removeFromWorkList(TheXor);
6998 DAG.DeleteNode(TheXor);
6999 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7000 MVT::Other, Chain, Tmp, N2);
7003 // visitXOR has changed XOR's operands or replaced the XOR completely,
7005 return SDValue(N, 0);
7009 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7011 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7012 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7013 Op0.getOpcode() == ISD::XOR) {
7014 TheXor = Op0.getNode();
7018 EVT SetCCVT = N1.getValueType();
7020 SetCCVT = getSetCCResultType(SetCCVT);
7021 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7024 Equal ? ISD::SETEQ : ISD::SETNE);
7025 // Replace the uses of XOR with SETCC
7026 WorkListRemover DeadNodes(*this);
7027 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7028 removeFromWorkList(N1.getNode());
7029 DAG.DeleteNode(N1.getNode());
7030 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7031 MVT::Other, Chain, SetCC, N2);
7038 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7040 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7041 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7042 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7044 // If N is a constant we could fold this into a fallthrough or unconditional
7045 // branch. However that doesn't happen very often in normal code, because
7046 // Instcombine/SimplifyCFG should have handled the available opportunities.
7047 // If we did this folding here, it would be necessary to update the
7048 // MachineBasicBlock CFG, which is awkward.
7050 // Use SimplifySetCC to simplify SETCC's.
7051 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7052 CondLHS, CondRHS, CC->get(), SDLoc(N),
7054 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7056 // fold to a simpler setcc
7057 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7058 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7059 N->getOperand(0), Simp.getOperand(2),
7060 Simp.getOperand(0), Simp.getOperand(1),
7066 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7067 /// uses N as its base pointer and that N may be folded in the load / store
7068 /// addressing mode.
7069 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7071 const TargetLowering &TLI) {
7073 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7074 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7076 VT = Use->getValueType(0);
7077 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7078 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7080 VT = ST->getValue().getValueType();
7084 TargetLowering::AddrMode AM;
7085 if (N->getOpcode() == ISD::ADD) {
7086 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7089 AM.BaseOffs = Offset->getSExtValue();
7093 } else if (N->getOpcode() == ISD::SUB) {
7094 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7097 AM.BaseOffs = -Offset->getSExtValue();
7104 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7107 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7108 /// pre-indexed load / store when the base pointer is an add or subtract
7109 /// and it has other uses besides the load / store. After the
7110 /// transformation, the new indexed load / store has effectively folded
7111 /// the add / subtract in and all of its other uses are redirected to the
7112 /// new load / store.
7113 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7114 if (Level < AfterLegalizeDAG)
7120 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7121 if (LD->isIndexed())
7123 VT = LD->getMemoryVT();
7124 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7125 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7127 Ptr = LD->getBasePtr();
7128 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7129 if (ST->isIndexed())
7131 VT = ST->getMemoryVT();
7132 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7133 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7135 Ptr = ST->getBasePtr();
7141 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7142 // out. There is no reason to make this a preinc/predec.
7143 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7144 Ptr.getNode()->hasOneUse())
7147 // Ask the target to do addressing mode selection.
7150 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7151 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7154 // Backends without true r+i pre-indexed forms may need to pass a
7155 // constant base with a variable offset so that constant coercion
7156 // will work with the patterns in canonical form.
7157 bool Swapped = false;
7158 if (isa<ConstantSDNode>(BasePtr)) {
7159 std::swap(BasePtr, Offset);
7163 // Don't create a indexed load / store with zero offset.
7164 if (isa<ConstantSDNode>(Offset) &&
7165 cast<ConstantSDNode>(Offset)->isNullValue())
7168 // Try turning it into a pre-indexed load / store except when:
7169 // 1) The new base ptr is a frame index.
7170 // 2) If N is a store and the new base ptr is either the same as or is a
7171 // predecessor of the value being stored.
7172 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7173 // that would create a cycle.
7174 // 4) All uses are load / store ops that use it as old base ptr.
7176 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7177 // (plus the implicit offset) to a register to preinc anyway.
7178 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7183 SDValue Val = cast<StoreSDNode>(N)->getValue();
7184 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7188 // If the offset is a constant, there may be other adds of constants that
7189 // can be folded with this one. We should do this to avoid having to keep
7190 // a copy of the original base pointer.
7191 SmallVector<SDNode *, 16> OtherUses;
7192 if (isa<ConstantSDNode>(Offset))
7193 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7194 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7196 if (Use == Ptr.getNode())
7199 if (Use->isPredecessorOf(N))
7202 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7207 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7208 if (Op1.getNode() == BasePtr.getNode())
7209 std::swap(Op0, Op1);
7210 assert(Op0.getNode() == BasePtr.getNode() &&
7211 "Use of ADD/SUB but not an operand");
7213 if (!isa<ConstantSDNode>(Op1)) {
7218 // FIXME: In some cases, we can be smarter about this.
7219 if (Op1.getValueType() != Offset.getValueType()) {
7224 OtherUses.push_back(Use);
7228 std::swap(BasePtr, Offset);
7230 // Now check for #3 and #4.
7231 bool RealUse = false;
7233 // Caches for hasPredecessorHelper
7234 SmallPtrSet<const SDNode *, 32> Visited;
7235 SmallVector<const SDNode *, 16> Worklist;
7237 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7238 E = Ptr.getNode()->use_end(); I != E; ++I) {
7242 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7245 // If Ptr may be folded in addressing mode of other use, then it's
7246 // not profitable to do this transformation.
7247 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7256 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7257 BasePtr, Offset, AM);
7259 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7260 BasePtr, Offset, AM);
7263 DEBUG(dbgs() << "\nReplacing.4 ";
7265 dbgs() << "\nWith: ";
7266 Result.getNode()->dump(&DAG);
7268 WorkListRemover DeadNodes(*this);
7270 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7271 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7273 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7276 // Finally, since the node is now dead, remove it from the graph.
7280 std::swap(BasePtr, Offset);
7282 // Replace other uses of BasePtr that can be updated to use Ptr
7283 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7284 unsigned OffsetIdx = 1;
7285 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7287 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7288 BasePtr.getNode() && "Expected BasePtr operand");
7290 // We need to replace ptr0 in the following expression:
7291 // x0 * offset0 + y0 * ptr0 = t0
7293 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7295 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7296 // indexed load/store and the expresion that needs to be re-written.
7298 // Therefore, we have:
7299 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7301 ConstantSDNode *CN =
7302 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7304 APInt Offset0 = CN->getAPIntValue();
7305 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7307 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7308 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7309 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7310 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7312 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7314 APInt CNV = Offset0;
7315 if (X0 < 0) CNV = -CNV;
7316 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7317 else CNV = CNV - Offset1;
7319 // We can now generate the new expression.
7320 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7321 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7323 SDValue NewUse = DAG.getNode(Opcode,
7324 SDLoc(OtherUses[i]),
7325 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7326 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7327 removeFromWorkList(OtherUses[i]);
7328 DAG.DeleteNode(OtherUses[i]);
7331 // Replace the uses of Ptr with uses of the updated base value.
7332 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7333 removeFromWorkList(Ptr.getNode());
7334 DAG.DeleteNode(Ptr.getNode());
7339 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7340 /// add / sub of the base pointer node into a post-indexed load / store.
7341 /// The transformation folded the add / subtract into the new indexed
7342 /// load / store effectively and all of its uses are redirected to the
7343 /// new load / store.
7344 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7345 if (Level < AfterLegalizeDAG)
7351 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7352 if (LD->isIndexed())
7354 VT = LD->getMemoryVT();
7355 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7356 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7358 Ptr = LD->getBasePtr();
7359 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7360 if (ST->isIndexed())
7362 VT = ST->getMemoryVT();
7363 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7364 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7366 Ptr = ST->getBasePtr();
7372 if (Ptr.getNode()->hasOneUse())
7375 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7376 E = Ptr.getNode()->use_end(); I != E; ++I) {
7379 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7384 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7385 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7386 // Don't create a indexed load / store with zero offset.
7387 if (isa<ConstantSDNode>(Offset) &&
7388 cast<ConstantSDNode>(Offset)->isNullValue())
7391 // Try turning it into a post-indexed load / store except when
7392 // 1) All uses are load / store ops that use it as base ptr (and
7393 // it may be folded as addressing mmode).
7394 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7395 // nor a successor of N. Otherwise, if Op is folded that would
7398 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7402 bool TryNext = false;
7403 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7404 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7406 if (Use == Ptr.getNode())
7409 // If all the uses are load / store addresses, then don't do the
7411 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7412 bool RealUse = false;
7413 for (SDNode::use_iterator III = Use->use_begin(),
7414 EEE = Use->use_end(); III != EEE; ++III) {
7415 SDNode *UseUse = *III;
7416 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7431 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7432 SDValue Result = isLoad
7433 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7434 BasePtr, Offset, AM)
7435 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7436 BasePtr, Offset, AM);
7439 DEBUG(dbgs() << "\nReplacing.5 ";
7441 dbgs() << "\nWith: ";
7442 Result.getNode()->dump(&DAG);
7444 WorkListRemover DeadNodes(*this);
7446 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7452 // Finally, since the node is now dead, remove it from the graph.
7455 // Replace the uses of Use with uses of the updated base value.
7456 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7457 Result.getValue(isLoad ? 1 : 0));
7458 removeFromWorkList(Op);
7468 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7469 LoadSDNode *LD = cast<LoadSDNode>(N);
7470 SDValue Chain = LD->getChain();
7471 SDValue Ptr = LD->getBasePtr();
7473 // If load is not volatile and there are no uses of the loaded value (and
7474 // the updated indexed value in case of indexed loads), change uses of the
7475 // chain value into uses of the chain input (i.e. delete the dead load).
7476 if (!LD->isVolatile()) {
7477 if (N->getValueType(1) == MVT::Other) {
7479 if (!N->hasAnyUseOfValue(0)) {
7480 // It's not safe to use the two value CombineTo variant here. e.g.
7481 // v1, chain2 = load chain1, loc
7482 // v2, chain3 = load chain2, loc
7484 // Now we replace use of chain2 with chain1. This makes the second load
7485 // isomorphic to the one we are deleting, and thus makes this load live.
7486 DEBUG(dbgs() << "\nReplacing.6 ";
7488 dbgs() << "\nWith chain: ";
7489 Chain.getNode()->dump(&DAG);
7491 WorkListRemover DeadNodes(*this);
7492 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7494 if (N->use_empty()) {
7495 removeFromWorkList(N);
7499 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7503 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7504 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7505 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7506 DEBUG(dbgs() << "\nReplacing.7 ";
7508 dbgs() << "\nWith: ";
7509 Undef.getNode()->dump(&DAG);
7510 dbgs() << " and 2 other values\n");
7511 WorkListRemover DeadNodes(*this);
7512 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7513 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7514 DAG.getUNDEF(N->getValueType(1)));
7515 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7516 removeFromWorkList(N);
7518 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7523 // If this load is directly stored, replace the load value with the stored
7525 // TODO: Handle store large -> read small portion.
7526 // TODO: Handle TRUNCSTORE/LOADEXT
7527 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7528 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7529 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7530 if (PrevST->getBasePtr() == Ptr &&
7531 PrevST->getValue().getValueType() == N->getValueType(0))
7532 return CombineTo(N, Chain.getOperand(1), Chain);
7536 // Try to infer better alignment information than the load already has.
7537 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7538 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7539 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7541 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7542 LD->getValueType(0),
7543 Chain, Ptr, LD->getPointerInfo(),
7545 LD->isVolatile(), LD->isNonTemporal(), Align,
7547 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7552 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7553 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7555 // Walk up chain skipping non-aliasing memory nodes.
7556 SDValue BetterChain = FindBetterChain(N, Chain);
7558 // If there is a better chain.
7559 if (Chain != BetterChain) {
7562 // Replace the chain to void dependency.
7563 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7564 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7565 BetterChain, Ptr, LD->getMemOperand());
7567 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7568 LD->getValueType(0),
7569 BetterChain, Ptr, LD->getMemoryVT(),
7570 LD->getMemOperand());
7573 // Create token factor to keep old chain connected.
7574 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7575 MVT::Other, Chain, ReplLoad.getValue(1));
7577 // Make sure the new and old chains are cleaned up.
7578 AddToWorkList(Token.getNode());
7580 // Replace uses with load result and token factor. Don't add users
7582 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7586 // Try transforming N to an indexed load.
7587 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7588 return SDValue(N, 0);
7590 // Try to slice up N to more direct loads if the slices are mapped to
7591 // different register banks or pairing can take place.
7593 return SDValue(N, 0);
7599 /// \brief Helper structure used to slice a load in smaller loads.
7600 /// Basically a slice is obtained from the following sequence:
7601 /// Origin = load Ty1, Base
7602 /// Shift = srl Ty1 Origin, CstTy Amount
7603 /// Inst = trunc Shift to Ty2
7605 /// Then, it will be rewriten into:
7606 /// Slice = load SliceTy, Base + SliceOffset
7607 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7609 /// SliceTy is deduced from the number of bits that are actually used to
7611 struct LoadedSlice {
7612 /// \brief Helper structure used to compute the cost of a slice.
7614 /// Are we optimizing for code size.
7619 unsigned CrossRegisterBanksCopies;
7623 Cost(bool ForCodeSize = false)
7624 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7625 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7627 /// \brief Get the cost of one isolated slice.
7628 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7629 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7630 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7631 EVT TruncType = LS.Inst->getValueType(0);
7632 EVT LoadedType = LS.getLoadedType();
7633 if (TruncType != LoadedType &&
7634 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7638 /// \brief Account for slicing gain in the current cost.
7639 /// Slicing provide a few gains like removing a shift or a
7640 /// truncate. This method allows to grow the cost of the original
7641 /// load with the gain from this slice.
7642 void addSliceGain(const LoadedSlice &LS) {
7643 // Each slice saves a truncate.
7644 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7645 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7646 LS.Inst->getOperand(0).getValueType()))
7648 // If there is a shift amount, this slice gets rid of it.
7651 // If this slice can merge a cross register bank copy, account for it.
7652 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7653 ++CrossRegisterBanksCopies;
7656 Cost &operator+=(const Cost &RHS) {
7658 Truncates += RHS.Truncates;
7659 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7665 bool operator==(const Cost &RHS) const {
7666 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7667 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7668 ZExts == RHS.ZExts && Shift == RHS.Shift;
7671 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7673 bool operator<(const Cost &RHS) const {
7674 // Assume cross register banks copies are as expensive as loads.
7675 // FIXME: Do we want some more target hooks?
7676 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7677 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7678 // Unless we are optimizing for code size, consider the
7679 // expensive operation first.
7680 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7681 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7682 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7683 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7686 bool operator>(const Cost &RHS) const { return RHS < *this; }
7688 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7690 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7692 // The last instruction that represent the slice. This should be a
7693 // truncate instruction.
7695 // The original load instruction.
7697 // The right shift amount in bits from the original load.
7699 // The DAG from which Origin came from.
7700 // This is used to get some contextual information about legal types, etc.
7703 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7704 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7705 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7707 LoadedSlice(const LoadedSlice &LS)
7708 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7710 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7711 /// \return Result is \p BitWidth and has used bits set to 1 and
7712 /// not used bits set to 0.
7713 APInt getUsedBits() const {
7714 // Reproduce the trunc(lshr) sequence:
7715 // - Start from the truncated value.
7716 // - Zero extend to the desired bit width.
7718 assert(Origin && "No original load to compare against.");
7719 unsigned BitWidth = Origin->getValueSizeInBits(0);
7720 assert(Inst && "This slice is not bound to an instruction");
7721 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7722 "Extracted slice is bigger than the whole type!");
7723 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7724 UsedBits.setAllBits();
7725 UsedBits = UsedBits.zext(BitWidth);
7730 /// \brief Get the size of the slice to be loaded in bytes.
7731 unsigned getLoadedSize() const {
7732 unsigned SliceSize = getUsedBits().countPopulation();
7733 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7734 return SliceSize / 8;
7737 /// \brief Get the type that will be loaded for this slice.
7738 /// Note: This may not be the final type for the slice.
7739 EVT getLoadedType() const {
7740 assert(DAG && "Missing context");
7741 LLVMContext &Ctxt = *DAG->getContext();
7742 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7745 /// \brief Get the alignment of the load used for this slice.
7746 unsigned getAlignment() const {
7747 unsigned Alignment = Origin->getAlignment();
7748 unsigned Offset = getOffsetFromBase();
7750 Alignment = MinAlign(Alignment, Alignment + Offset);
7754 /// \brief Check if this slice can be rewritten with legal operations.
7755 bool isLegal() const {
7756 // An invalid slice is not legal.
7757 if (!Origin || !Inst || !DAG)
7760 // Offsets are for indexed load only, we do not handle that.
7761 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7764 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7766 // Check that the type is legal.
7767 EVT SliceType = getLoadedType();
7768 if (!TLI.isTypeLegal(SliceType))
7771 // Check that the load is legal for this type.
7772 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7775 // Check that the offset can be computed.
7776 // 1. Check its type.
7777 EVT PtrType = Origin->getBasePtr().getValueType();
7778 if (PtrType == MVT::Untyped || PtrType.isExtended())
7781 // 2. Check that it fits in the immediate.
7782 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7785 // 3. Check that the computation is legal.
7786 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7789 // Check that the zext is legal if it needs one.
7790 EVT TruncateType = Inst->getValueType(0);
7791 if (TruncateType != SliceType &&
7792 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7798 /// \brief Get the offset in bytes of this slice in the original chunk of
7800 /// \pre DAG != NULL.
7801 uint64_t getOffsetFromBase() const {
7802 assert(DAG && "Missing context.");
7804 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7805 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7806 uint64_t Offset = Shift / 8;
7807 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7808 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7809 "The size of the original loaded type is not a multiple of a"
7811 // If Offset is bigger than TySizeInBytes, it means we are loading all
7812 // zeros. This should have been optimized before in the process.
7813 assert(TySizeInBytes > Offset &&
7814 "Invalid shift amount for given loaded size");
7816 Offset = TySizeInBytes - Offset - getLoadedSize();
7820 /// \brief Generate the sequence of instructions to load the slice
7821 /// represented by this object and redirect the uses of this slice to
7822 /// this new sequence of instructions.
7823 /// \pre this->Inst && this->Origin are valid Instructions and this
7824 /// object passed the legal check: LoadedSlice::isLegal returned true.
7825 /// \return The last instruction of the sequence used to load the slice.
7826 SDValue loadSlice() const {
7827 assert(Inst && Origin && "Unable to replace a non-existing slice.");
7828 const SDValue &OldBaseAddr = Origin->getBasePtr();
7829 SDValue BaseAddr = OldBaseAddr;
7830 // Get the offset in that chunk of bytes w.r.t. the endianess.
7831 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7832 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7834 // BaseAddr = BaseAddr + Offset.
7835 EVT ArithType = BaseAddr.getValueType();
7836 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7837 DAG->getConstant(Offset, ArithType));
7840 // Create the type of the loaded slice according to its size.
7841 EVT SliceType = getLoadedType();
7843 // Create the load for the slice.
7844 SDValue LastInst = DAG->getLoad(
7845 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7846 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7847 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7848 // If the final type is not the same as the loaded type, this means that
7849 // we have to pad with zero. Create a zero extend for that.
7850 EVT FinalType = Inst->getValueType(0);
7851 if (SliceType != FinalType)
7853 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7857 /// \brief Check if this slice can be merged with an expensive cross register
7858 /// bank copy. E.g.,
7860 /// f = bitcast i32 i to float
7861 bool canMergeExpensiveCrossRegisterBankCopy() const {
7862 if (!Inst || !Inst->hasOneUse())
7864 SDNode *Use = *Inst->use_begin();
7865 if (Use->getOpcode() != ISD::BITCAST)
7867 assert(DAG && "Missing context");
7868 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7869 EVT ResVT = Use->getValueType(0);
7870 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7871 const TargetRegisterClass *ArgRC =
7872 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7873 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7876 // At this point, we know that we perform a cross-register-bank copy.
7877 // Check if it is expensive.
7878 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7879 // Assume bitcasts are cheap, unless both register classes do not
7880 // explicitly share a common sub class.
7881 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7884 // Check if it will be merged with the load.
7885 // 1. Check the alignment constraint.
7886 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7887 ResVT.getTypeForEVT(*DAG->getContext()));
7889 if (RequiredAlignment > getAlignment())
7892 // 2. Check that the load is a legal operation for that type.
7893 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7896 // 3. Check that we do not have a zext in the way.
7897 if (Inst->getValueType(0) != getLoadedType())
7905 /// \brief Sorts LoadedSlice according to their offset.
7906 struct LoadedSliceSorter {
7907 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7908 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7909 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7913 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7914 /// \p UsedBits looks like 0..0 1..1 0..0.
7915 static bool areUsedBitsDense(const APInt &UsedBits) {
7916 // If all the bits are one, this is dense!
7917 if (UsedBits.isAllOnesValue())
7920 // Get rid of the unused bits on the right.
7921 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7922 // Get rid of the unused bits on the left.
7923 if (NarrowedUsedBits.countLeadingZeros())
7924 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7925 // Check that the chunk of bits is completely used.
7926 return NarrowedUsedBits.isAllOnesValue();
7929 /// \brief Check whether or not \p First and \p Second are next to each other
7930 /// in memory. This means that there is no hole between the bits loaded
7931 /// by \p First and the bits loaded by \p Second.
7932 static bool areSlicesNextToEachOther(const LoadedSlice &First,
7933 const LoadedSlice &Second) {
7934 assert(First.Origin == Second.Origin && First.Origin &&
7935 "Unable to match different memory origins.");
7936 APInt UsedBits = First.getUsedBits();
7937 assert((UsedBits & Second.getUsedBits()) == 0 &&
7938 "Slices are not supposed to overlap.");
7939 UsedBits |= Second.getUsedBits();
7940 return areUsedBitsDense(UsedBits);
7943 /// \brief Adjust the \p GlobalLSCost according to the target
7944 /// paring capabilities and the layout of the slices.
7945 /// \pre \p GlobalLSCost should account for at least as many loads as
7946 /// there is in the slices in \p LoadedSlices.
7947 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
7948 LoadedSlice::Cost &GlobalLSCost) {
7949 unsigned NumberOfSlices = LoadedSlices.size();
7950 // If there is less than 2 elements, no pairing is possible.
7951 if (NumberOfSlices < 2)
7954 // Sort the slices so that elements that are likely to be next to each
7955 // other in memory are next to each other in the list.
7956 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
7957 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
7958 // First (resp. Second) is the first (resp. Second) potentially candidate
7959 // to be placed in a paired load.
7960 const LoadedSlice *First = NULL;
7961 const LoadedSlice *Second = NULL;
7962 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
7963 // Set the beginning of the pair.
7966 Second = &LoadedSlices[CurrSlice];
7968 // If First is NULL, it means we start a new pair.
7969 // Get to the next slice.
7973 EVT LoadedType = First->getLoadedType();
7975 // If the types of the slices are different, we cannot pair them.
7976 if (LoadedType != Second->getLoadedType())
7979 // Check if the target supplies paired loads for this type.
7980 unsigned RequiredAlignment = 0;
7981 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
7982 // move to the next pair, this type is hopeless.
7986 // Check if we meet the alignment requirement.
7987 if (RequiredAlignment > First->getAlignment())
7990 // Check that both loads are next to each other in memory.
7991 if (!areSlicesNextToEachOther(*First, *Second))
7994 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
7995 --GlobalLSCost.Loads;
7996 // Move to the next pair.
8001 /// \brief Check the profitability of all involved LoadedSlice.
8002 /// Currently, it is considered profitable if there is exactly two
8003 /// involved slices (1) which are (2) next to each other in memory, and
8004 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8006 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8007 /// the elements themselves.
8009 /// FIXME: When the cost model will be mature enough, we can relax
8010 /// constraints (1) and (2).
8011 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8012 const APInt &UsedBits, bool ForCodeSize) {
8013 unsigned NumberOfSlices = LoadedSlices.size();
8014 if (StressLoadSlicing)
8015 return NumberOfSlices > 1;
8018 if (NumberOfSlices != 2)
8022 if (!areUsedBitsDense(UsedBits))
8026 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8027 // The original code has one big load.
8029 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8030 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8031 // Accumulate the cost of all the slices.
8032 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8033 GlobalSlicingCost += SliceCost;
8035 // Account as cost in the original configuration the gain obtained
8036 // with the current slices.
8037 OrigCost.addSliceGain(LS);
8040 // If the target supports paired load, adjust the cost accordingly.
8041 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8042 return OrigCost > GlobalSlicingCost;
8045 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8046 /// operations, split it in the various pieces being extracted.
8048 /// This sort of thing is introduced by SROA.
8049 /// This slicing takes care not to insert overlapping loads.
8050 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8051 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8052 if (Level < AfterLegalizeDAG)
8055 LoadSDNode *LD = cast<LoadSDNode>(N);
8056 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8057 !LD->getValueType(0).isInteger())
8060 // Keep track of already used bits to detect overlapping values.
8061 // In that case, we will just abort the transformation.
8062 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8064 SmallVector<LoadedSlice, 4> LoadedSlices;
8066 // Check if this load is used as several smaller chunks of bits.
8067 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8068 // of computation for each trunc.
8069 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8070 UI != UIEnd; ++UI) {
8071 // Skip the uses of the chain.
8072 if (UI.getUse().getResNo() != 0)
8078 // Check if this is a trunc(lshr).
8079 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8080 isa<ConstantSDNode>(User->getOperand(1))) {
8081 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8082 User = *User->use_begin();
8085 // At this point, User is a Truncate, iff we encountered, trunc or
8087 if (User->getOpcode() != ISD::TRUNCATE)
8090 // The width of the type must be a power of 2 and greater than 8-bits.
8091 // Otherwise the load cannot be represented in LLVM IR.
8092 // Moreover, if we shifted with a non 8-bits multiple, the slice
8093 // will be accross several bytes. We do not support that.
8094 unsigned Width = User->getValueSizeInBits(0);
8095 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8098 // Build the slice for this chain of computations.
8099 LoadedSlice LS(User, LD, Shift, &DAG);
8100 APInt CurrentUsedBits = LS.getUsedBits();
8102 // Check if this slice overlaps with another.
8103 if ((CurrentUsedBits & UsedBits) != 0)
8105 // Update the bits used globally.
8106 UsedBits |= CurrentUsedBits;
8108 // Check if the new slice would be legal.
8112 // Record the slice.
8113 LoadedSlices.push_back(LS);
8116 // Abort slicing if it does not seem to be profitable.
8117 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8122 // Rewrite each chain to use an independent load.
8123 // By construction, each chain can be represented by a unique load.
8125 // Prepare the argument for the new token factor for all the slices.
8126 SmallVector<SDValue, 8> ArgChains;
8127 for (SmallVectorImpl<LoadedSlice>::const_iterator
8128 LSIt = LoadedSlices.begin(),
8129 LSItEnd = LoadedSlices.end();
8130 LSIt != LSItEnd; ++LSIt) {
8131 SDValue SliceInst = LSIt->loadSlice();
8132 CombineTo(LSIt->Inst, SliceInst, true);
8133 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8134 SliceInst = SliceInst.getOperand(0);
8135 assert(SliceInst->getOpcode() == ISD::LOAD &&
8136 "It takes more than a zext to get to the loaded slice!!");
8137 ArgChains.push_back(SliceInst.getValue(1));
8140 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8141 &ArgChains[0], ArgChains.size());
8142 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8146 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8147 /// load is having specific bytes cleared out. If so, return the byte size
8148 /// being masked out and the shift amount.
8149 static std::pair<unsigned, unsigned>
8150 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8151 std::pair<unsigned, unsigned> Result(0, 0);
8153 // Check for the structure we're looking for.
8154 if (V->getOpcode() != ISD::AND ||
8155 !isa<ConstantSDNode>(V->getOperand(1)) ||
8156 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8159 // Check the chain and pointer.
8160 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8161 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8163 // The store should be chained directly to the load or be an operand of a
8165 if (LD == Chain.getNode())
8167 else if (Chain->getOpcode() != ISD::TokenFactor)
8168 return Result; // Fail.
8171 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8172 if (Chain->getOperand(i).getNode() == LD) {
8176 if (!isOk) return Result;
8179 // This only handles simple types.
8180 if (V.getValueType() != MVT::i16 &&
8181 V.getValueType() != MVT::i32 &&
8182 V.getValueType() != MVT::i64)
8185 // Check the constant mask. Invert it so that the bits being masked out are
8186 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8187 // follow the sign bit for uniformity.
8188 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8189 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8190 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8191 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8192 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8193 if (NotMaskLZ == 64) return Result; // All zero mask.
8195 // See if we have a continuous run of bits. If so, we have 0*1+0*
8196 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8199 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8200 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8201 NotMaskLZ -= 64-V.getValueSizeInBits();
8203 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8204 switch (MaskedBytes) {
8208 default: return Result; // All one mask, or 5-byte mask.
8211 // Verify that the first bit starts at a multiple of mask so that the access
8212 // is aligned the same as the access width.
8213 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8215 Result.first = MaskedBytes;
8216 Result.second = NotMaskTZ/8;
8221 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8222 /// provides a value as specified by MaskInfo. If so, replace the specified
8223 /// store with a narrower store of truncated IVal.
8225 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8226 SDValue IVal, StoreSDNode *St,
8228 unsigned NumBytes = MaskInfo.first;
8229 unsigned ByteShift = MaskInfo.second;
8230 SelectionDAG &DAG = DC->getDAG();
8232 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8233 // that uses this. If not, this is not a replacement.
8234 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8235 ByteShift*8, (ByteShift+NumBytes)*8);
8236 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8238 // Check that it is legal on the target to do this. It is legal if the new
8239 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8241 MVT VT = MVT::getIntegerVT(NumBytes*8);
8242 if (!DC->isTypeLegal(VT))
8245 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8246 // shifted by ByteShift and truncated down to NumBytes.
8248 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8249 DAG.getConstant(ByteShift*8,
8250 DC->getShiftAmountTy(IVal.getValueType())));
8252 // Figure out the offset for the store and the alignment of the access.
8254 unsigned NewAlign = St->getAlignment();
8256 if (DAG.getTargetLoweringInfo().isLittleEndian())
8257 StOffset = ByteShift;
8259 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8261 SDValue Ptr = St->getBasePtr();
8263 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8264 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8265 NewAlign = MinAlign(NewAlign, StOffset);
8268 // Truncate down to the new size.
8269 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8272 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8273 St->getPointerInfo().getWithOffset(StOffset),
8274 false, false, NewAlign).getNode();
8278 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8279 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8280 /// of the loaded bits, try narrowing the load and store if it would end up
8281 /// being a win for performance or code size.
8282 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8283 StoreSDNode *ST = cast<StoreSDNode>(N);
8284 if (ST->isVolatile())
8287 SDValue Chain = ST->getChain();
8288 SDValue Value = ST->getValue();
8289 SDValue Ptr = ST->getBasePtr();
8290 EVT VT = Value.getValueType();
8292 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8295 unsigned Opc = Value.getOpcode();
8297 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8298 // is a byte mask indicating a consecutive number of bytes, check to see if
8299 // Y is known to provide just those bytes. If so, we try to replace the
8300 // load + replace + store sequence with a single (narrower) store, which makes
8302 if (Opc == ISD::OR) {
8303 std::pair<unsigned, unsigned> MaskedLoad;
8304 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8305 if (MaskedLoad.first)
8306 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8307 Value.getOperand(1), ST,this))
8308 return SDValue(NewST, 0);
8310 // Or is commutative, so try swapping X and Y.
8311 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8312 if (MaskedLoad.first)
8313 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8314 Value.getOperand(0), ST,this))
8315 return SDValue(NewST, 0);
8318 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8319 Value.getOperand(1).getOpcode() != ISD::Constant)
8322 SDValue N0 = Value.getOperand(0);
8323 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8324 Chain == SDValue(N0.getNode(), 1)) {
8325 LoadSDNode *LD = cast<LoadSDNode>(N0);
8326 if (LD->getBasePtr() != Ptr ||
8327 LD->getPointerInfo().getAddrSpace() !=
8328 ST->getPointerInfo().getAddrSpace())
8331 // Find the type to narrow it the load / op / store to.
8332 SDValue N1 = Value.getOperand(1);
8333 unsigned BitWidth = N1.getValueSizeInBits();
8334 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8335 if (Opc == ISD::AND)
8336 Imm ^= APInt::getAllOnesValue(BitWidth);
8337 if (Imm == 0 || Imm.isAllOnesValue())
8339 unsigned ShAmt = Imm.countTrailingZeros();
8340 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8341 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8342 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8343 while (NewBW < BitWidth &&
8344 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8345 TLI.isNarrowingProfitable(VT, NewVT))) {
8346 NewBW = NextPowerOf2(NewBW);
8347 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8349 if (NewBW >= BitWidth)
8352 // If the lsb changed does not start at the type bitwidth boundary,
8353 // start at the previous one.
8355 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8356 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8357 std::min(BitWidth, ShAmt + NewBW));
8358 if ((Imm & Mask) == Imm) {
8359 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8360 if (Opc == ISD::AND)
8361 NewImm ^= APInt::getAllOnesValue(NewBW);
8362 uint64_t PtrOff = ShAmt / 8;
8363 // For big endian targets, we need to adjust the offset to the pointer to
8364 // load the correct bytes.
8365 if (TLI.isBigEndian())
8366 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8368 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8369 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8370 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8373 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8374 Ptr.getValueType(), Ptr,
8375 DAG.getConstant(PtrOff, Ptr.getValueType()));
8376 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8377 LD->getChain(), NewPtr,
8378 LD->getPointerInfo().getWithOffset(PtrOff),
8379 LD->isVolatile(), LD->isNonTemporal(),
8380 LD->isInvariant(), NewAlign,
8382 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8383 DAG.getConstant(NewImm, NewVT));
8384 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8386 ST->getPointerInfo().getWithOffset(PtrOff),
8387 false, false, NewAlign);
8389 AddToWorkList(NewPtr.getNode());
8390 AddToWorkList(NewLD.getNode());
8391 AddToWorkList(NewVal.getNode());
8392 WorkListRemover DeadNodes(*this);
8393 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8402 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8403 /// if the load value isn't used by any other operations, then consider
8404 /// transforming the pair to integer load / store operations if the target
8405 /// deems the transformation profitable.
8406 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8407 StoreSDNode *ST = cast<StoreSDNode>(N);
8408 SDValue Chain = ST->getChain();
8409 SDValue Value = ST->getValue();
8410 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8411 Value.hasOneUse() &&
8412 Chain == SDValue(Value.getNode(), 1)) {
8413 LoadSDNode *LD = cast<LoadSDNode>(Value);
8414 EVT VT = LD->getMemoryVT();
8415 if (!VT.isFloatingPoint() ||
8416 VT != ST->getMemoryVT() ||
8417 LD->isNonTemporal() ||
8418 ST->isNonTemporal() ||
8419 LD->getPointerInfo().getAddrSpace() != 0 ||
8420 ST->getPointerInfo().getAddrSpace() != 0)
8423 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8424 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8425 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8426 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8427 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8430 unsigned LDAlign = LD->getAlignment();
8431 unsigned STAlign = ST->getAlignment();
8432 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8433 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8434 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8437 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8438 LD->getChain(), LD->getBasePtr(),
8439 LD->getPointerInfo(),
8440 false, false, false, LDAlign);
8442 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8443 NewLD, ST->getBasePtr(),
8444 ST->getPointerInfo(),
8445 false, false, STAlign);
8447 AddToWorkList(NewLD.getNode());
8448 AddToWorkList(NewST.getNode());
8449 WorkListRemover DeadNodes(*this);
8450 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8458 /// Helper struct to parse and store a memory address as base + index + offset.
8459 /// We ignore sign extensions when it is safe to do so.
8460 /// The following two expressions are not equivalent. To differentiate we need
8461 /// to store whether there was a sign extension involved in the index
8463 /// (load (i64 add (i64 copyfromreg %c)
8464 /// (i64 signextend (add (i8 load %index)
8468 /// (load (i64 add (i64 copyfromreg %c)
8469 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8471 struct BaseIndexOffset {
8475 bool IsIndexSignExt;
8477 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8479 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8480 bool IsIndexSignExt) :
8481 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8483 bool equalBaseIndex(const BaseIndexOffset &Other) {
8484 return Other.Base == Base && Other.Index == Index &&
8485 Other.IsIndexSignExt == IsIndexSignExt;
8488 /// Parses tree in Ptr for base, index, offset addresses.
8489 static BaseIndexOffset match(SDValue Ptr) {
8490 bool IsIndexSignExt = false;
8492 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8493 // instruction, then it could be just the BASE or everything else we don't
8494 // know how to handle. Just use Ptr as BASE and give up.
8495 if (Ptr->getOpcode() != ISD::ADD)
8496 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8498 // We know that we have at least an ADD instruction. Try to pattern match
8499 // the simple case of BASE + OFFSET.
8500 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8501 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8502 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8506 // Inside a loop the current BASE pointer is calculated using an ADD and a
8507 // MUL instruction. In this case Ptr is the actual BASE pointer.
8508 // (i64 add (i64 %array_ptr)
8509 // (i64 mul (i64 %induction_var)
8510 // (i64 %element_size)))
8511 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8512 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8514 // Look at Base + Index + Offset cases.
8515 SDValue Base = Ptr->getOperand(0);
8516 SDValue IndexOffset = Ptr->getOperand(1);
8518 // Skip signextends.
8519 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8520 IndexOffset = IndexOffset->getOperand(0);
8521 IsIndexSignExt = true;
8524 // Either the case of Base + Index (no offset) or something else.
8525 if (IndexOffset->getOpcode() != ISD::ADD)
8526 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8528 // Now we have the case of Base + Index + offset.
8529 SDValue Index = IndexOffset->getOperand(0);
8530 SDValue Offset = IndexOffset->getOperand(1);
8532 if (!isa<ConstantSDNode>(Offset))
8533 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8535 // Ignore signextends.
8536 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8537 Index = Index->getOperand(0);
8538 IsIndexSignExt = true;
8539 } else IsIndexSignExt = false;
8541 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8542 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8546 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8547 /// is located in a sequence of memory operations connected by a chain.
8549 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8550 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8551 // Ptr to the mem node.
8552 LSBaseSDNode *MemNode;
8553 // Offset from the base ptr.
8554 int64_t OffsetFromBase;
8555 // What is the sequence number of this mem node.
8556 // Lowest mem operand in the DAG starts at zero.
8557 unsigned SequenceNum;
8560 /// Sorts store nodes in a link according to their offset from a shared
8562 struct ConsecutiveMemoryChainSorter {
8563 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8564 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8568 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8569 EVT MemVT = St->getMemoryVT();
8570 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8571 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8572 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8574 // Don't merge vectors into wider inputs.
8575 if (MemVT.isVector() || !MemVT.isSimple())
8578 // Perform an early exit check. Do not bother looking at stored values that
8579 // are not constants or loads.
8580 SDValue StoredVal = St->getValue();
8581 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8582 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8586 // Only look at ends of store sequences.
8587 SDValue Chain = SDValue(St, 1);
8588 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8591 // This holds the base pointer, index, and the offset in bytes from the base
8593 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8595 // We must have a base and an offset.
8596 if (!BasePtr.Base.getNode())
8599 // Do not handle stores to undef base pointers.
8600 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8603 // Save the LoadSDNodes that we find in the chain.
8604 // We need to make sure that these nodes do not interfere with
8605 // any of the store nodes.
8606 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8608 // Save the StoreSDNodes that we find in the chain.
8609 SmallVector<MemOpLink, 8> StoreNodes;
8611 // Walk up the chain and look for nodes with offsets from the same
8612 // base pointer. Stop when reaching an instruction with a different kind
8613 // or instruction which has a different base pointer.
8615 StoreSDNode *Index = St;
8617 // If the chain has more than one use, then we can't reorder the mem ops.
8618 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8621 // Find the base pointer and offset for this memory node.
8622 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8624 // Check that the base pointer is the same as the original one.
8625 if (!Ptr.equalBaseIndex(BasePtr))
8628 // Check that the alignment is the same.
8629 if (Index->getAlignment() != St->getAlignment())
8632 // The memory operands must not be volatile.
8633 if (Index->isVolatile() || Index->isIndexed())
8637 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8638 if (St->isTruncatingStore())
8641 // The stored memory type must be the same.
8642 if (Index->getMemoryVT() != MemVT)
8645 // We do not allow unaligned stores because we want to prevent overriding
8647 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8650 // We found a potential memory operand to merge.
8651 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8653 // Find the next memory operand in the chain. If the next operand in the
8654 // chain is a store then move up and continue the scan with the next
8655 // memory operand. If the next operand is a load save it and use alias
8656 // information to check if it interferes with anything.
8657 SDNode *NextInChain = Index->getChain().getNode();
8659 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8660 // We found a store node. Use it for the next iteration.
8663 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8664 // Save the load node for later. Continue the scan.
8665 AliasLoadNodes.push_back(Ldn);
8666 NextInChain = Ldn->getChain().getNode();
8675 // Check if there is anything to merge.
8676 if (StoreNodes.size() < 2)
8679 // Sort the memory operands according to their distance from the base pointer.
8680 std::sort(StoreNodes.begin(), StoreNodes.end(),
8681 ConsecutiveMemoryChainSorter());
8683 // Scan the memory operations on the chain and find the first non-consecutive
8684 // store memory address.
8685 unsigned LastConsecutiveStore = 0;
8686 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8687 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8689 // Check that the addresses are consecutive starting from the second
8690 // element in the list of stores.
8692 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8693 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8698 // Check if this store interferes with any of the loads that we found.
8699 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8700 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8704 // We found a load that alias with this store. Stop the sequence.
8708 // Mark this node as useful.
8709 LastConsecutiveStore = i;
8712 // The node with the lowest store address.
8713 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8715 // Store the constants into memory as one consecutive store.
8717 unsigned LastLegalType = 0;
8718 unsigned LastLegalVectorType = 0;
8719 bool NonZero = false;
8720 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8721 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8722 SDValue StoredVal = St->getValue();
8724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8725 NonZero |= !C->isNullValue();
8726 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8727 NonZero |= !C->getConstantFPValue()->isNullValue();
8733 // Find a legal type for the constant store.
8734 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8735 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8736 if (TLI.isTypeLegal(StoreTy))
8737 LastLegalType = i+1;
8738 // Or check whether a truncstore is legal.
8739 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8740 TargetLowering::TypePromoteInteger) {
8741 EVT LegalizedStoredValueTy =
8742 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8743 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8744 LastLegalType = i+1;
8747 // Find a legal type for the vector store.
8748 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8749 if (TLI.isTypeLegal(Ty))
8750 LastLegalVectorType = i + 1;
8753 // We only use vectors if the constant is known to be zero and the
8754 // function is not marked with the noimplicitfloat attribute.
8755 if (NonZero || NoVectors)
8756 LastLegalVectorType = 0;
8758 // Check if we found a legal integer type to store.
8759 if (LastLegalType == 0 && LastLegalVectorType == 0)
8762 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8763 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8765 // Make sure we have something to merge.
8769 unsigned EarliestNodeUsed = 0;
8770 for (unsigned i=0; i < NumElem; ++i) {
8771 // Find a chain for the new wide-store operand. Notice that some
8772 // of the store nodes that we found may not be selected for inclusion
8773 // in the wide store. The chain we use needs to be the chain of the
8774 // earliest store node which is *used* and replaced by the wide store.
8775 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8776 EarliestNodeUsed = i;
8779 // The earliest Node in the DAG.
8780 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8781 SDLoc DL(StoreNodes[0].MemNode);
8785 // Find a legal type for the vector store.
8786 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8787 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8788 StoredVal = DAG.getConstant(0, Ty);
8790 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8791 APInt StoreInt(StoreBW, 0);
8793 // Construct a single integer constant which is made of the smaller
8795 bool IsLE = TLI.isLittleEndian();
8796 for (unsigned i = 0; i < NumElem ; ++i) {
8797 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8798 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8799 SDValue Val = St->getValue();
8800 StoreInt<<=ElementSizeBytes*8;
8801 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8802 StoreInt|=C->getAPIntValue().zext(StoreBW);
8803 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8804 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8806 assert(false && "Invalid constant element type");
8810 // Create the new Load and Store operations.
8811 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8812 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8815 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8816 FirstInChain->getBasePtr(),
8817 FirstInChain->getPointerInfo(),
8819 FirstInChain->getAlignment());
8821 // Replace the first store with the new store
8822 CombineTo(EarliestOp, NewStore);
8823 // Erase all other stores.
8824 for (unsigned i = 0; i < NumElem ; ++i) {
8825 if (StoreNodes[i].MemNode == EarliestOp)
8827 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8828 // ReplaceAllUsesWith will replace all uses that existed when it was
8829 // called, but graph optimizations may cause new ones to appear. For
8830 // example, the case in pr14333 looks like
8832 // St's chain -> St -> another store -> X
8834 // And the only difference from St to the other store is the chain.
8835 // When we change it's chain to be St's chain they become identical,
8836 // get CSEed and the net result is that X is now a use of St.
8837 // Since we know that St is redundant, just iterate.
8838 while (!St->use_empty())
8839 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8840 removeFromWorkList(St);
8847 // Below we handle the case of multiple consecutive stores that
8848 // come from multiple consecutive loads. We merge them into a single
8849 // wide load and a single wide store.
8851 // Look for load nodes which are used by the stored values.
8852 SmallVector<MemOpLink, 8> LoadNodes;
8854 // Find acceptable loads. Loads need to have the same chain (token factor),
8855 // must not be zext, volatile, indexed, and they must be consecutive.
8856 BaseIndexOffset LdBasePtr;
8857 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8858 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8859 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8862 // Loads must only have one use.
8863 if (!Ld->hasNUsesOfValue(1, 0))
8866 // Check that the alignment is the same as the stores.
8867 if (Ld->getAlignment() != St->getAlignment())
8870 // The memory operands must not be volatile.
8871 if (Ld->isVolatile() || Ld->isIndexed())
8874 // We do not accept ext loads.
8875 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8878 // The stored memory type must be the same.
8879 if (Ld->getMemoryVT() != MemVT)
8882 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8883 // If this is not the first ptr that we check.
8884 if (LdBasePtr.Base.getNode()) {
8885 // The base ptr must be the same.
8886 if (!LdPtr.equalBaseIndex(LdBasePtr))
8889 // Check that all other base pointers are the same as this one.
8893 // We found a potential memory operand to merge.
8894 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8897 if (LoadNodes.size() < 2)
8900 // Scan the memory operations on the chain and find the first non-consecutive
8901 // load memory address. These variables hold the index in the store node
8903 unsigned LastConsecutiveLoad = 0;
8904 // This variable refers to the size and not index in the array.
8905 unsigned LastLegalVectorType = 0;
8906 unsigned LastLegalIntegerType = 0;
8907 StartAddress = LoadNodes[0].OffsetFromBase;
8908 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8909 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8910 // All loads much share the same chain.
8911 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8914 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8915 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8917 LastConsecutiveLoad = i;
8919 // Find a legal type for the vector store.
8920 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8921 if (TLI.isTypeLegal(StoreTy))
8922 LastLegalVectorType = i + 1;
8924 // Find a legal type for the integer store.
8925 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8926 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8927 if (TLI.isTypeLegal(StoreTy))
8928 LastLegalIntegerType = i + 1;
8929 // Or check whether a truncstore and extload is legal.
8930 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8931 TargetLowering::TypePromoteInteger) {
8932 EVT LegalizedStoredValueTy =
8933 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8934 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8935 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8936 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8937 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8938 LastLegalIntegerType = i+1;
8942 // Only use vector types if the vector type is larger than the integer type.
8943 // If they are the same, use integers.
8944 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8945 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8947 // We add +1 here because the LastXXX variables refer to location while
8948 // the NumElem refers to array/index size.
8949 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8950 NumElem = std::min(LastLegalType, NumElem);
8955 // The earliest Node in the DAG.
8956 unsigned EarliestNodeUsed = 0;
8957 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8958 for (unsigned i=1; i<NumElem; ++i) {
8959 // Find a chain for the new wide-store operand. Notice that some
8960 // of the store nodes that we found may not be selected for inclusion
8961 // in the wide store. The chain we use needs to be the chain of the
8962 // earliest store node which is *used* and replaced by the wide store.
8963 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8964 EarliestNodeUsed = i;
8967 // Find if it is better to use vectors or integers to load and store
8971 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8973 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8974 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8977 SDLoc LoadDL(LoadNodes[0].MemNode);
8978 SDLoc StoreDL(StoreNodes[0].MemNode);
8980 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8981 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8982 FirstLoad->getChain(),
8983 FirstLoad->getBasePtr(),
8984 FirstLoad->getPointerInfo(),
8985 false, false, false,
8986 FirstLoad->getAlignment());
8988 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8989 FirstInChain->getBasePtr(),
8990 FirstInChain->getPointerInfo(), false, false,
8991 FirstInChain->getAlignment());
8993 // Replace one of the loads with the new load.
8994 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8995 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8996 SDValue(NewLoad.getNode(), 1));
8998 // Remove the rest of the load chains.
8999 for (unsigned i = 1; i < NumElem ; ++i) {
9000 // Replace all chain users of the old load nodes with the chain of the new
9002 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9003 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9006 // Replace the first store with the new store.
9007 CombineTo(EarliestOp, NewStore);
9008 // Erase all other stores.
9009 for (unsigned i = 0; i < NumElem ; ++i) {
9010 // Remove all Store nodes.
9011 if (StoreNodes[i].MemNode == EarliestOp)
9013 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9014 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9015 removeFromWorkList(St);
9022 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9023 StoreSDNode *ST = cast<StoreSDNode>(N);
9024 SDValue Chain = ST->getChain();
9025 SDValue Value = ST->getValue();
9026 SDValue Ptr = ST->getBasePtr();
9028 // If this is a store of a bit convert, store the input value if the
9029 // resultant store does not need a higher alignment than the original.
9030 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9031 ST->isUnindexed()) {
9032 unsigned OrigAlign = ST->getAlignment();
9033 EVT SVT = Value.getOperand(0).getValueType();
9034 unsigned Align = TLI.getDataLayout()->
9035 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9036 if (Align <= OrigAlign &&
9037 ((!LegalOperations && !ST->isVolatile()) ||
9038 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9039 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9040 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9041 ST->isNonTemporal(), OrigAlign,
9045 // Turn 'store undef, Ptr' -> nothing.
9046 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9049 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9050 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9051 // NOTE: If the original store is volatile, this transform must not increase
9052 // the number of stores. For example, on x86-32 an f64 can be stored in one
9053 // processor operation but an i64 (which is not legal) requires two. So the
9054 // transform should not be done in this case.
9055 if (Value.getOpcode() != ISD::TargetConstantFP) {
9057 switch (CFP->getSimpleValueType(0).SimpleTy) {
9058 default: llvm_unreachable("Unknown FP type");
9059 case MVT::f16: // We don't do this for these yet.
9065 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9066 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9067 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9068 bitcastToAPInt().getZExtValue(), MVT::i32);
9069 return DAG.getStore(Chain, SDLoc(N), Tmp,
9070 Ptr, ST->getMemOperand());
9074 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9075 !ST->isVolatile()) ||
9076 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9077 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9078 getZExtValue(), MVT::i64);
9079 return DAG.getStore(Chain, SDLoc(N), Tmp,
9080 Ptr, ST->getMemOperand());
9083 if (!ST->isVolatile() &&
9084 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9085 // Many FP stores are not made apparent until after legalize, e.g. for
9086 // argument passing. Since this is so common, custom legalize the
9087 // 64-bit integer store into two 32-bit stores.
9088 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9089 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9090 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9091 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9093 unsigned Alignment = ST->getAlignment();
9094 bool isVolatile = ST->isVolatile();
9095 bool isNonTemporal = ST->isNonTemporal();
9096 const MDNode *TBAAInfo = ST->getTBAAInfo();
9098 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9099 Ptr, ST->getPointerInfo(),
9100 isVolatile, isNonTemporal,
9101 ST->getAlignment(), TBAAInfo);
9102 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9103 DAG.getConstant(4, Ptr.getValueType()));
9104 Alignment = MinAlign(Alignment, 4U);
9105 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9106 Ptr, ST->getPointerInfo().getWithOffset(4),
9107 isVolatile, isNonTemporal,
9108 Alignment, TBAAInfo);
9109 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9118 // Try to infer better alignment information than the store already has.
9119 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9120 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9121 if (Align > ST->getAlignment())
9122 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9123 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9124 ST->isVolatile(), ST->isNonTemporal(), Align,
9129 // Try transforming a pair floating point load / store ops to integer
9130 // load / store ops.
9131 SDValue NewST = TransformFPLoadStorePair(N);
9132 if (NewST.getNode())
9135 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9136 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9138 // Walk up chain skipping non-aliasing memory nodes.
9139 SDValue BetterChain = FindBetterChain(N, Chain);
9141 // If there is a better chain.
9142 if (Chain != BetterChain) {
9145 // Replace the chain to avoid dependency.
9146 if (ST->isTruncatingStore()) {
9147 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9148 ST->getMemoryVT(), ST->getMemOperand());
9150 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9151 ST->getMemOperand());
9154 // Create token to keep both nodes around.
9155 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9156 MVT::Other, Chain, ReplStore);
9158 // Make sure the new and old chains are cleaned up.
9159 AddToWorkList(Token.getNode());
9161 // Don't add users to work list.
9162 return CombineTo(N, Token, false);
9166 // Try transforming N to an indexed store.
9167 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9168 return SDValue(N, 0);
9170 // FIXME: is there such a thing as a truncating indexed store?
9171 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9172 Value.getValueType().isInteger()) {
9173 // See if we can simplify the input to this truncstore with knowledge that
9174 // only the low bits are being used. For example:
9175 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9177 GetDemandedBits(Value,
9178 APInt::getLowBitsSet(
9179 Value.getValueType().getScalarType().getSizeInBits(),
9180 ST->getMemoryVT().getScalarType().getSizeInBits()));
9181 AddToWorkList(Value.getNode());
9182 if (Shorter.getNode())
9183 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9184 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9186 // Otherwise, see if we can simplify the operation with
9187 // SimplifyDemandedBits, which only works if the value has a single use.
9188 if (SimplifyDemandedBits(Value,
9189 APInt::getLowBitsSet(
9190 Value.getValueType().getScalarType().getSizeInBits(),
9191 ST->getMemoryVT().getScalarType().getSizeInBits())))
9192 return SDValue(N, 0);
9195 // If this is a load followed by a store to the same location, then the store
9197 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9198 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9199 ST->isUnindexed() && !ST->isVolatile() &&
9200 // There can't be any side effects between the load and store, such as
9202 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9203 // The store is dead, remove it.
9208 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9209 // truncating store. We can do this even if this is already a truncstore.
9210 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9211 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9212 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9213 ST->getMemoryVT())) {
9214 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9215 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9218 // Only perform this optimization before the types are legal, because we
9219 // don't want to perform this optimization on every DAGCombine invocation.
9221 bool EverChanged = false;
9224 // There can be multiple store sequences on the same chain.
9225 // Keep trying to merge store sequences until we are unable to do so
9226 // or until we merge the last store on the chain.
9227 bool Changed = MergeConsecutiveStores(ST);
9228 EverChanged |= Changed;
9229 if (!Changed) break;
9230 } while (ST->getOpcode() != ISD::DELETED_NODE);
9233 return SDValue(N, 0);
9236 return ReduceLoadOpStoreWidth(N);
9239 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9240 SDValue InVec = N->getOperand(0);
9241 SDValue InVal = N->getOperand(1);
9242 SDValue EltNo = N->getOperand(2);
9245 // If the inserted element is an UNDEF, just use the input vector.
9246 if (InVal.getOpcode() == ISD::UNDEF)
9249 EVT VT = InVec.getValueType();
9251 // If we can't generate a legal BUILD_VECTOR, exit
9252 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9255 // Check that we know which element is being inserted
9256 if (!isa<ConstantSDNode>(EltNo))
9258 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9260 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9261 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9263 SmallVector<SDValue, 8> Ops;
9264 // Do not combine these two vectors if the output vector will not replace
9265 // the input vector.
9266 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9267 Ops.append(InVec.getNode()->op_begin(),
9268 InVec.getNode()->op_end());
9269 } else if (InVec.getOpcode() == ISD::UNDEF) {
9270 unsigned NElts = VT.getVectorNumElements();
9271 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9276 // Insert the element
9277 if (Elt < Ops.size()) {
9278 // All the operands of BUILD_VECTOR must have the same type;
9279 // we enforce that here.
9280 EVT OpVT = Ops[0].getValueType();
9281 if (InVal.getValueType() != OpVT)
9282 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9283 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9284 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9288 // Return the new vector
9289 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9290 VT, &Ops[0], Ops.size());
9293 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9294 // (vextract (scalar_to_vector val, 0) -> val
9295 SDValue InVec = N->getOperand(0);
9296 EVT VT = InVec.getValueType();
9297 EVT NVT = N->getValueType(0);
9299 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9300 // Check if the result type doesn't match the inserted element type. A
9301 // SCALAR_TO_VECTOR may truncate the inserted element and the
9302 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9303 SDValue InOp = InVec.getOperand(0);
9304 if (InOp.getValueType() != NVT) {
9305 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9306 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9311 SDValue EltNo = N->getOperand(1);
9312 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9314 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9315 // We only perform this optimization before the op legalization phase because
9316 // we may introduce new vector instructions which are not backed by TD
9317 // patterns. For example on AVX, extracting elements from a wide vector
9318 // without using extract_subvector.
9319 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9320 && ConstEltNo && !LegalOperations) {
9321 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9322 int NumElem = VT.getVectorNumElements();
9323 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9324 // Find the new index to extract from.
9325 int OrigElt = SVOp->getMaskElt(Elt);
9327 // Extracting an undef index is undef.
9329 return DAG.getUNDEF(NVT);
9331 // Select the right vector half to extract from.
9332 if (OrigElt < NumElem) {
9333 InVec = InVec->getOperand(0);
9335 InVec = InVec->getOperand(1);
9339 EVT IndexTy = TLI.getVectorIdxTy();
9340 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9341 InVec, DAG.getConstant(OrigElt, IndexTy));
9344 // Perform only after legalization to ensure build_vector / vector_shuffle
9345 // optimizations have already been done.
9346 if (!LegalOperations) return SDValue();
9348 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9349 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9350 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9353 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9354 bool NewLoad = false;
9355 bool BCNumEltsChanged = false;
9356 EVT ExtVT = VT.getVectorElementType();
9359 // If the result of load has to be truncated, then it's not necessarily
9361 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9364 if (InVec.getOpcode() == ISD::BITCAST) {
9365 // Don't duplicate a load with other uses.
9366 if (!InVec.hasOneUse())
9369 EVT BCVT = InVec.getOperand(0).getValueType();
9370 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9372 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9373 BCNumEltsChanged = true;
9374 InVec = InVec.getOperand(0);
9375 ExtVT = BCVT.getVectorElementType();
9379 LoadSDNode *LN0 = NULL;
9380 const ShuffleVectorSDNode *SVN = NULL;
9381 if (ISD::isNormalLoad(InVec.getNode())) {
9382 LN0 = cast<LoadSDNode>(InVec);
9383 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9384 InVec.getOperand(0).getValueType() == ExtVT &&
9385 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9386 // Don't duplicate a load with other uses.
9387 if (!InVec.hasOneUse())
9390 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9391 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9392 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9394 // (load $addr+1*size)
9396 // Don't duplicate a load with other uses.
9397 if (!InVec.hasOneUse())
9400 // If the bit convert changed the number of elements, it is unsafe
9401 // to examine the mask.
9402 if (BCNumEltsChanged)
9405 // Select the input vector, guarding against out of range extract vector.
9406 unsigned NumElems = VT.getVectorNumElements();
9407 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9408 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9410 if (InVec.getOpcode() == ISD::BITCAST) {
9411 // Don't duplicate a load with other uses.
9412 if (!InVec.hasOneUse())
9415 InVec = InVec.getOperand(0);
9417 if (ISD::isNormalLoad(InVec.getNode())) {
9418 LN0 = cast<LoadSDNode>(InVec);
9419 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9423 // Make sure we found a non-volatile load and the extractelement is
9425 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9428 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9430 return DAG.getUNDEF(LVT);
9432 unsigned Align = LN0->getAlignment();
9434 // Check the resultant load doesn't need a higher alignment than the
9438 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9440 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9446 SDValue NewPtr = LN0->getBasePtr();
9447 unsigned PtrOff = 0;
9450 PtrOff = LVT.getSizeInBits() * Elt / 8;
9451 EVT PtrType = NewPtr.getValueType();
9452 if (TLI.isBigEndian())
9453 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9454 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9455 DAG.getConstant(PtrOff, PtrType));
9458 // The replacement we need to do here is a little tricky: we need to
9459 // replace an extractelement of a load with a load.
9460 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9461 // Note that this replacement assumes that the extractvalue is the only
9462 // use of the load; that's okay because we don't want to perform this
9463 // transformation in other cases anyway.
9466 if (NVT.bitsGT(LVT)) {
9467 // If the result type of vextract is wider than the load, then issue an
9468 // extending load instead.
9469 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9470 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9471 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9472 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9473 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9474 Align, LN0->getTBAAInfo());
9475 Chain = Load.getValue(1);
9477 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9478 LN0->getPointerInfo().getWithOffset(PtrOff),
9479 LN0->isVolatile(), LN0->isNonTemporal(),
9480 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9481 Chain = Load.getValue(1);
9482 if (NVT.bitsLT(LVT))
9483 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9485 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9487 WorkListRemover DeadNodes(*this);
9488 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9489 SDValue To[] = { Load, Chain };
9490 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9491 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9492 // worklist explicitly as well.
9493 AddToWorkList(Load.getNode());
9494 AddUsersToWorkList(Load.getNode()); // Add users too
9495 // Make sure to revisit this node to clean it up; it will usually be dead.
9497 return SDValue(N, 0);
9503 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9504 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9505 // We perform this optimization post type-legalization because
9506 // the type-legalizer often scalarizes integer-promoted vectors.
9507 // Performing this optimization before may create bit-casts which
9508 // will be type-legalized to complex code sequences.
9509 // We perform this optimization only before the operation legalizer because we
9510 // may introduce illegal operations.
9511 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9514 unsigned NumInScalars = N->getNumOperands();
9516 EVT VT = N->getValueType(0);
9518 // Check to see if this is a BUILD_VECTOR of a bunch of values
9519 // which come from any_extend or zero_extend nodes. If so, we can create
9520 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9521 // optimizations. We do not handle sign-extend because we can't fill the sign
9523 EVT SourceType = MVT::Other;
9524 bool AllAnyExt = true;
9526 for (unsigned i = 0; i != NumInScalars; ++i) {
9527 SDValue In = N->getOperand(i);
9528 // Ignore undef inputs.
9529 if (In.getOpcode() == ISD::UNDEF) continue;
9531 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9532 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9534 // Abort if the element is not an extension.
9535 if (!ZeroExt && !AnyExt) {
9536 SourceType = MVT::Other;
9540 // The input is a ZeroExt or AnyExt. Check the original type.
9541 EVT InTy = In.getOperand(0).getValueType();
9543 // Check that all of the widened source types are the same.
9544 if (SourceType == MVT::Other)
9547 else if (InTy != SourceType) {
9548 // Multiple income types. Abort.
9549 SourceType = MVT::Other;
9553 // Check if all of the extends are ANY_EXTENDs.
9554 AllAnyExt &= AnyExt;
9557 // In order to have valid types, all of the inputs must be extended from the
9558 // same source type and all of the inputs must be any or zero extend.
9559 // Scalar sizes must be a power of two.
9560 EVT OutScalarTy = VT.getScalarType();
9561 bool ValidTypes = SourceType != MVT::Other &&
9562 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9563 isPowerOf2_32(SourceType.getSizeInBits());
9565 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9566 // turn into a single shuffle instruction.
9570 bool isLE = TLI.isLittleEndian();
9571 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9572 assert(ElemRatio > 1 && "Invalid element size ratio");
9573 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9574 DAG.getConstant(0, SourceType);
9576 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9577 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9579 // Populate the new build_vector
9580 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9581 SDValue Cast = N->getOperand(i);
9582 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9583 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9584 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9586 if (Cast.getOpcode() == ISD::UNDEF)
9587 In = DAG.getUNDEF(SourceType);
9589 In = Cast->getOperand(0);
9590 unsigned Index = isLE ? (i * ElemRatio) :
9591 (i * ElemRatio + (ElemRatio - 1));
9593 assert(Index < Ops.size() && "Invalid index");
9597 // The type of the new BUILD_VECTOR node.
9598 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9599 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9600 "Invalid vector size");
9601 // Check if the new vector type is legal.
9602 if (!isTypeLegal(VecVT)) return SDValue();
9604 // Make the new BUILD_VECTOR.
9605 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9607 // The new BUILD_VECTOR node has the potential to be further optimized.
9608 AddToWorkList(BV.getNode());
9609 // Bitcast to the desired type.
9610 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9613 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9614 EVT VT = N->getValueType(0);
9616 unsigned NumInScalars = N->getNumOperands();
9619 EVT SrcVT = MVT::Other;
9620 unsigned Opcode = ISD::DELETED_NODE;
9621 unsigned NumDefs = 0;
9623 for (unsigned i = 0; i != NumInScalars; ++i) {
9624 SDValue In = N->getOperand(i);
9625 unsigned Opc = In.getOpcode();
9627 if (Opc == ISD::UNDEF)
9630 // If all scalar values are floats and converted from integers.
9631 if (Opcode == ISD::DELETED_NODE &&
9632 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9639 EVT InVT = In.getOperand(0).getValueType();
9641 // If all scalar values are typed differently, bail out. It's chosen to
9642 // simplify BUILD_VECTOR of integer types.
9643 if (SrcVT == MVT::Other)
9650 // If the vector has just one element defined, it's not worth to fold it into
9651 // a vectorized one.
9655 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9656 && "Should only handle conversion from integer to float.");
9657 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9659 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9661 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9664 SmallVector<SDValue, 8> Opnds;
9665 for (unsigned i = 0; i != NumInScalars; ++i) {
9666 SDValue In = N->getOperand(i);
9668 if (In.getOpcode() == ISD::UNDEF)
9669 Opnds.push_back(DAG.getUNDEF(SrcVT));
9671 Opnds.push_back(In.getOperand(0));
9673 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9674 &Opnds[0], Opnds.size());
9675 AddToWorkList(BV.getNode());
9677 return DAG.getNode(Opcode, dl, VT, BV);
9680 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9681 unsigned NumInScalars = N->getNumOperands();
9683 EVT VT = N->getValueType(0);
9685 // A vector built entirely of undefs is undef.
9686 if (ISD::allOperandsUndef(N))
9687 return DAG.getUNDEF(VT);
9689 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9693 V = reduceBuildVecConvertToConvertBuildVec(N);
9697 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9698 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9699 // at most two distinct vectors, turn this into a shuffle node.
9701 // May only combine to shuffle after legalize if shuffle is legal.
9702 if (LegalOperations &&
9703 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9706 SDValue VecIn1, VecIn2;
9707 for (unsigned i = 0; i != NumInScalars; ++i) {
9708 // Ignore undef inputs.
9709 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9711 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9712 // constant index, bail out.
9713 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9714 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9715 VecIn1 = VecIn2 = SDValue(0, 0);
9719 // We allow up to two distinct input vectors.
9720 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9721 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9724 if (VecIn1.getNode() == 0) {
9725 VecIn1 = ExtractedFromVec;
9726 } else if (VecIn2.getNode() == 0) {
9727 VecIn2 = ExtractedFromVec;
9730 VecIn1 = VecIn2 = SDValue(0, 0);
9735 // If everything is good, we can make a shuffle operation.
9736 if (VecIn1.getNode()) {
9737 SmallVector<int, 8> Mask;
9738 for (unsigned i = 0; i != NumInScalars; ++i) {
9739 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9744 // If extracting from the first vector, just use the index directly.
9745 SDValue Extract = N->getOperand(i);
9746 SDValue ExtVal = Extract.getOperand(1);
9747 if (Extract.getOperand(0) == VecIn1) {
9748 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9749 if (ExtIndex > VT.getVectorNumElements())
9752 Mask.push_back(ExtIndex);
9756 // Otherwise, use InIdx + VecSize
9757 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9758 Mask.push_back(Idx+NumInScalars);
9761 // We can't generate a shuffle node with mismatched input and output types.
9762 // Attempt to transform a single input vector to the correct type.
9763 if ((VT != VecIn1.getValueType())) {
9764 // We don't support shuffeling between TWO values of different types.
9765 if (VecIn2.getNode() != 0)
9768 // We only support widening of vectors which are half the size of the
9769 // output registers. For example XMM->YMM widening on X86 with AVX.
9770 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9773 // If the input vector type has a different base type to the output
9774 // vector type, bail out.
9775 if (VecIn1.getValueType().getVectorElementType() !=
9776 VT.getVectorElementType())
9779 // Widen the input vector by adding undef values.
9780 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9781 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9784 // If VecIn2 is unused then change it to undef.
9785 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9787 // Check that we were able to transform all incoming values to the same
9789 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9790 VecIn1.getValueType() != VT)
9793 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9794 if (!isTypeLegal(VT))
9797 // Return the new VECTOR_SHUFFLE node.
9801 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9807 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9808 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9809 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9810 // inputs come from at most two distinct vectors, turn this into a shuffle
9813 // If we only have one input vector, we don't need to do any concatenation.
9814 if (N->getNumOperands() == 1)
9815 return N->getOperand(0);
9817 // Check if all of the operands are undefs.
9818 EVT VT = N->getValueType(0);
9819 if (ISD::allOperandsUndef(N))
9820 return DAG.getUNDEF(VT);
9822 // Optimize concat_vectors where one of the vectors is undef.
9823 if (N->getNumOperands() == 2 &&
9824 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9825 SDValue In = N->getOperand(0);
9826 assert(In->getValueType(0).isVector() && "Must concat vectors");
9828 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9829 if (In->getOpcode() == ISD::BITCAST &&
9830 !In->getOperand(0)->getValueType(0).isVector()) {
9831 SDValue Scalar = In->getOperand(0);
9832 EVT SclTy = Scalar->getValueType(0);
9834 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
9837 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
9838 VT.getSizeInBits() / SclTy.getSizeInBits());
9839 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
9842 SDLoc dl = SDLoc(N);
9843 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
9844 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
9848 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9849 // nodes often generate nop CONCAT_VECTOR nodes.
9850 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9851 // place the incoming vectors at the exact same location.
9852 SDValue SingleSource = SDValue();
9853 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9855 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9856 SDValue Op = N->getOperand(i);
9858 if (Op.getOpcode() == ISD::UNDEF)
9861 // Check if this is the identity extract:
9862 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9865 // Find the single incoming vector for the extract_subvector.
9866 if (SingleSource.getNode()) {
9867 if (Op.getOperand(0) != SingleSource)
9870 SingleSource = Op.getOperand(0);
9872 // Check the source type is the same as the type of the result.
9873 // If not, this concat may extend the vector, so we can not
9874 // optimize it away.
9875 if (SingleSource.getValueType() != N->getValueType(0))
9879 unsigned IdentityIndex = i * PartNumElem;
9880 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9881 // The extract index must be constant.
9885 // Check that we are reading from the identity index.
9886 if (CS->getZExtValue() != IdentityIndex)
9890 if (SingleSource.getNode())
9891 return SingleSource;
9896 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9897 EVT NVT = N->getValueType(0);
9898 SDValue V = N->getOperand(0);
9900 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9902 // (extract_subvec (concat V1, V2, ...), i)
9905 // Only operand 0 is checked as 'concat' assumes all inputs of the same
9907 if (V->getOperand(0).getValueType() != NVT)
9909 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9910 unsigned NumElems = NVT.getVectorNumElements();
9911 assert((Idx % NumElems) == 0 &&
9912 "IDX in concat is not a multiple of the result vector length.");
9913 return V->getOperand(Idx / NumElems);
9917 if (V->getOpcode() == ISD::BITCAST)
9918 V = V.getOperand(0);
9920 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9922 // Handle only simple case where vector being inserted and vector
9923 // being extracted are of same type, and are half size of larger vectors.
9924 EVT BigVT = V->getOperand(0).getValueType();
9925 EVT SmallVT = V->getOperand(1).getValueType();
9926 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9929 // Only handle cases where both indexes are constants with the same type.
9930 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9931 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9933 if (InsIdx && ExtIdx &&
9934 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9935 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9937 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9939 // indices are equal or bit offsets are equal => V1
9940 // otherwise => (extract_subvec V1, ExtIdx)
9941 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9942 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9943 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9944 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9945 DAG.getNode(ISD::BITCAST, dl,
9946 N->getOperand(0).getValueType(),
9947 V->getOperand(0)), N->getOperand(1));
9954 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9955 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9956 EVT VT = N->getValueType(0);
9957 unsigned NumElts = VT.getVectorNumElements();
9959 SDValue N0 = N->getOperand(0);
9960 SDValue N1 = N->getOperand(1);
9961 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9963 SmallVector<SDValue, 4> Ops;
9964 EVT ConcatVT = N0.getOperand(0).getValueType();
9965 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9966 unsigned NumConcats = NumElts / NumElemsPerConcat;
9968 // Look at every vector that's inserted. We're looking for exact
9969 // subvector-sized copies from a concatenated vector
9970 for (unsigned I = 0; I != NumConcats; ++I) {
9971 // Make sure we're dealing with a copy.
9972 unsigned Begin = I * NumElemsPerConcat;
9973 bool AllUndef = true, NoUndef = true;
9974 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9975 if (SVN->getMaskElt(J) >= 0)
9982 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9985 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9986 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9989 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9990 if (FirstElt < N0.getNumOperands())
9991 Ops.push_back(N0.getOperand(FirstElt));
9993 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9995 } else if (AllUndef) {
9996 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9997 } else { // Mixed with general masks and undefs, can't do optimization.
10002 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10006 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10007 EVT VT = N->getValueType(0);
10008 unsigned NumElts = VT.getVectorNumElements();
10010 SDValue N0 = N->getOperand(0);
10011 SDValue N1 = N->getOperand(1);
10013 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10015 // Canonicalize shuffle undef, undef -> undef
10016 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10017 return DAG.getUNDEF(VT);
10019 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10021 // Canonicalize shuffle v, v -> v, undef
10023 SmallVector<int, 8> NewMask;
10024 for (unsigned i = 0; i != NumElts; ++i) {
10025 int Idx = SVN->getMaskElt(i);
10026 if (Idx >= (int)NumElts) Idx -= NumElts;
10027 NewMask.push_back(Idx);
10029 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10033 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10034 if (N0.getOpcode() == ISD::UNDEF) {
10035 SmallVector<int, 8> NewMask;
10036 for (unsigned i = 0; i != NumElts; ++i) {
10037 int Idx = SVN->getMaskElt(i);
10039 if (Idx >= (int)NumElts)
10042 Idx = -1; // remove reference to lhs
10044 NewMask.push_back(Idx);
10046 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10050 // Remove references to rhs if it is undef
10051 if (N1.getOpcode() == ISD::UNDEF) {
10052 bool Changed = false;
10053 SmallVector<int, 8> NewMask;
10054 for (unsigned i = 0; i != NumElts; ++i) {
10055 int Idx = SVN->getMaskElt(i);
10056 if (Idx >= (int)NumElts) {
10060 NewMask.push_back(Idx);
10063 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10066 // If it is a splat, check if the argument vector is another splat or a
10067 // build_vector with all scalar elements the same.
10068 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10069 SDNode *V = N0.getNode();
10071 // If this is a bit convert that changes the element type of the vector but
10072 // not the number of vector elements, look through it. Be careful not to
10073 // look though conversions that change things like v4f32 to v2f64.
10074 if (V->getOpcode() == ISD::BITCAST) {
10075 SDValue ConvInput = V->getOperand(0);
10076 if (ConvInput.getValueType().isVector() &&
10077 ConvInput.getValueType().getVectorNumElements() == NumElts)
10078 V = ConvInput.getNode();
10081 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10082 assert(V->getNumOperands() == NumElts &&
10083 "BUILD_VECTOR has wrong number of operands");
10085 bool AllSame = true;
10086 for (unsigned i = 0; i != NumElts; ++i) {
10087 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10088 Base = V->getOperand(i);
10092 // Splat of <u, u, u, u>, return <u, u, u, u>
10093 if (!Base.getNode())
10095 for (unsigned i = 0; i != NumElts; ++i) {
10096 if (V->getOperand(i) != Base) {
10101 // Splat of <x, x, x, x>, return <x, x, x, x>
10107 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10108 Level < AfterLegalizeVectorOps &&
10109 (N1.getOpcode() == ISD::UNDEF ||
10110 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10111 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10112 SDValue V = partitionShuffleOfConcats(N, DAG);
10118 // If this shuffle node is simply a swizzle of another shuffle node,
10119 // and it reverses the swizzle of the previous shuffle then we can
10120 // optimize shuffle(shuffle(x, undef), undef) -> x.
10121 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10122 N1.getOpcode() == ISD::UNDEF) {
10124 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10126 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10127 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10130 // The incoming shuffle must be of the same type as the result of the
10131 // current shuffle.
10132 assert(OtherSV->getOperand(0).getValueType() == VT &&
10133 "Shuffle types don't match");
10135 for (unsigned i = 0; i != NumElts; ++i) {
10136 int Idx = SVN->getMaskElt(i);
10137 assert(Idx < (int)NumElts && "Index references undef operand");
10138 // Next, this index comes from the first value, which is the incoming
10139 // shuffle. Adopt the incoming index.
10141 Idx = OtherSV->getMaskElt(Idx);
10143 // The combined shuffle must map each index to itself.
10144 if (Idx >= 0 && (unsigned)Idx != i)
10148 return OtherSV->getOperand(0);
10154 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10155 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10156 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10157 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10158 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10159 EVT VT = N->getValueType(0);
10161 SDValue LHS = N->getOperand(0);
10162 SDValue RHS = N->getOperand(1);
10163 if (N->getOpcode() == ISD::AND) {
10164 if (RHS.getOpcode() == ISD::BITCAST)
10165 RHS = RHS.getOperand(0);
10166 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10167 SmallVector<int, 8> Indices;
10168 unsigned NumElts = RHS.getNumOperands();
10169 for (unsigned i = 0; i != NumElts; ++i) {
10170 SDValue Elt = RHS.getOperand(i);
10171 if (!isa<ConstantSDNode>(Elt))
10174 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10175 Indices.push_back(i);
10176 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10177 Indices.push_back(NumElts);
10182 // Let's see if the target supports this vector_shuffle.
10183 EVT RVT = RHS.getValueType();
10184 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10187 // Return the new VECTOR_SHUFFLE node.
10188 EVT EltVT = RVT.getVectorElementType();
10189 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10190 DAG.getConstant(0, EltVT));
10191 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10192 RVT, &ZeroOps[0], ZeroOps.size());
10193 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10194 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10195 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10202 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10203 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10204 assert(N->getValueType(0).isVector() &&
10205 "SimplifyVBinOp only works on vectors!");
10207 SDValue LHS = N->getOperand(0);
10208 SDValue RHS = N->getOperand(1);
10209 SDValue Shuffle = XformToShuffleWithZero(N);
10210 if (Shuffle.getNode()) return Shuffle;
10212 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10214 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10215 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10216 SmallVector<SDValue, 8> Ops;
10217 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10218 SDValue LHSOp = LHS.getOperand(i);
10219 SDValue RHSOp = RHS.getOperand(i);
10220 // If these two elements can't be folded, bail out.
10221 if ((LHSOp.getOpcode() != ISD::UNDEF &&
10222 LHSOp.getOpcode() != ISD::Constant &&
10223 LHSOp.getOpcode() != ISD::ConstantFP) ||
10224 (RHSOp.getOpcode() != ISD::UNDEF &&
10225 RHSOp.getOpcode() != ISD::Constant &&
10226 RHSOp.getOpcode() != ISD::ConstantFP))
10229 // Can't fold divide by zero.
10230 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10231 N->getOpcode() == ISD::FDIV) {
10232 if ((RHSOp.getOpcode() == ISD::Constant &&
10233 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10234 (RHSOp.getOpcode() == ISD::ConstantFP &&
10235 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10239 EVT VT = LHSOp.getValueType();
10240 EVT RVT = RHSOp.getValueType();
10242 // Integer BUILD_VECTOR operands may have types larger than the element
10243 // size (e.g., when the element type is not legal). Prior to type
10244 // legalization, the types may not match between the two BUILD_VECTORS.
10245 // Truncate one of the operands to make them match.
10246 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10247 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10249 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10253 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10255 if (FoldOp.getOpcode() != ISD::UNDEF &&
10256 FoldOp.getOpcode() != ISD::Constant &&
10257 FoldOp.getOpcode() != ISD::ConstantFP)
10259 Ops.push_back(FoldOp);
10260 AddToWorkList(FoldOp.getNode());
10263 if (Ops.size() == LHS.getNumOperands())
10264 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10265 LHS.getValueType(), &Ops[0], Ops.size());
10271 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10272 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10273 assert(N->getValueType(0).isVector() &&
10274 "SimplifyVUnaryOp only works on vectors!");
10276 SDValue N0 = N->getOperand(0);
10278 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10281 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10282 SmallVector<SDValue, 8> Ops;
10283 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10284 SDValue Op = N0.getOperand(i);
10285 if (Op.getOpcode() != ISD::UNDEF &&
10286 Op.getOpcode() != ISD::ConstantFP)
10288 EVT EltVT = Op.getValueType();
10289 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10290 if (FoldOp.getOpcode() != ISD::UNDEF &&
10291 FoldOp.getOpcode() != ISD::ConstantFP)
10293 Ops.push_back(FoldOp);
10294 AddToWorkList(FoldOp.getNode());
10297 if (Ops.size() != N0.getNumOperands())
10300 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10301 N0.getValueType(), &Ops[0], Ops.size());
10304 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10305 SDValue N1, SDValue N2){
10306 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10308 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10309 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10311 // If we got a simplified select_cc node back from SimplifySelectCC, then
10312 // break it down into a new SETCC node, and a new SELECT node, and then return
10313 // the SELECT node, since we were called with a SELECT node.
10314 if (SCC.getNode()) {
10315 // Check to see if we got a select_cc back (to turn into setcc/select).
10316 // Otherwise, just return whatever node we got back, like fabs.
10317 if (SCC.getOpcode() == ISD::SELECT_CC) {
10318 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10320 SCC.getOperand(0), SCC.getOperand(1),
10321 SCC.getOperand(4));
10322 AddToWorkList(SETCC.getNode());
10323 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10324 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10332 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10333 /// are the two values being selected between, see if we can simplify the
10334 /// select. Callers of this should assume that TheSelect is deleted if this
10335 /// returns true. As such, they should return the appropriate thing (e.g. the
10336 /// node) back to the top-level of the DAG combiner loop to avoid it being
10338 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10341 // Cannot simplify select with vector condition
10342 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10344 // If this is a select from two identical things, try to pull the operation
10345 // through the select.
10346 if (LHS.getOpcode() != RHS.getOpcode() ||
10347 !LHS.hasOneUse() || !RHS.hasOneUse())
10350 // If this is a load and the token chain is identical, replace the select
10351 // of two loads with a load through a select of the address to load from.
10352 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10353 // constants have been dropped into the constant pool.
10354 if (LHS.getOpcode() == ISD::LOAD) {
10355 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10356 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10358 // Token chains must be identical.
10359 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10360 // Do not let this transformation reduce the number of volatile loads.
10361 LLD->isVolatile() || RLD->isVolatile() ||
10362 // If this is an EXTLOAD, the VT's must match.
10363 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10364 // If this is an EXTLOAD, the kind of extension must match.
10365 (LLD->getExtensionType() != RLD->getExtensionType() &&
10366 // The only exception is if one of the extensions is anyext.
10367 LLD->getExtensionType() != ISD::EXTLOAD &&
10368 RLD->getExtensionType() != ISD::EXTLOAD) ||
10369 // FIXME: this discards src value information. This is
10370 // over-conservative. It would be beneficial to be able to remember
10371 // both potential memory locations. Since we are discarding
10372 // src value info, don't do the transformation if the memory
10373 // locations are not in the default address space.
10374 LLD->getPointerInfo().getAddrSpace() != 0 ||
10375 RLD->getPointerInfo().getAddrSpace() != 0 ||
10376 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10377 LLD->getBasePtr().getValueType()))
10380 // Check that the select condition doesn't reach either load. If so,
10381 // folding this will induce a cycle into the DAG. If not, this is safe to
10382 // xform, so create a select of the addresses.
10384 if (TheSelect->getOpcode() == ISD::SELECT) {
10385 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10386 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10387 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10389 // The loads must not depend on one another.
10390 if (LLD->isPredecessorOf(RLD) ||
10391 RLD->isPredecessorOf(LLD))
10393 Addr = DAG.getSelect(SDLoc(TheSelect),
10394 LLD->getBasePtr().getValueType(),
10395 TheSelect->getOperand(0), LLD->getBasePtr(),
10396 RLD->getBasePtr());
10397 } else { // Otherwise SELECT_CC
10398 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10399 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10401 if ((LLD->hasAnyUseOfValue(1) &&
10402 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10403 (RLD->hasAnyUseOfValue(1) &&
10404 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10407 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10408 LLD->getBasePtr().getValueType(),
10409 TheSelect->getOperand(0),
10410 TheSelect->getOperand(1),
10411 LLD->getBasePtr(), RLD->getBasePtr(),
10412 TheSelect->getOperand(4));
10416 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10417 Load = DAG.getLoad(TheSelect->getValueType(0),
10419 // FIXME: Discards pointer and TBAA info.
10420 LLD->getChain(), Addr, MachinePointerInfo(),
10421 LLD->isVolatile(), LLD->isNonTemporal(),
10422 LLD->isInvariant(), LLD->getAlignment());
10424 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10425 RLD->getExtensionType() : LLD->getExtensionType(),
10427 TheSelect->getValueType(0),
10428 // FIXME: Discards pointer and TBAA info.
10429 LLD->getChain(), Addr, MachinePointerInfo(),
10430 LLD->getMemoryVT(), LLD->isVolatile(),
10431 LLD->isNonTemporal(), LLD->getAlignment());
10434 // Users of the select now use the result of the load.
10435 CombineTo(TheSelect, Load);
10437 // Users of the old loads now use the new load's chain. We know the
10438 // old-load value is dead now.
10439 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10440 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10447 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10448 /// where 'cond' is the comparison specified by CC.
10449 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10450 SDValue N2, SDValue N3,
10451 ISD::CondCode CC, bool NotExtCompare) {
10452 // (x ? y : y) -> y.
10453 if (N2 == N3) return N2;
10455 EVT VT = N2.getValueType();
10456 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10457 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10458 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10460 // Determine if the condition we're dealing with is constant
10461 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10462 N0, N1, CC, DL, false);
10463 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10464 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10466 // fold select_cc true, x, y -> x
10467 if (SCCC && !SCCC->isNullValue())
10469 // fold select_cc false, x, y -> y
10470 if (SCCC && SCCC->isNullValue())
10473 // Check to see if we can simplify the select into an fabs node
10474 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10475 // Allow either -0.0 or 0.0
10476 if (CFP->getValueAPF().isZero()) {
10477 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10478 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10479 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10480 N2 == N3.getOperand(0))
10481 return DAG.getNode(ISD::FABS, DL, VT, N0);
10483 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10484 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10485 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10486 N2.getOperand(0) == N3)
10487 return DAG.getNode(ISD::FABS, DL, VT, N3);
10491 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10492 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10493 // in it. This is a win when the constant is not otherwise available because
10494 // it replaces two constant pool loads with one. We only do this if the FP
10495 // type is known to be legal, because if it isn't, then we are before legalize
10496 // types an we want the other legalization to happen first (e.g. to avoid
10497 // messing with soft float) and if the ConstantFP is not legal, because if
10498 // it is legal, we may not need to store the FP constant in a constant pool.
10499 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10500 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10501 if (TLI.isTypeLegal(N2.getValueType()) &&
10502 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10503 TargetLowering::Legal) &&
10504 // If both constants have multiple uses, then we won't need to do an
10505 // extra load, they are likely around in registers for other users.
10506 (TV->hasOneUse() || FV->hasOneUse())) {
10507 Constant *Elts[] = {
10508 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10509 const_cast<ConstantFP*>(TV->getConstantFPValue())
10511 Type *FPTy = Elts[0]->getType();
10512 const DataLayout &TD = *TLI.getDataLayout();
10514 // Create a ConstantArray of the two constants.
10515 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10516 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10517 TD.getPrefTypeAlignment(FPTy));
10518 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10520 // Get the offsets to the 0 and 1 element of the array so that we can
10521 // select between them.
10522 SDValue Zero = DAG.getIntPtrConstant(0);
10523 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10524 SDValue One = DAG.getIntPtrConstant(EltSize);
10526 SDValue Cond = DAG.getSetCC(DL,
10527 getSetCCResultType(N0.getValueType()),
10529 AddToWorkList(Cond.getNode());
10530 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10532 AddToWorkList(CstOffset.getNode());
10533 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10535 AddToWorkList(CPIdx.getNode());
10536 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10537 MachinePointerInfo::getConstantPool(), false,
10538 false, false, Alignment);
10543 // Check to see if we can perform the "gzip trick", transforming
10544 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10545 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10546 (N1C->isNullValue() || // (a < 0) ? b : 0
10547 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10548 EVT XType = N0.getValueType();
10549 EVT AType = N2.getValueType();
10550 if (XType.bitsGE(AType)) {
10551 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10552 // single-bit constant.
10553 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10554 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10555 ShCtV = XType.getSizeInBits()-ShCtV-1;
10556 SDValue ShCt = DAG.getConstant(ShCtV,
10557 getShiftAmountTy(N0.getValueType()));
10558 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10560 AddToWorkList(Shift.getNode());
10562 if (XType.bitsGT(AType)) {
10563 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10564 AddToWorkList(Shift.getNode());
10567 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10570 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10572 DAG.getConstant(XType.getSizeInBits()-1,
10573 getShiftAmountTy(N0.getValueType())));
10574 AddToWorkList(Shift.getNode());
10576 if (XType.bitsGT(AType)) {
10577 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10578 AddToWorkList(Shift.getNode());
10581 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10585 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10586 // where y is has a single bit set.
10587 // A plaintext description would be, we can turn the SELECT_CC into an AND
10588 // when the condition can be materialized as an all-ones register. Any
10589 // single bit-test can be materialized as an all-ones register with
10590 // shift-left and shift-right-arith.
10591 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10592 N0->getValueType(0) == VT &&
10593 N1C && N1C->isNullValue() &&
10594 N2C && N2C->isNullValue()) {
10595 SDValue AndLHS = N0->getOperand(0);
10596 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10597 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10598 // Shift the tested bit over the sign bit.
10599 APInt AndMask = ConstAndRHS->getAPIntValue();
10601 DAG.getConstant(AndMask.countLeadingZeros(),
10602 getShiftAmountTy(AndLHS.getValueType()));
10603 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10605 // Now arithmetic right shift it all the way over, so the result is either
10606 // all-ones, or zero.
10608 DAG.getConstant(AndMask.getBitWidth()-1,
10609 getShiftAmountTy(Shl.getValueType()));
10610 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10612 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10616 // fold select C, 16, 0 -> shl C, 4
10617 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10618 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10619 TargetLowering::ZeroOrOneBooleanContent) {
10621 // If the caller doesn't want us to simplify this into a zext of a compare,
10623 if (NotExtCompare && N2C->getAPIntValue() == 1)
10626 // Get a SetCC of the condition
10627 // NOTE: Don't create a SETCC if it's not legal on this target.
10628 if (!LegalOperations ||
10629 TLI.isOperationLegal(ISD::SETCC,
10630 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10632 // cast from setcc result type to select result type
10634 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10636 if (N2.getValueType().bitsLT(SCC.getValueType()))
10637 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10638 N2.getValueType());
10640 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10641 N2.getValueType(), SCC);
10643 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10644 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10645 N2.getValueType(), SCC);
10648 AddToWorkList(SCC.getNode());
10649 AddToWorkList(Temp.getNode());
10651 if (N2C->getAPIntValue() == 1)
10654 // shl setcc result by log2 n2c
10655 return DAG.getNode(
10656 ISD::SHL, DL, N2.getValueType(), Temp,
10657 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10658 getShiftAmountTy(Temp.getValueType())));
10662 // Check to see if this is the equivalent of setcc
10663 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10664 // otherwise, go ahead with the folds.
10665 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10666 EVT XType = N0.getValueType();
10667 if (!LegalOperations ||
10668 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10669 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10670 if (Res.getValueType() != VT)
10671 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10675 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10676 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10677 (!LegalOperations ||
10678 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10679 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10680 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10681 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10682 getShiftAmountTy(Ctlz.getValueType())));
10684 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10685 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10686 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10687 XType, DAG.getConstant(0, XType), N0);
10688 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10689 return DAG.getNode(ISD::SRL, DL, XType,
10690 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10691 DAG.getConstant(XType.getSizeInBits()-1,
10692 getShiftAmountTy(XType)));
10694 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10695 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10696 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10697 DAG.getConstant(XType.getSizeInBits()-1,
10698 getShiftAmountTy(N0.getValueType())));
10699 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10703 // Check to see if this is an integer abs.
10704 // select_cc setg[te] X, 0, X, -X ->
10705 // select_cc setgt X, -1, X, -X ->
10706 // select_cc setl[te] X, 0, -X, X ->
10707 // select_cc setlt X, 1, -X, X ->
10708 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10710 ConstantSDNode *SubC = NULL;
10711 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10712 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10713 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10714 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10715 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10716 (N1C->isOne() && CC == ISD::SETLT)) &&
10717 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10718 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10720 EVT XType = N0.getValueType();
10721 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10722 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10724 DAG.getConstant(XType.getSizeInBits()-1,
10725 getShiftAmountTy(N0.getValueType())));
10726 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10728 AddToWorkList(Shift.getNode());
10729 AddToWorkList(Add.getNode());
10730 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10737 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10738 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10739 SDValue N1, ISD::CondCode Cond,
10740 SDLoc DL, bool foldBooleans) {
10741 TargetLowering::DAGCombinerInfo
10742 DagCombineInfo(DAG, Level, false, this);
10743 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10746 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10747 /// return a DAG expression to select that will generate the same value by
10748 /// multiplying by a magic number. See:
10749 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10750 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10751 std::vector<SDNode*> Built;
10752 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10754 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10756 AddToWorkList(*ii);
10760 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10761 /// return a DAG expression to select that will generate the same value by
10762 /// multiplying by a magic number. See:
10763 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10764 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10765 std::vector<SDNode*> Built;
10766 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10768 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10770 AddToWorkList(*ii);
10774 /// FindBaseOffset - Return true if base is a frame index, which is known not
10775 // to alias with anything but itself. Provides base object and offset as
10777 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10778 const GlobalValue *&GV, const void *&CV) {
10779 // Assume it is a primitive operation.
10780 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10782 // If it's an adding a simple constant then integrate the offset.
10783 if (Base.getOpcode() == ISD::ADD) {
10784 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10785 Base = Base.getOperand(0);
10786 Offset += C->getZExtValue();
10790 // Return the underlying GlobalValue, and update the Offset. Return false
10791 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10792 // by multiple nodes with different offsets.
10793 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10794 GV = G->getGlobal();
10795 Offset += G->getOffset();
10799 // Return the underlying Constant value, and update the Offset. Return false
10800 // for ConstantSDNodes since the same constant pool entry may be represented
10801 // by multiple nodes with different offsets.
10802 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10803 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10804 : (const void *)C->getConstVal();
10805 Offset += C->getOffset();
10808 // If it's any of the following then it can't alias with anything but itself.
10809 return isa<FrameIndexSDNode>(Base);
10812 /// isAlias - Return true if there is any possibility that the two addresses
10814 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10815 const Value *SrcValue1, int SrcValueOffset1,
10816 unsigned SrcValueAlign1,
10817 const MDNode *TBAAInfo1,
10818 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10819 const Value *SrcValue2, int SrcValueOffset2,
10820 unsigned SrcValueAlign2,
10821 const MDNode *TBAAInfo2) const {
10822 // If they are the same then they must be aliases.
10823 if (Ptr1 == Ptr2) return true;
10825 // If they are both volatile then they cannot be reordered.
10826 if (IsVolatile1 && IsVolatile2) return true;
10828 // Gather base node and offset information.
10829 SDValue Base1, Base2;
10830 int64_t Offset1, Offset2;
10831 const GlobalValue *GV1, *GV2;
10832 const void *CV1, *CV2;
10833 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10834 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10836 // If they have a same base address then check to see if they overlap.
10837 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10838 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10840 // It is possible for different frame indices to alias each other, mostly
10841 // when tail call optimization reuses return address slots for arguments.
10842 // To catch this case, look up the actual index of frame indices to compute
10843 // the real alias relationship.
10844 if (isFrameIndex1 && isFrameIndex2) {
10845 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10846 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10847 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10848 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10851 // Otherwise, if we know what the bases are, and they aren't identical, then
10852 // we know they cannot alias.
10853 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10856 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10857 // compared to the size and offset of the access, we may be able to prove they
10858 // do not alias. This check is conservative for now to catch cases created by
10859 // splitting vector types.
10860 if ((SrcValueAlign1 == SrcValueAlign2) &&
10861 (SrcValueOffset1 != SrcValueOffset2) &&
10862 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10863 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10864 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10866 // There is no overlap between these relatively aligned accesses of similar
10867 // size, return no alias.
10868 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10872 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10873 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10874 if (UseAA && SrcValue1 && SrcValue2) {
10875 // Use alias analysis information.
10876 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10877 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10878 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10879 AliasAnalysis::AliasResult AAResult =
10880 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10881 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10882 if (AAResult == AliasAnalysis::NoAlias)
10886 // Otherwise we have to assume they alias.
10890 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10891 SDValue Ptr0, Ptr1;
10892 int64_t Size0, Size1;
10893 bool IsVolatile0, IsVolatile1;
10894 const Value *SrcValue0, *SrcValue1;
10895 int SrcValueOffset0, SrcValueOffset1;
10896 unsigned SrcValueAlign0, SrcValueAlign1;
10897 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10898 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10899 SrcValueAlign0, SrcTBAAInfo0);
10900 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10901 SrcValueAlign1, SrcTBAAInfo1);
10902 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10903 SrcValueAlign0, SrcTBAAInfo0,
10904 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10905 SrcValueAlign1, SrcTBAAInfo1);
10908 /// FindAliasInfo - Extracts the relevant alias information from the memory
10909 /// node. Returns true if the operand was a nonvolatile load.
10910 bool DAGCombiner::FindAliasInfo(SDNode *N,
10911 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
10912 const Value *&SrcValue,
10913 int &SrcValueOffset,
10914 unsigned &SrcValueAlign,
10915 const MDNode *&TBAAInfo) const {
10916 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10918 Ptr = LS->getBasePtr();
10919 Size = LS->getMemoryVT().getSizeInBits() >> 3;
10920 IsVolatile = LS->isVolatile();
10921 SrcValue = LS->getSrcValue();
10922 SrcValueOffset = LS->getSrcValueOffset();
10923 SrcValueAlign = LS->getOriginalAlignment();
10924 TBAAInfo = LS->getTBAAInfo();
10925 return isa<LoadSDNode>(LS) && !IsVolatile;
10928 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10929 /// looking for aliasing nodes and adding them to the Aliases vector.
10930 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10931 SmallVectorImpl<SDValue> &Aliases) {
10932 SmallVector<SDValue, 8> Chains; // List of chains to visit.
10933 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
10935 // Get alias information for node.
10939 const Value *SrcValue;
10940 int SrcValueOffset;
10941 unsigned SrcValueAlign;
10942 const MDNode *SrcTBAAInfo;
10943 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
10944 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
10947 Chains.push_back(OriginalChain);
10948 unsigned Depth = 0;
10950 // Look at each chain and determine if it is an alias. If so, add it to the
10951 // aliases list. If not, then continue up the chain looking for the next
10953 while (!Chains.empty()) {
10954 SDValue Chain = Chains.back();
10957 // For TokenFactor nodes, look at each operand and only continue up the
10958 // chain until we find two aliases. If we've seen two aliases, assume we'll
10959 // find more and revert to original chain since the xform is unlikely to be
10962 // FIXME: The depth check could be made to return the last non-aliasing
10963 // chain we found before we hit a tokenfactor rather than the original
10965 if (Depth > 6 || Aliases.size() == 2) {
10967 Aliases.push_back(OriginalChain);
10971 // Don't bother if we've been before.
10972 if (!Visited.insert(Chain.getNode()))
10975 switch (Chain.getOpcode()) {
10976 case ISD::EntryToken:
10977 // Entry token is ideal chain operand, but handled in FindBetterChain.
10982 // Get alias information for Chain.
10986 const Value *OpSrcValue;
10987 int OpSrcValueOffset;
10988 unsigned OpSrcValueAlign;
10989 const MDNode *OpSrcTBAAInfo;
10990 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10991 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
10995 // If chain is alias then stop here.
10996 if (!(IsLoad && IsOpLoad) &&
10997 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
10998 SrcValueAlign, SrcTBAAInfo,
10999 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11000 OpSrcValueAlign, OpSrcTBAAInfo)) {
11001 Aliases.push_back(Chain);
11003 // Look further up the chain.
11004 Chains.push_back(Chain.getOperand(0));
11010 case ISD::TokenFactor:
11011 // We have to check each of the operands of the token factor for "small"
11012 // token factors, so we queue them up. Adding the operands to the queue
11013 // (stack) in reverse order maintains the original order and increases the
11014 // likelihood that getNode will find a matching token factor (CSE.)
11015 if (Chain.getNumOperands() > 16) {
11016 Aliases.push_back(Chain);
11019 for (unsigned n = Chain.getNumOperands(); n;)
11020 Chains.push_back(Chain.getOperand(--n));
11025 // For all other instructions we will just have to take what we can get.
11026 Aliases.push_back(Chain);
11032 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11033 /// for a better chain (aliasing node.)
11034 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11035 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11037 // Accumulate all the aliases to this node.
11038 GatherAllAliases(N, OldChain, Aliases);
11040 // If no operands then chain to entry token.
11041 if (Aliases.size() == 0)
11042 return DAG.getEntryNode();
11044 // If a single operand then chain to it. We don't need to revisit it.
11045 if (Aliases.size() == 1)
11048 // Construct a custom tailored token factor.
11049 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11050 &Aliases[0], Aliases.size());
11053 // SelectionDAG::Combine - This is the entry point for the file.
11055 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11056 CodeGenOpt::Level OptLevel) {
11057 /// run - This is the main entry point to this class.
11059 DAGCombiner(*this, AA, OptLevel).Run(Level);