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"
41 STATISTIC(NodesCombined , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
45 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
60 const TargetLowering &TLI;
62 CodeGenOpt::Level OptLevel;
66 // Worklist of all of the nodes that need to be simplified.
68 // This has the semantics that when adding to the worklist,
69 // the item added must be next to be processed. It should
70 // also only appear once. The naive approach to this takes
73 // To reduce the insert/remove time to logarithmic, we use
74 // a set and a vector to maintain our worklist.
76 // The set contains the items on the worklist, but does not
77 // maintain the order they should be visited.
79 // The vector maintains the order nodes should be visited, but may
80 // contain duplicate or removed nodes. When choosing a node to
81 // visit, we pop off the order stack until we find an item that is
82 // also in the contents set. All operations are O(log N).
83 SmallPtrSet<SDNode*, 64> WorkListContents;
84 SmallVector<SDNode*, 64> WorkListOrder;
86 // AA - Used for DAG load/store alias analysis.
89 /// AddUsersToWorkList - When an instruction is simplified, add all users of
90 /// the instruction to the work lists because they might get more simplified
93 void AddUsersToWorkList(SDNode *N) {
94 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
99 /// visit - call the node-specific routine that knows how to fold each
100 /// particular type of node.
101 SDValue visit(SDNode *N);
104 /// AddToWorkList - Add to the work list making sure its instance is at the
105 /// back (next to be processed.)
106 void AddToWorkList(SDNode *N) {
107 WorkListContents.insert(N);
108 WorkListOrder.push_back(N);
111 /// removeFromWorkList - remove all instances of N from the worklist.
113 void removeFromWorkList(SDNode *N) {
114 WorkListContents.erase(N);
117 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
120 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
121 return CombineTo(N, &Res, 1, AddTo);
124 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
126 SDValue To[] = { Res0, Res1 };
127 return CombineTo(N, To, 2, AddTo);
130 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
134 /// SimplifyDemandedBits - Check the specified integer node value to see if
135 /// it can be simplified or if things it uses can be simplified by bit
136 /// propagation. If so, return true.
137 bool SimplifyDemandedBits(SDValue Op) {
138 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
139 APInt Demanded = APInt::getAllOnesValue(BitWidth);
140 return SimplifyDemandedBits(Op, Demanded);
143 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
145 bool CombineToPreIndexedLoadStore(SDNode *N);
146 bool CombineToPostIndexedLoadStore(SDNode *N);
148 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
149 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
150 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
151 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
152 SDValue PromoteIntBinOp(SDValue Op);
153 SDValue PromoteIntShiftOp(SDValue Op);
154 SDValue PromoteExtend(SDValue Op);
155 bool PromoteLoad(SDValue Op);
157 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
158 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
159 ISD::NodeType ExtType);
161 /// combine - call the node-specific routine that knows how to fold each
162 /// particular type of node. If that doesn't do anything, try the
163 /// target-specific DAG combines.
164 SDValue combine(SDNode *N);
166 // Visitation implementation - Implement dag node combining for different
167 // node types. The semantics are as follows:
169 // SDValue.getNode() == 0 - No change was made
170 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
171 // otherwise - N should be replaced by the returned Operand.
173 SDValue visitTokenFactor(SDNode *N);
174 SDValue visitMERGE_VALUES(SDNode *N);
175 SDValue visitADD(SDNode *N);
176 SDValue visitSUB(SDNode *N);
177 SDValue visitADDC(SDNode *N);
178 SDValue visitSUBC(SDNode *N);
179 SDValue visitADDE(SDNode *N);
180 SDValue visitSUBE(SDNode *N);
181 SDValue visitMUL(SDNode *N);
182 SDValue visitSDIV(SDNode *N);
183 SDValue visitUDIV(SDNode *N);
184 SDValue visitSREM(SDNode *N);
185 SDValue visitUREM(SDNode *N);
186 SDValue visitMULHU(SDNode *N);
187 SDValue visitMULHS(SDNode *N);
188 SDValue visitSMUL_LOHI(SDNode *N);
189 SDValue visitUMUL_LOHI(SDNode *N);
190 SDValue visitSMULO(SDNode *N);
191 SDValue visitUMULO(SDNode *N);
192 SDValue visitSDIVREM(SDNode *N);
193 SDValue visitUDIVREM(SDNode *N);
194 SDValue visitAND(SDNode *N);
195 SDValue visitOR(SDNode *N);
196 SDValue visitXOR(SDNode *N);
197 SDValue SimplifyVBinOp(SDNode *N);
198 SDValue SimplifyVUnaryOp(SDNode *N);
199 SDValue visitSHL(SDNode *N);
200 SDValue visitSRA(SDNode *N);
201 SDValue visitSRL(SDNode *N);
202 SDValue visitCTLZ(SDNode *N);
203 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
204 SDValue visitCTTZ(SDNode *N);
205 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
206 SDValue visitCTPOP(SDNode *N);
207 SDValue visitSELECT(SDNode *N);
208 SDValue visitSELECT_CC(SDNode *N);
209 SDValue visitSETCC(SDNode *N);
210 SDValue visitSIGN_EXTEND(SDNode *N);
211 SDValue visitZERO_EXTEND(SDNode *N);
212 SDValue visitANY_EXTEND(SDNode *N);
213 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
214 SDValue visitTRUNCATE(SDNode *N);
215 SDValue visitBITCAST(SDNode *N);
216 SDValue visitBUILD_PAIR(SDNode *N);
217 SDValue visitFADD(SDNode *N);
218 SDValue visitFSUB(SDNode *N);
219 SDValue visitFMUL(SDNode *N);
220 SDValue visitFMA(SDNode *N);
221 SDValue visitFDIV(SDNode *N);
222 SDValue visitFREM(SDNode *N);
223 SDValue visitFCOPYSIGN(SDNode *N);
224 SDValue visitSINT_TO_FP(SDNode *N);
225 SDValue visitUINT_TO_FP(SDNode *N);
226 SDValue visitFP_TO_SINT(SDNode *N);
227 SDValue visitFP_TO_UINT(SDNode *N);
228 SDValue visitFP_ROUND(SDNode *N);
229 SDValue visitFP_ROUND_INREG(SDNode *N);
230 SDValue visitFP_EXTEND(SDNode *N);
231 SDValue visitFNEG(SDNode *N);
232 SDValue visitFABS(SDNode *N);
233 SDValue visitFCEIL(SDNode *N);
234 SDValue visitFTRUNC(SDNode *N);
235 SDValue visitFFLOOR(SDNode *N);
236 SDValue visitBRCOND(SDNode *N);
237 SDValue visitBR_CC(SDNode *N);
238 SDValue visitLOAD(SDNode *N);
239 SDValue visitSTORE(SDNode *N);
240 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
241 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
242 SDValue visitBUILD_VECTOR(SDNode *N);
243 SDValue visitCONCAT_VECTORS(SDNode *N);
244 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
245 SDValue visitVECTOR_SHUFFLE(SDNode *N);
247 SDValue XformToShuffleWithZero(SDNode *N);
248 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
250 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
252 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
253 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
254 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
255 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
256 SDValue N3, ISD::CondCode CC,
257 bool NotExtCompare = false);
258 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
259 DebugLoc DL, bool foldBooleans = true);
260 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
262 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
263 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
264 SDValue BuildSDIV(SDNode *N);
265 SDValue BuildUDIV(SDNode *N);
266 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
267 bool DemandHighBits = true);
268 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
269 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
270 SDValue ReduceLoadWidth(SDNode *N);
271 SDValue ReduceLoadOpStoreWidth(SDNode *N);
272 SDValue TransformFPLoadStorePair(SDNode *N);
273 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
274 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
276 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
278 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
279 /// looking for aliasing nodes and adding them to the Aliases vector.
280 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
281 SmallVector<SDValue, 8> &Aliases);
283 /// isAlias - Return true if there is any possibility that the two addresses
285 bool isAlias(SDValue Ptr1, int64_t Size1,
286 const Value *SrcValue1, int SrcValueOffset1,
287 unsigned SrcValueAlign1,
288 const MDNode *TBAAInfo1,
289 SDValue Ptr2, int64_t Size2,
290 const Value *SrcValue2, int SrcValueOffset2,
291 unsigned SrcValueAlign2,
292 const MDNode *TBAAInfo2) const;
294 /// isAlias - Return true if there is any possibility that the two addresses
296 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
298 /// FindAliasInfo - Extracts the relevant alias information from the memory
299 /// node. Returns true if the operand was a load.
300 bool FindAliasInfo(SDNode *N,
301 SDValue &Ptr, int64_t &Size,
302 const Value *&SrcValue, int &SrcValueOffset,
303 unsigned &SrcValueAlignment,
304 const MDNode *&TBAAInfo) const;
306 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
307 /// looking for a better chain (aliasing node.)
308 SDValue FindBetterChain(SDNode *N, SDValue Chain);
310 /// Merge consecutive store operations into a wide store.
311 /// This optimization uses wide integers or vectors when possible.
312 /// \return True if some memory operations were changed.
313 bool MergeConsecutiveStores(StoreSDNode *N);
316 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
317 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
318 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
320 /// Run - runs the dag combiner on all nodes in the work list
321 void Run(CombineLevel AtLevel);
323 SelectionDAG &getDAG() const { return DAG; }
325 /// getShiftAmountTy - Returns a type large enough to hold any valid
326 /// shift amount - before type legalization these can be huge.
327 EVT getShiftAmountTy(EVT LHSTy) {
328 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
331 /// isTypeLegal - This method returns true if we are running before type
332 /// legalization or if the specified VT is legal.
333 bool isTypeLegal(const EVT &VT) {
334 if (!LegalTypes) return true;
335 return TLI.isTypeLegal(VT);
342 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
343 /// nodes from the worklist.
344 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
347 explicit WorkListRemover(DAGCombiner &dc)
348 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
350 virtual void NodeDeleted(SDNode *N, SDNode *E) {
351 DC.removeFromWorkList(N);
356 //===----------------------------------------------------------------------===//
357 // TargetLowering::DAGCombinerInfo implementation
358 //===----------------------------------------------------------------------===//
360 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
361 ((DAGCombiner*)DC)->AddToWorkList(N);
364 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
365 ((DAGCombiner*)DC)->removeFromWorkList(N);
368 SDValue TargetLowering::DAGCombinerInfo::
369 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
370 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
373 SDValue TargetLowering::DAGCombinerInfo::
374 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
375 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
379 SDValue TargetLowering::DAGCombinerInfo::
380 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
381 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
384 void TargetLowering::DAGCombinerInfo::
385 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
386 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
389 //===----------------------------------------------------------------------===//
391 //===----------------------------------------------------------------------===//
393 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
394 /// specified expression for the same cost as the expression itself, or 2 if we
395 /// can compute the negated form more cheaply than the expression itself.
396 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
397 const TargetLowering &TLI,
398 const TargetOptions *Options,
399 unsigned Depth = 0) {
400 // fneg is removable even if it has multiple uses.
401 if (Op.getOpcode() == ISD::FNEG) return 2;
403 // Don't allow anything with multiple uses.
404 if (!Op.hasOneUse()) return 0;
406 // Don't recurse exponentially.
407 if (Depth > 6) return 0;
409 switch (Op.getOpcode()) {
410 default: return false;
411 case ISD::ConstantFP:
412 // Don't invert constant FP values after legalize. The negated constant
413 // isn't necessarily legal.
414 return LegalOperations ? 0 : 1;
416 // FIXME: determine better conditions for this xform.
417 if (!Options->UnsafeFPMath) return 0;
419 // After operation legalization, it might not be legal to create new FSUBs.
420 if (LegalOperations &&
421 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
424 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
425 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
428 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
429 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
432 // We can't turn -(A-B) into B-A when we honor signed zeros.
433 if (!Options->UnsafeFPMath) return 0;
435 // fold (fneg (fsub A, B)) -> (fsub B, A)
440 if (Options->HonorSignDependentRoundingFPMath()) return 0;
442 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
443 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
447 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
453 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
458 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
459 /// returns the newly negated expression.
460 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
461 bool LegalOperations, unsigned Depth = 0) {
462 // fneg is removable even if it has multiple uses.
463 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
465 // Don't allow anything with multiple uses.
466 assert(Op.hasOneUse() && "Unknown reuse!");
468 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
469 switch (Op.getOpcode()) {
470 default: llvm_unreachable("Unknown code");
471 case ISD::ConstantFP: {
472 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
474 return DAG.getConstantFP(V, Op.getValueType());
477 // FIXME: determine better conditions for this xform.
478 assert(DAG.getTarget().Options.UnsafeFPMath);
480 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
481 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
482 DAG.getTargetLoweringInfo(),
483 &DAG.getTarget().Options, Depth+1))
484 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
485 GetNegatedExpression(Op.getOperand(0), DAG,
486 LegalOperations, Depth+1),
488 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
489 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
490 GetNegatedExpression(Op.getOperand(1), DAG,
491 LegalOperations, Depth+1),
494 // We can't turn -(A-B) into B-A when we honor signed zeros.
495 assert(DAG.getTarget().Options.UnsafeFPMath);
497 // fold (fneg (fsub 0, B)) -> B
498 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
499 if (N0CFP->getValueAPF().isZero())
500 return Op.getOperand(1);
502 // fold (fneg (fsub A, B)) -> (fsub B, A)
503 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
504 Op.getOperand(1), Op.getOperand(0));
508 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
510 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
511 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
512 DAG.getTargetLoweringInfo(),
513 &DAG.getTarget().Options, Depth+1))
514 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
515 GetNegatedExpression(Op.getOperand(0), DAG,
516 LegalOperations, Depth+1),
519 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
520 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
522 GetNegatedExpression(Op.getOperand(1), DAG,
523 LegalOperations, Depth+1));
527 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
528 GetNegatedExpression(Op.getOperand(0), DAG,
529 LegalOperations, Depth+1));
531 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
532 GetNegatedExpression(Op.getOperand(0), DAG,
533 LegalOperations, Depth+1),
539 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
540 // that selects between the values 1 and 0, making it equivalent to a setcc.
541 // Also, set the incoming LHS, RHS, and CC references to the appropriate
542 // nodes based on the type of node we are checking. This simplifies life a
543 // bit for the callers.
544 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
546 if (N.getOpcode() == ISD::SETCC) {
547 LHS = N.getOperand(0);
548 RHS = N.getOperand(1);
549 CC = N.getOperand(2);
552 if (N.getOpcode() == ISD::SELECT_CC &&
553 N.getOperand(2).getOpcode() == ISD::Constant &&
554 N.getOperand(3).getOpcode() == ISD::Constant &&
555 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
556 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
557 LHS = N.getOperand(0);
558 RHS = N.getOperand(1);
559 CC = N.getOperand(4);
565 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
566 // one use. If this is true, it allows the users to invert the operation for
567 // free when it is profitable to do so.
568 static bool isOneUseSetCC(SDValue N) {
570 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
575 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
576 SDValue N0, SDValue N1) {
577 EVT VT = N0.getValueType();
578 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
579 if (isa<ConstantSDNode>(N1)) {
580 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
582 DAG.FoldConstantArithmetic(Opc, VT,
583 cast<ConstantSDNode>(N0.getOperand(1)),
584 cast<ConstantSDNode>(N1));
585 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
587 if (N0.hasOneUse()) {
588 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
589 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
590 N0.getOperand(0), N1);
591 AddToWorkList(OpNode.getNode());
592 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
596 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
597 if (isa<ConstantSDNode>(N0)) {
598 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
600 DAG.FoldConstantArithmetic(Opc, VT,
601 cast<ConstantSDNode>(N1.getOperand(1)),
602 cast<ConstantSDNode>(N0));
603 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
605 if (N1.hasOneUse()) {
606 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
607 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
608 N1.getOperand(0), N0);
609 AddToWorkList(OpNode.getNode());
610 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
617 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
619 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
621 DEBUG(dbgs() << "\nReplacing.1 ";
623 dbgs() << "\nWith: ";
624 To[0].getNode()->dump(&DAG);
625 dbgs() << " and " << NumTo-1 << " other values\n";
626 for (unsigned i = 0, e = NumTo; i != e; ++i)
627 assert((!To[i].getNode() ||
628 N->getValueType(i) == To[i].getValueType()) &&
629 "Cannot combine value to value of different type!"));
630 WorkListRemover DeadNodes(*this);
631 DAG.ReplaceAllUsesWith(N, To);
633 // Push the new nodes and any users onto the worklist
634 for (unsigned i = 0, e = NumTo; i != e; ++i) {
635 if (To[i].getNode()) {
636 AddToWorkList(To[i].getNode());
637 AddUsersToWorkList(To[i].getNode());
642 // Finally, if the node is now dead, remove it from the graph. The node
643 // may not be dead if the replacement process recursively simplified to
644 // something else needing this node.
645 if (N->use_empty()) {
646 // Nodes can be reintroduced into the worklist. Make sure we do not
647 // process a node that has been replaced.
648 removeFromWorkList(N);
650 // Finally, since the node is now dead, remove it from the graph.
653 return SDValue(N, 0);
657 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
658 // Replace all uses. If any nodes become isomorphic to other nodes and
659 // are deleted, make sure to remove them from our worklist.
660 WorkListRemover DeadNodes(*this);
661 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
663 // Push the new node and any (possibly new) users onto the worklist.
664 AddToWorkList(TLO.New.getNode());
665 AddUsersToWorkList(TLO.New.getNode());
667 // Finally, if the node is now dead, remove it from the graph. The node
668 // may not be dead if the replacement process recursively simplified to
669 // something else needing this node.
670 if (TLO.Old.getNode()->use_empty()) {
671 removeFromWorkList(TLO.Old.getNode());
673 // If the operands of this node are only used by the node, they will now
674 // be dead. Make sure to visit them first to delete dead nodes early.
675 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
676 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
677 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
679 DAG.DeleteNode(TLO.Old.getNode());
683 /// SimplifyDemandedBits - Check the specified integer node value to see if
684 /// it can be simplified or if things it uses can be simplified by bit
685 /// propagation. If so, return true.
686 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
687 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
688 APInt KnownZero, KnownOne;
689 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
693 AddToWorkList(Op.getNode());
695 // Replace the old value with the new one.
697 DEBUG(dbgs() << "\nReplacing.2 ";
698 TLO.Old.getNode()->dump(&DAG);
699 dbgs() << "\nWith: ";
700 TLO.New.getNode()->dump(&DAG);
703 CommitTargetLoweringOpt(TLO);
707 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
708 DebugLoc dl = Load->getDebugLoc();
709 EVT VT = Load->getValueType(0);
710 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
712 DEBUG(dbgs() << "\nReplacing.9 ";
714 dbgs() << "\nWith: ";
715 Trunc.getNode()->dump(&DAG);
717 WorkListRemover DeadNodes(*this);
718 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
719 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
720 removeFromWorkList(Load);
721 DAG.DeleteNode(Load);
722 AddToWorkList(Trunc.getNode());
725 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
727 DebugLoc dl = Op.getDebugLoc();
728 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
729 EVT MemVT = LD->getMemoryVT();
730 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
731 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
733 : LD->getExtensionType();
735 return DAG.getExtLoad(ExtType, dl, PVT,
736 LD->getChain(), LD->getBasePtr(),
737 LD->getPointerInfo(),
738 MemVT, LD->isVolatile(),
739 LD->isNonTemporal(), LD->getAlignment());
742 unsigned Opc = Op.getOpcode();
745 case ISD::AssertSext:
746 return DAG.getNode(ISD::AssertSext, dl, PVT,
747 SExtPromoteOperand(Op.getOperand(0), PVT),
749 case ISD::AssertZext:
750 return DAG.getNode(ISD::AssertZext, dl, PVT,
751 ZExtPromoteOperand(Op.getOperand(0), PVT),
753 case ISD::Constant: {
755 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
756 return DAG.getNode(ExtOpc, dl, PVT, Op);
760 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
762 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
765 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
766 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
768 EVT OldVT = Op.getValueType();
769 DebugLoc dl = Op.getDebugLoc();
770 bool Replace = false;
771 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
772 if (NewOp.getNode() == 0)
774 AddToWorkList(NewOp.getNode());
777 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
778 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
779 DAG.getValueType(OldVT));
782 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
783 EVT OldVT = Op.getValueType();
784 DebugLoc dl = Op.getDebugLoc();
785 bool Replace = false;
786 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
787 if (NewOp.getNode() == 0)
789 AddToWorkList(NewOp.getNode());
792 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
793 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
796 /// PromoteIntBinOp - Promote the specified integer binary operation if the
797 /// target indicates it is beneficial. e.g. On x86, it's usually better to
798 /// promote i16 operations to i32 since i16 instructions are longer.
799 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
800 if (!LegalOperations)
803 EVT VT = Op.getValueType();
804 if (VT.isVector() || !VT.isInteger())
807 // If operation type is 'undesirable', e.g. i16 on x86, consider
809 unsigned Opc = Op.getOpcode();
810 if (TLI.isTypeDesirableForOp(Opc, VT))
814 // Consult target whether it is a good idea to promote this operation and
815 // what's the right type to promote it to.
816 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
817 assert(PVT != VT && "Don't know what type to promote to!");
819 bool Replace0 = false;
820 SDValue N0 = Op.getOperand(0);
821 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
822 if (NN0.getNode() == 0)
825 bool Replace1 = false;
826 SDValue N1 = Op.getOperand(1);
831 NN1 = PromoteOperand(N1, PVT, Replace1);
832 if (NN1.getNode() == 0)
836 AddToWorkList(NN0.getNode());
838 AddToWorkList(NN1.getNode());
841 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
843 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
845 DEBUG(dbgs() << "\nPromoting ";
846 Op.getNode()->dump(&DAG));
847 DebugLoc dl = Op.getDebugLoc();
848 return DAG.getNode(ISD::TRUNCATE, dl, VT,
849 DAG.getNode(Opc, dl, PVT, NN0, NN1));
854 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
855 /// target indicates it is beneficial. e.g. On x86, it's usually better to
856 /// promote i16 operations to i32 since i16 instructions are longer.
857 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
858 if (!LegalOperations)
861 EVT VT = Op.getValueType();
862 if (VT.isVector() || !VT.isInteger())
865 // If operation type is 'undesirable', e.g. i16 on x86, consider
867 unsigned Opc = Op.getOpcode();
868 if (TLI.isTypeDesirableForOp(Opc, VT))
872 // Consult target whether it is a good idea to promote this operation and
873 // what's the right type to promote it to.
874 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
875 assert(PVT != VT && "Don't know what type to promote to!");
877 bool Replace = false;
878 SDValue N0 = Op.getOperand(0);
880 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
881 else if (Opc == ISD::SRL)
882 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
884 N0 = PromoteOperand(N0, PVT, Replace);
885 if (N0.getNode() == 0)
888 AddToWorkList(N0.getNode());
890 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
892 DEBUG(dbgs() << "\nPromoting ";
893 Op.getNode()->dump(&DAG));
894 DebugLoc dl = Op.getDebugLoc();
895 return DAG.getNode(ISD::TRUNCATE, dl, VT,
896 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
901 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
902 if (!LegalOperations)
905 EVT VT = Op.getValueType();
906 if (VT.isVector() || !VT.isInteger())
909 // If operation type is 'undesirable', e.g. i16 on x86, consider
911 unsigned Opc = Op.getOpcode();
912 if (TLI.isTypeDesirableForOp(Opc, VT))
916 // Consult target whether it is a good idea to promote this operation and
917 // what's the right type to promote it to.
918 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
919 assert(PVT != VT && "Don't know what type to promote to!");
920 // fold (aext (aext x)) -> (aext x)
921 // fold (aext (zext x)) -> (zext x)
922 // fold (aext (sext x)) -> (sext x)
923 DEBUG(dbgs() << "\nPromoting ";
924 Op.getNode()->dump(&DAG));
925 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
930 bool DAGCombiner::PromoteLoad(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!");
950 DebugLoc dl = Op.getDebugLoc();
951 SDNode *N = Op.getNode();
952 LoadSDNode *LD = cast<LoadSDNode>(N);
953 EVT MemVT = LD->getMemoryVT();
954 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
955 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
957 : LD->getExtensionType();
958 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
959 LD->getChain(), LD->getBasePtr(),
960 LD->getPointerInfo(),
961 MemVT, LD->isVolatile(),
962 LD->isNonTemporal(), LD->getAlignment());
963 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
965 DEBUG(dbgs() << "\nPromoting ";
968 Result.getNode()->dump(&DAG);
970 WorkListRemover DeadNodes(*this);
971 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
972 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
973 removeFromWorkList(N);
975 AddToWorkList(Result.getNode());
982 //===----------------------------------------------------------------------===//
983 // Main DAG Combiner implementation
984 //===----------------------------------------------------------------------===//
986 void DAGCombiner::Run(CombineLevel AtLevel) {
987 // set the instance variables, so that the various visit routines may use it.
989 LegalOperations = Level >= AfterLegalizeVectorOps;
990 LegalTypes = Level >= AfterLegalizeTypes;
992 // Add all the dag nodes to the worklist.
993 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
994 E = DAG.allnodes_end(); I != E; ++I)
997 // Create a dummy node (which is not added to allnodes), that adds a reference
998 // to the root node, preventing it from being deleted, and tracking any
999 // changes of the root.
1000 HandleSDNode Dummy(DAG.getRoot());
1002 // The root of the dag may dangle to deleted nodes until the dag combiner is
1003 // done. Set it to null to avoid confusion.
1004 DAG.setRoot(SDValue());
1006 // while the worklist isn't empty, find a node and
1007 // try and combine it.
1008 while (!WorkListContents.empty()) {
1010 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1011 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1012 // worklist *should* contain, and check the node we want to visit is should
1013 // actually be visited.
1015 N = WorkListOrder.pop_back_val();
1016 } while (!WorkListContents.erase(N));
1018 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1019 // N is deleted from the DAG, since they too may now be dead or may have a
1020 // reduced number of uses, allowing other xforms.
1021 if (N->use_empty() && N != &Dummy) {
1022 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1023 AddToWorkList(N->getOperand(i).getNode());
1029 SDValue RV = combine(N);
1031 if (RV.getNode() == 0)
1036 // If we get back the same node we passed in, rather than a new node or
1037 // zero, we know that the node must have defined multiple values and
1038 // CombineTo was used. Since CombineTo takes care of the worklist
1039 // mechanics for us, we have no work to do in this case.
1040 if (RV.getNode() == N)
1043 assert(N->getOpcode() != ISD::DELETED_NODE &&
1044 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1045 "Node was deleted but visit returned new node!");
1047 DEBUG(dbgs() << "\nReplacing.3 ";
1049 dbgs() << "\nWith: ";
1050 RV.getNode()->dump(&DAG);
1053 // Transfer debug value.
1054 DAG.TransferDbgValues(SDValue(N, 0), RV);
1055 WorkListRemover DeadNodes(*this);
1056 if (N->getNumValues() == RV.getNode()->getNumValues())
1057 DAG.ReplaceAllUsesWith(N, RV.getNode());
1059 assert(N->getValueType(0) == RV.getValueType() &&
1060 N->getNumValues() == 1 && "Type mismatch");
1062 DAG.ReplaceAllUsesWith(N, &OpV);
1065 // Push the new node and any users onto the worklist
1066 AddToWorkList(RV.getNode());
1067 AddUsersToWorkList(RV.getNode());
1069 // Add any uses of the old node to the worklist in case this node is the
1070 // last one that uses them. They may become dead after this node is
1072 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1073 AddToWorkList(N->getOperand(i).getNode());
1075 // Finally, if the node is now dead, remove it from the graph. The node
1076 // may not be dead if the replacement process recursively simplified to
1077 // something else needing this node.
1078 if (N->use_empty()) {
1079 // Nodes can be reintroduced into the worklist. Make sure we do not
1080 // process a node that has been replaced.
1081 removeFromWorkList(N);
1083 // Finally, since the node is now dead, remove it from the graph.
1088 // If the root changed (e.g. it was a dead load, update the root).
1089 DAG.setRoot(Dummy.getValue());
1090 DAG.RemoveDeadNodes();
1093 SDValue DAGCombiner::visit(SDNode *N) {
1094 switch (N->getOpcode()) {
1096 case ISD::TokenFactor: return visitTokenFactor(N);
1097 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1098 case ISD::ADD: return visitADD(N);
1099 case ISD::SUB: return visitSUB(N);
1100 case ISD::ADDC: return visitADDC(N);
1101 case ISD::SUBC: return visitSUBC(N);
1102 case ISD::ADDE: return visitADDE(N);
1103 case ISD::SUBE: return visitSUBE(N);
1104 case ISD::MUL: return visitMUL(N);
1105 case ISD::SDIV: return visitSDIV(N);
1106 case ISD::UDIV: return visitUDIV(N);
1107 case ISD::SREM: return visitSREM(N);
1108 case ISD::UREM: return visitUREM(N);
1109 case ISD::MULHU: return visitMULHU(N);
1110 case ISD::MULHS: return visitMULHS(N);
1111 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1112 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1113 case ISD::SMULO: return visitSMULO(N);
1114 case ISD::UMULO: return visitUMULO(N);
1115 case ISD::SDIVREM: return visitSDIVREM(N);
1116 case ISD::UDIVREM: return visitUDIVREM(N);
1117 case ISD::AND: return visitAND(N);
1118 case ISD::OR: return visitOR(N);
1119 case ISD::XOR: return visitXOR(N);
1120 case ISD::SHL: return visitSHL(N);
1121 case ISD::SRA: return visitSRA(N);
1122 case ISD::SRL: return visitSRL(N);
1123 case ISD::CTLZ: return visitCTLZ(N);
1124 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1125 case ISD::CTTZ: return visitCTTZ(N);
1126 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1127 case ISD::CTPOP: return visitCTPOP(N);
1128 case ISD::SELECT: return visitSELECT(N);
1129 case ISD::SELECT_CC: return visitSELECT_CC(N);
1130 case ISD::SETCC: return visitSETCC(N);
1131 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1132 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1133 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1134 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1135 case ISD::TRUNCATE: return visitTRUNCATE(N);
1136 case ISD::BITCAST: return visitBITCAST(N);
1137 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1138 case ISD::FADD: return visitFADD(N);
1139 case ISD::FSUB: return visitFSUB(N);
1140 case ISD::FMUL: return visitFMUL(N);
1141 case ISD::FMA: return visitFMA(N);
1142 case ISD::FDIV: return visitFDIV(N);
1143 case ISD::FREM: return visitFREM(N);
1144 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1145 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1146 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1147 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1148 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1149 case ISD::FP_ROUND: return visitFP_ROUND(N);
1150 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1151 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1152 case ISD::FNEG: return visitFNEG(N);
1153 case ISD::FABS: return visitFABS(N);
1154 case ISD::FFLOOR: return visitFFLOOR(N);
1155 case ISD::FCEIL: return visitFCEIL(N);
1156 case ISD::FTRUNC: return visitFTRUNC(N);
1157 case ISD::BRCOND: return visitBRCOND(N);
1158 case ISD::BR_CC: return visitBR_CC(N);
1159 case ISD::LOAD: return visitLOAD(N);
1160 case ISD::STORE: return visitSTORE(N);
1161 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1162 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1163 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1164 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1165 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1166 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1171 SDValue DAGCombiner::combine(SDNode *N) {
1172 SDValue RV = visit(N);
1174 // If nothing happened, try a target-specific DAG combine.
1175 if (RV.getNode() == 0) {
1176 assert(N->getOpcode() != ISD::DELETED_NODE &&
1177 "Node was deleted but visit returned NULL!");
1179 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1180 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1182 // Expose the DAG combiner to the target combiner impls.
1183 TargetLowering::DAGCombinerInfo
1184 DagCombineInfo(DAG, Level, false, this);
1186 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1190 // If nothing happened still, try promoting the operation.
1191 if (RV.getNode() == 0) {
1192 switch (N->getOpcode()) {
1200 RV = PromoteIntBinOp(SDValue(N, 0));
1205 RV = PromoteIntShiftOp(SDValue(N, 0));
1207 case ISD::SIGN_EXTEND:
1208 case ISD::ZERO_EXTEND:
1209 case ISD::ANY_EXTEND:
1210 RV = PromoteExtend(SDValue(N, 0));
1213 if (PromoteLoad(SDValue(N, 0)))
1219 // If N is a commutative binary node, try commuting it to enable more
1221 if (RV.getNode() == 0 &&
1222 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1223 N->getNumValues() == 1) {
1224 SDValue N0 = N->getOperand(0);
1225 SDValue N1 = N->getOperand(1);
1227 // Constant operands are canonicalized to RHS.
1228 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1229 SDValue Ops[] = { N1, N0 };
1230 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1233 return SDValue(CSENode, 0);
1240 /// getInputChainForNode - Given a node, return its input chain if it has one,
1241 /// otherwise return a null sd operand.
1242 static SDValue getInputChainForNode(SDNode *N) {
1243 if (unsigned NumOps = N->getNumOperands()) {
1244 if (N->getOperand(0).getValueType() == MVT::Other)
1245 return N->getOperand(0);
1246 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1247 return N->getOperand(NumOps-1);
1248 for (unsigned i = 1; i < NumOps-1; ++i)
1249 if (N->getOperand(i).getValueType() == MVT::Other)
1250 return N->getOperand(i);
1255 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1256 // If N has two operands, where one has an input chain equal to the other,
1257 // the 'other' chain is redundant.
1258 if (N->getNumOperands() == 2) {
1259 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1260 return N->getOperand(0);
1261 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1262 return N->getOperand(1);
1265 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1266 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1267 SmallPtrSet<SDNode*, 16> SeenOps;
1268 bool Changed = false; // If we should replace this token factor.
1270 // Start out with this token factor.
1273 // Iterate through token factors. The TFs grows when new token factors are
1275 for (unsigned i = 0; i < TFs.size(); ++i) {
1276 SDNode *TF = TFs[i];
1278 // Check each of the operands.
1279 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1280 SDValue Op = TF->getOperand(i);
1282 switch (Op.getOpcode()) {
1283 case ISD::EntryToken:
1284 // Entry tokens don't need to be added to the list. They are
1289 case ISD::TokenFactor:
1290 if (Op.hasOneUse() &&
1291 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1292 // Queue up for processing.
1293 TFs.push_back(Op.getNode());
1294 // Clean up in case the token factor is removed.
1295 AddToWorkList(Op.getNode());
1302 // Only add if it isn't already in the list.
1303 if (SeenOps.insert(Op.getNode()))
1314 // If we've change things around then replace token factor.
1317 // The entry token is the only possible outcome.
1318 Result = DAG.getEntryNode();
1320 // New and improved token factor.
1321 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1322 MVT::Other, &Ops[0], Ops.size());
1325 // Don't add users to work list.
1326 return CombineTo(N, Result, false);
1332 /// MERGE_VALUES can always be eliminated.
1333 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1334 WorkListRemover DeadNodes(*this);
1335 // Replacing results may cause a different MERGE_VALUES to suddenly
1336 // be CSE'd with N, and carry its uses with it. Iterate until no
1337 // uses remain, to ensure that the node can be safely deleted.
1338 // First add the users of this node to the work list so that they
1339 // can be tried again once they have new operands.
1340 AddUsersToWorkList(N);
1342 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1343 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1344 } while (!N->use_empty());
1345 removeFromWorkList(N);
1347 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1351 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1352 SelectionDAG &DAG) {
1353 EVT VT = N0.getValueType();
1354 SDValue N00 = N0.getOperand(0);
1355 SDValue N01 = N0.getOperand(1);
1356 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1358 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1359 isa<ConstantSDNode>(N00.getOperand(1))) {
1360 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1361 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1362 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1363 N00.getOperand(0), N01),
1364 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1365 N00.getOperand(1), N01));
1366 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1372 SDValue DAGCombiner::visitADD(SDNode *N) {
1373 SDValue N0 = N->getOperand(0);
1374 SDValue N1 = N->getOperand(1);
1375 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1376 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1377 EVT VT = N0.getValueType();
1380 if (VT.isVector()) {
1381 SDValue FoldedVOp = SimplifyVBinOp(N);
1382 if (FoldedVOp.getNode()) return FoldedVOp;
1384 // fold (add x, 0) -> x, vector edition
1385 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1387 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1391 // fold (add x, undef) -> undef
1392 if (N0.getOpcode() == ISD::UNDEF)
1394 if (N1.getOpcode() == ISD::UNDEF)
1396 // fold (add c1, c2) -> c1+c2
1398 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1399 // canonicalize constant to RHS
1401 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1402 // fold (add x, 0) -> x
1403 if (N1C && N1C->isNullValue())
1405 // fold (add Sym, c) -> Sym+c
1406 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1407 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1408 GA->getOpcode() == ISD::GlobalAddress)
1409 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1411 (uint64_t)N1C->getSExtValue());
1412 // fold ((c1-A)+c2) -> (c1+c2)-A
1413 if (N1C && N0.getOpcode() == ISD::SUB)
1414 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1415 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1416 DAG.getConstant(N1C->getAPIntValue()+
1417 N0C->getAPIntValue(), VT),
1420 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1421 if (RADD.getNode() != 0)
1423 // fold ((0-A) + B) -> B-A
1424 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1425 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1426 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1427 // fold (A + (0-B)) -> A-B
1428 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1429 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1430 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1431 // fold (A+(B-A)) -> B
1432 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1433 return N1.getOperand(0);
1434 // fold ((B-A)+A) -> B
1435 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1436 return N0.getOperand(0);
1437 // fold (A+(B-(A+C))) to (B-C)
1438 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1439 N0 == N1.getOperand(1).getOperand(0))
1440 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1441 N1.getOperand(1).getOperand(1));
1442 // fold (A+(B-(C+A))) to (B-C)
1443 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1444 N0 == N1.getOperand(1).getOperand(1))
1445 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1446 N1.getOperand(1).getOperand(0));
1447 // fold (A+((B-A)+or-C)) to (B+or-C)
1448 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1449 N1.getOperand(0).getOpcode() == ISD::SUB &&
1450 N0 == N1.getOperand(0).getOperand(1))
1451 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1452 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1454 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1455 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1456 SDValue N00 = N0.getOperand(0);
1457 SDValue N01 = N0.getOperand(1);
1458 SDValue N10 = N1.getOperand(0);
1459 SDValue N11 = N1.getOperand(1);
1461 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1462 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1463 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1464 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1467 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1468 return SDValue(N, 0);
1470 // fold (a+b) -> (a|b) iff a and b share no bits.
1471 if (VT.isInteger() && !VT.isVector()) {
1472 APInt LHSZero, LHSOne;
1473 APInt RHSZero, RHSOne;
1474 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1476 if (LHSZero.getBoolValue()) {
1477 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1479 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1480 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1481 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1482 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1486 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1487 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1488 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1489 if (Result.getNode()) return Result;
1491 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1492 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1493 if (Result.getNode()) return Result;
1496 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1497 if (N1.getOpcode() == ISD::SHL &&
1498 N1.getOperand(0).getOpcode() == ISD::SUB)
1499 if (ConstantSDNode *C =
1500 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1501 if (C->getAPIntValue() == 0)
1502 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1503 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1504 N1.getOperand(0).getOperand(1),
1506 if (N0.getOpcode() == ISD::SHL &&
1507 N0.getOperand(0).getOpcode() == ISD::SUB)
1508 if (ConstantSDNode *C =
1509 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1510 if (C->getAPIntValue() == 0)
1511 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1512 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1513 N0.getOperand(0).getOperand(1),
1516 if (N1.getOpcode() == ISD::AND) {
1517 SDValue AndOp0 = N1.getOperand(0);
1518 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1519 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1520 unsigned DestBits = VT.getScalarType().getSizeInBits();
1522 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1523 // and similar xforms where the inner op is either ~0 or 0.
1524 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1525 DebugLoc DL = N->getDebugLoc();
1526 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1530 // add (sext i1), X -> sub X, (zext i1)
1531 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1532 N0.getOperand(0).getValueType() == MVT::i1 &&
1533 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1534 DebugLoc DL = N->getDebugLoc();
1535 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1536 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1542 SDValue DAGCombiner::visitADDC(SDNode *N) {
1543 SDValue N0 = N->getOperand(0);
1544 SDValue N1 = N->getOperand(1);
1545 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1547 EVT VT = N0.getValueType();
1549 // If the flag result is dead, turn this into an ADD.
1550 if (!N->hasAnyUseOfValue(1))
1551 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1552 DAG.getNode(ISD::CARRY_FALSE,
1553 N->getDebugLoc(), MVT::Glue));
1555 // canonicalize constant to RHS.
1557 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1559 // fold (addc x, 0) -> x + no carry out
1560 if (N1C && N1C->isNullValue())
1561 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1562 N->getDebugLoc(), MVT::Glue));
1564 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1565 APInt LHSZero, LHSOne;
1566 APInt RHSZero, RHSOne;
1567 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1569 if (LHSZero.getBoolValue()) {
1570 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1572 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1573 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1574 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1575 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1576 DAG.getNode(ISD::CARRY_FALSE,
1577 N->getDebugLoc(), MVT::Glue));
1583 SDValue DAGCombiner::visitADDE(SDNode *N) {
1584 SDValue N0 = N->getOperand(0);
1585 SDValue N1 = N->getOperand(1);
1586 SDValue CarryIn = N->getOperand(2);
1587 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1588 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1590 // canonicalize constant to RHS
1592 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1595 // fold (adde x, y, false) -> (addc x, y)
1596 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1597 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1602 // Since it may not be valid to emit a fold to zero for vector initializers
1603 // check if we can before folding.
1604 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1605 SelectionDAG &DAG, bool LegalOperations) {
1606 if (!VT.isVector()) {
1607 return DAG.getConstant(0, VT);
1609 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1610 // Produce a vector of zeros.
1611 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1612 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1613 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1614 &Ops[0], Ops.size());
1619 SDValue DAGCombiner::visitSUB(SDNode *N) {
1620 SDValue N0 = N->getOperand(0);
1621 SDValue N1 = N->getOperand(1);
1622 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1623 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1624 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1625 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1626 EVT VT = N0.getValueType();
1629 if (VT.isVector()) {
1630 SDValue FoldedVOp = SimplifyVBinOp(N);
1631 if (FoldedVOp.getNode()) return FoldedVOp;
1633 // fold (sub x, 0) -> x, vector edition
1634 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1638 // fold (sub x, x) -> 0
1639 // FIXME: Refactor this and xor and other similar operations together.
1641 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1642 // fold (sub c1, c2) -> c1-c2
1644 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1645 // fold (sub x, c) -> (add x, -c)
1647 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1648 DAG.getConstant(-N1C->getAPIntValue(), VT));
1649 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1650 if (N0C && N0C->isAllOnesValue())
1651 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1652 // fold A-(A-B) -> B
1653 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1654 return N1.getOperand(1);
1655 // fold (A+B)-A -> B
1656 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1657 return N0.getOperand(1);
1658 // fold (A+B)-B -> A
1659 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1660 return N0.getOperand(0);
1661 // fold C2-(A+C1) -> (C2-C1)-A
1662 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1663 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1665 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1668 // fold ((A+(B+or-C))-B) -> A+or-C
1669 if (N0.getOpcode() == ISD::ADD &&
1670 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1671 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1672 N0.getOperand(1).getOperand(0) == N1)
1673 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1674 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1675 // fold ((A+(C+B))-B) -> A+C
1676 if (N0.getOpcode() == ISD::ADD &&
1677 N0.getOperand(1).getOpcode() == ISD::ADD &&
1678 N0.getOperand(1).getOperand(1) == N1)
1679 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1680 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1681 // fold ((A-(B-C))-C) -> A-B
1682 if (N0.getOpcode() == ISD::SUB &&
1683 N0.getOperand(1).getOpcode() == ISD::SUB &&
1684 N0.getOperand(1).getOperand(1) == N1)
1685 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1686 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1688 // If either operand of a sub is undef, the result is undef
1689 if (N0.getOpcode() == ISD::UNDEF)
1691 if (N1.getOpcode() == ISD::UNDEF)
1694 // If the relocation model supports it, consider symbol offsets.
1695 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1696 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1697 // fold (sub Sym, c) -> Sym-c
1698 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1699 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1701 (uint64_t)N1C->getSExtValue());
1702 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1703 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1704 if (GA->getGlobal() == GB->getGlobal())
1705 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1712 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1713 SDValue N0 = N->getOperand(0);
1714 SDValue N1 = N->getOperand(1);
1715 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1716 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1717 EVT VT = N0.getValueType();
1719 // If the flag result is dead, turn this into an SUB.
1720 if (!N->hasAnyUseOfValue(1))
1721 return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1722 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1725 // fold (subc x, x) -> 0 + no borrow
1727 return CombineTo(N, DAG.getConstant(0, VT),
1728 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1731 // fold (subc x, 0) -> x + no borrow
1732 if (N1C && N1C->isNullValue())
1733 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1736 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1737 if (N0C && N0C->isAllOnesValue())
1738 return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1739 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1745 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1746 SDValue N0 = N->getOperand(0);
1747 SDValue N1 = N->getOperand(1);
1748 SDValue CarryIn = N->getOperand(2);
1750 // fold (sube x, y, false) -> (subc x, y)
1751 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1752 return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1757 SDValue DAGCombiner::visitMUL(SDNode *N) {
1758 SDValue N0 = N->getOperand(0);
1759 SDValue N1 = N->getOperand(1);
1760 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1761 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1762 EVT VT = N0.getValueType();
1765 if (VT.isVector()) {
1766 SDValue FoldedVOp = SimplifyVBinOp(N);
1767 if (FoldedVOp.getNode()) return FoldedVOp;
1770 // fold (mul x, undef) -> 0
1771 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1772 return DAG.getConstant(0, VT);
1773 // fold (mul c1, c2) -> c1*c2
1775 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1776 // canonicalize constant to RHS
1778 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1779 // fold (mul x, 0) -> 0
1780 if (N1C && N1C->isNullValue())
1782 // fold (mul x, -1) -> 0-x
1783 if (N1C && N1C->isAllOnesValue())
1784 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1785 DAG.getConstant(0, VT), N0);
1786 // fold (mul x, (1 << c)) -> x << c
1787 if (N1C && N1C->getAPIntValue().isPowerOf2())
1788 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1789 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1790 getShiftAmountTy(N0.getValueType())));
1791 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1792 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1793 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1794 // FIXME: If the input is something that is easily negated (e.g. a
1795 // single-use add), we should put the negate there.
1796 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1797 DAG.getConstant(0, VT),
1798 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1799 DAG.getConstant(Log2Val,
1800 getShiftAmountTy(N0.getValueType()))));
1802 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1803 if (N1C && N0.getOpcode() == ISD::SHL &&
1804 isa<ConstantSDNode>(N0.getOperand(1))) {
1805 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1806 N1, N0.getOperand(1));
1807 AddToWorkList(C3.getNode());
1808 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1809 N0.getOperand(0), C3);
1812 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1815 SDValue Sh(0,0), Y(0,0);
1816 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1817 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1818 N0.getNode()->hasOneUse()) {
1820 } else if (N1.getOpcode() == ISD::SHL &&
1821 isa<ConstantSDNode>(N1.getOperand(1)) &&
1822 N1.getNode()->hasOneUse()) {
1827 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1828 Sh.getOperand(0), Y);
1829 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1830 Mul, Sh.getOperand(1));
1834 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1835 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1836 isa<ConstantSDNode>(N0.getOperand(1)))
1837 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1838 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1839 N0.getOperand(0), N1),
1840 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1841 N0.getOperand(1), N1));
1844 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1845 if (RMUL.getNode() != 0)
1851 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1852 SDValue N0 = N->getOperand(0);
1853 SDValue N1 = N->getOperand(1);
1854 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1855 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1856 EVT VT = N->getValueType(0);
1859 if (VT.isVector()) {
1860 SDValue FoldedVOp = SimplifyVBinOp(N);
1861 if (FoldedVOp.getNode()) return FoldedVOp;
1864 // fold (sdiv c1, c2) -> c1/c2
1865 if (N0C && N1C && !N1C->isNullValue())
1866 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1867 // fold (sdiv X, 1) -> X
1868 if (N1C && N1C->getAPIntValue() == 1LL)
1870 // fold (sdiv X, -1) -> 0-X
1871 if (N1C && N1C->isAllOnesValue())
1872 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1873 DAG.getConstant(0, VT), N0);
1874 // If we know the sign bits of both operands are zero, strength reduce to a
1875 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1876 if (!VT.isVector()) {
1877 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1878 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1881 // fold (sdiv X, pow2) -> simple ops after legalize
1882 if (N1C && !N1C->isNullValue() &&
1883 (N1C->getAPIntValue().isPowerOf2() ||
1884 (-N1C->getAPIntValue()).isPowerOf2())) {
1885 // If dividing by powers of two is cheap, then don't perform the following
1887 if (TLI.isPow2DivCheap())
1890 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1892 // Splat the sign bit into the register
1893 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1894 DAG.getConstant(VT.getSizeInBits()-1,
1895 getShiftAmountTy(N0.getValueType())));
1896 AddToWorkList(SGN.getNode());
1898 // Add (N0 < 0) ? abs2 - 1 : 0;
1899 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1900 DAG.getConstant(VT.getSizeInBits() - lg2,
1901 getShiftAmountTy(SGN.getValueType())));
1902 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1903 AddToWorkList(SRL.getNode());
1904 AddToWorkList(ADD.getNode()); // Divide by pow2
1905 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1906 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1908 // If we're dividing by a positive value, we're done. Otherwise, we must
1909 // negate the result.
1910 if (N1C->getAPIntValue().isNonNegative())
1913 AddToWorkList(SRA.getNode());
1914 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1915 DAG.getConstant(0, VT), SRA);
1918 // if integer divide is expensive and we satisfy the requirements, emit an
1919 // alternate sequence.
1920 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1921 SDValue Op = BuildSDIV(N);
1922 if (Op.getNode()) return Op;
1926 if (N0.getOpcode() == ISD::UNDEF)
1927 return DAG.getConstant(0, VT);
1928 // X / undef -> undef
1929 if (N1.getOpcode() == ISD::UNDEF)
1935 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1936 SDValue N0 = N->getOperand(0);
1937 SDValue N1 = N->getOperand(1);
1938 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1939 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1940 EVT VT = N->getValueType(0);
1943 if (VT.isVector()) {
1944 SDValue FoldedVOp = SimplifyVBinOp(N);
1945 if (FoldedVOp.getNode()) return FoldedVOp;
1948 // fold (udiv c1, c2) -> c1/c2
1949 if (N0C && N1C && !N1C->isNullValue())
1950 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1951 // fold (udiv x, (1 << c)) -> x >>u c
1952 if (N1C && N1C->getAPIntValue().isPowerOf2())
1953 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1954 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1955 getShiftAmountTy(N0.getValueType())));
1956 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1957 if (N1.getOpcode() == ISD::SHL) {
1958 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1959 if (SHC->getAPIntValue().isPowerOf2()) {
1960 EVT ADDVT = N1.getOperand(1).getValueType();
1961 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1963 DAG.getConstant(SHC->getAPIntValue()
1966 AddToWorkList(Add.getNode());
1967 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1971 // fold (udiv x, c) -> alternate
1972 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1973 SDValue Op = BuildUDIV(N);
1974 if (Op.getNode()) return Op;
1978 if (N0.getOpcode() == ISD::UNDEF)
1979 return DAG.getConstant(0, VT);
1980 // X / undef -> undef
1981 if (N1.getOpcode() == ISD::UNDEF)
1987 SDValue DAGCombiner::visitSREM(SDNode *N) {
1988 SDValue N0 = N->getOperand(0);
1989 SDValue N1 = N->getOperand(1);
1990 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1991 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1992 EVT VT = N->getValueType(0);
1994 // fold (srem c1, c2) -> c1%c2
1995 if (N0C && N1C && !N1C->isNullValue())
1996 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1997 // If we know the sign bits of both operands are zero, strength reduce to a
1998 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1999 if (!VT.isVector()) {
2000 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2001 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
2004 // If X/C can be simplified by the division-by-constant logic, lower
2005 // X%C to the equivalent of X-X/C*C.
2006 if (N1C && !N1C->isNullValue()) {
2007 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
2008 AddToWorkList(Div.getNode());
2009 SDValue OptimizedDiv = combine(Div.getNode());
2010 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2011 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2013 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2014 AddToWorkList(Mul.getNode());
2020 if (N0.getOpcode() == ISD::UNDEF)
2021 return DAG.getConstant(0, VT);
2022 // X % undef -> undef
2023 if (N1.getOpcode() == ISD::UNDEF)
2029 SDValue DAGCombiner::visitUREM(SDNode *N) {
2030 SDValue N0 = N->getOperand(0);
2031 SDValue N1 = N->getOperand(1);
2032 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2033 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2034 EVT VT = N->getValueType(0);
2036 // fold (urem c1, c2) -> c1%c2
2037 if (N0C && N1C && !N1C->isNullValue())
2038 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2039 // fold (urem x, pow2) -> (and x, pow2-1)
2040 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2041 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2042 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2043 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2044 if (N1.getOpcode() == ISD::SHL) {
2045 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2046 if (SHC->getAPIntValue().isPowerOf2()) {
2048 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2049 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2051 AddToWorkList(Add.getNode());
2052 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2057 // If X/C can be simplified by the division-by-constant logic, lower
2058 // X%C to the equivalent of X-X/C*C.
2059 if (N1C && !N1C->isNullValue()) {
2060 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2061 AddToWorkList(Div.getNode());
2062 SDValue OptimizedDiv = combine(Div.getNode());
2063 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2064 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2066 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2067 AddToWorkList(Mul.getNode());
2073 if (N0.getOpcode() == ISD::UNDEF)
2074 return DAG.getConstant(0, VT);
2075 // X % undef -> undef
2076 if (N1.getOpcode() == ISD::UNDEF)
2082 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2083 SDValue N0 = N->getOperand(0);
2084 SDValue N1 = N->getOperand(1);
2085 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2086 EVT VT = N->getValueType(0);
2087 DebugLoc DL = N->getDebugLoc();
2089 // fold (mulhs x, 0) -> 0
2090 if (N1C && N1C->isNullValue())
2092 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2093 if (N1C && N1C->getAPIntValue() == 1)
2094 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2095 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2096 getShiftAmountTy(N0.getValueType())));
2097 // fold (mulhs x, undef) -> 0
2098 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2099 return DAG.getConstant(0, VT);
2101 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2103 if (VT.isSimple() && !VT.isVector()) {
2104 MVT Simple = VT.getSimpleVT();
2105 unsigned SimpleSize = Simple.getSizeInBits();
2106 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2107 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2108 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2109 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2110 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2111 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2112 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2113 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2120 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2121 SDValue N0 = N->getOperand(0);
2122 SDValue N1 = N->getOperand(1);
2123 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2124 EVT VT = N->getValueType(0);
2125 DebugLoc DL = N->getDebugLoc();
2127 // fold (mulhu x, 0) -> 0
2128 if (N1C && N1C->isNullValue())
2130 // fold (mulhu x, 1) -> 0
2131 if (N1C && N1C->getAPIntValue() == 1)
2132 return DAG.getConstant(0, N0.getValueType());
2133 // fold (mulhu x, undef) -> 0
2134 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2135 return DAG.getConstant(0, VT);
2137 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2139 if (VT.isSimple() && !VT.isVector()) {
2140 MVT Simple = VT.getSimpleVT();
2141 unsigned SimpleSize = Simple.getSizeInBits();
2142 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2143 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2144 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2145 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2146 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2147 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2148 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2149 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2156 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2157 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2158 /// that are being performed. Return true if a simplification was made.
2160 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2162 // If the high half is not needed, just compute the low half.
2163 bool HiExists = N->hasAnyUseOfValue(1);
2165 (!LegalOperations ||
2166 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2167 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2168 N->op_begin(), N->getNumOperands());
2169 return CombineTo(N, Res, Res);
2172 // If the low half is not needed, just compute the high half.
2173 bool LoExists = N->hasAnyUseOfValue(0);
2175 (!LegalOperations ||
2176 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2177 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2178 N->op_begin(), N->getNumOperands());
2179 return CombineTo(N, Res, Res);
2182 // If both halves are used, return as it is.
2183 if (LoExists && HiExists)
2186 // If the two computed results can be simplified separately, separate them.
2188 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2189 N->op_begin(), N->getNumOperands());
2190 AddToWorkList(Lo.getNode());
2191 SDValue LoOpt = combine(Lo.getNode());
2192 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2193 (!LegalOperations ||
2194 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2195 return CombineTo(N, LoOpt, LoOpt);
2199 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2200 N->op_begin(), N->getNumOperands());
2201 AddToWorkList(Hi.getNode());
2202 SDValue HiOpt = combine(Hi.getNode());
2203 if (HiOpt.getNode() && HiOpt != Hi &&
2204 (!LegalOperations ||
2205 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2206 return CombineTo(N, HiOpt, HiOpt);
2212 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2213 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2214 if (Res.getNode()) return Res;
2216 EVT VT = N->getValueType(0);
2217 DebugLoc DL = N->getDebugLoc();
2219 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2221 if (VT.isSimple() && !VT.isVector()) {
2222 MVT Simple = VT.getSimpleVT();
2223 unsigned SimpleSize = Simple.getSizeInBits();
2224 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2225 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2226 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2227 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2228 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2229 // Compute the high part as N1.
2230 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2231 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2232 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2233 // Compute the low part as N0.
2234 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2235 return CombineTo(N, Lo, Hi);
2242 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2243 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2244 if (Res.getNode()) return Res;
2246 EVT VT = N->getValueType(0);
2247 DebugLoc DL = N->getDebugLoc();
2249 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2251 if (VT.isSimple() && !VT.isVector()) {
2252 MVT Simple = VT.getSimpleVT();
2253 unsigned SimpleSize = Simple.getSizeInBits();
2254 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2255 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2256 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2257 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2258 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2259 // Compute the high part as N1.
2260 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2261 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2262 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2263 // Compute the low part as N0.
2264 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2265 return CombineTo(N, Lo, Hi);
2272 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2273 // (smulo x, 2) -> (saddo x, x)
2274 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2275 if (C2->getAPIntValue() == 2)
2276 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2277 N->getOperand(0), N->getOperand(0));
2282 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2283 // (umulo x, 2) -> (uaddo x, x)
2284 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2285 if (C2->getAPIntValue() == 2)
2286 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2287 N->getOperand(0), N->getOperand(0));
2292 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2293 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2294 if (Res.getNode()) return Res;
2299 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2300 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2301 if (Res.getNode()) return Res;
2306 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2307 /// two operands of the same opcode, try to simplify it.
2308 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2309 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2310 EVT VT = N0.getValueType();
2311 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2313 // Bail early if none of these transforms apply.
2314 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2316 // For each of OP in AND/OR/XOR:
2317 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2318 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2319 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2320 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2322 // do not sink logical op inside of a vector extend, since it may combine
2324 EVT Op0VT = N0.getOperand(0).getValueType();
2325 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2326 N0.getOpcode() == ISD::SIGN_EXTEND ||
2327 // Avoid infinite looping with PromoteIntBinOp.
2328 (N0.getOpcode() == ISD::ANY_EXTEND &&
2329 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2330 (N0.getOpcode() == ISD::TRUNCATE &&
2331 (!TLI.isZExtFree(VT, Op0VT) ||
2332 !TLI.isTruncateFree(Op0VT, VT)) &&
2333 TLI.isTypeLegal(Op0VT))) &&
2335 Op0VT == N1.getOperand(0).getValueType() &&
2336 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2337 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2338 N0.getOperand(0).getValueType(),
2339 N0.getOperand(0), N1.getOperand(0));
2340 AddToWorkList(ORNode.getNode());
2341 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2344 // For each of OP in SHL/SRL/SRA/AND...
2345 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2346 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2347 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2348 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2349 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2350 N0.getOperand(1) == N1.getOperand(1)) {
2351 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2352 N0.getOperand(0).getValueType(),
2353 N0.getOperand(0), N1.getOperand(0));
2354 AddToWorkList(ORNode.getNode());
2355 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2356 ORNode, N0.getOperand(1));
2359 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2360 // Only perform this optimization after type legalization and before
2361 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2362 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2363 // we don't want to undo this promotion.
2364 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2366 if ((N0.getOpcode() == ISD::BITCAST ||
2367 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2368 Level == AfterLegalizeTypes) {
2369 SDValue In0 = N0.getOperand(0);
2370 SDValue In1 = N1.getOperand(0);
2371 EVT In0Ty = In0.getValueType();
2372 EVT In1Ty = In1.getValueType();
2373 DebugLoc DL = N->getDebugLoc();
2374 // If both incoming values are integers, and the original types are the
2376 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2377 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2378 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2379 AddToWorkList(Op.getNode());
2384 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2385 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2386 // If both shuffles use the same mask, and both shuffle within a single
2387 // vector, then it is worthwhile to move the swizzle after the operation.
2388 // The type-legalizer generates this pattern when loading illegal
2389 // vector types from memory. In many cases this allows additional shuffle
2391 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2392 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2393 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2394 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2395 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2397 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2398 "Inputs to shuffles are not the same type");
2400 unsigned NumElts = VT.getVectorNumElements();
2402 // Check that both shuffles use the same mask. The masks are known to be of
2403 // the same length because the result vector type is the same.
2404 bool SameMask = true;
2405 for (unsigned i = 0; i != NumElts; ++i) {
2406 int Idx0 = SVN0->getMaskElt(i);
2407 int Idx1 = SVN1->getMaskElt(i);
2415 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2416 N0.getOperand(0), N1.getOperand(0));
2417 AddToWorkList(Op.getNode());
2418 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2419 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2426 SDValue DAGCombiner::visitAND(SDNode *N) {
2427 SDValue N0 = N->getOperand(0);
2428 SDValue N1 = N->getOperand(1);
2429 SDValue LL, LR, RL, RR, CC0, CC1;
2430 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2431 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2432 EVT VT = N1.getValueType();
2433 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2436 if (VT.isVector()) {
2437 SDValue FoldedVOp = SimplifyVBinOp(N);
2438 if (FoldedVOp.getNode()) return FoldedVOp;
2440 // fold (and x, 0) -> 0, vector edition
2441 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2443 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2446 // fold (and x, -1) -> x, vector edition
2447 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2449 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2453 // fold (and x, undef) -> 0
2454 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2455 return DAG.getConstant(0, VT);
2456 // fold (and c1, c2) -> c1&c2
2458 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2459 // canonicalize constant to RHS
2461 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2462 // fold (and x, -1) -> x
2463 if (N1C && N1C->isAllOnesValue())
2465 // if (and x, c) is known to be zero, return 0
2466 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2467 APInt::getAllOnesValue(BitWidth)))
2468 return DAG.getConstant(0, VT);
2470 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2471 if (RAND.getNode() != 0)
2473 // fold (and (or x, C), D) -> D if (C & D) == D
2474 if (N1C && N0.getOpcode() == ISD::OR)
2475 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2476 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2478 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2479 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2480 SDValue N0Op0 = N0.getOperand(0);
2481 APInt Mask = ~N1C->getAPIntValue();
2482 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2483 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2484 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2485 N0.getValueType(), N0Op0);
2487 // Replace uses of the AND with uses of the Zero extend node.
2490 // We actually want to replace all uses of the any_extend with the
2491 // zero_extend, to avoid duplicating things. This will later cause this
2492 // AND to be folded.
2493 CombineTo(N0.getNode(), Zext);
2494 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2497 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2498 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2499 // already be zero by virtue of the width of the base type of the load.
2501 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2503 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2504 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2505 N0.getOpcode() == ISD::LOAD) {
2506 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2507 N0 : N0.getOperand(0) );
2509 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2510 // This can be a pure constant or a vector splat, in which case we treat the
2511 // vector as a scalar and use the splat value.
2512 APInt Constant = APInt::getNullValue(1);
2513 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2514 Constant = C->getAPIntValue();
2515 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2516 APInt SplatValue, SplatUndef;
2517 unsigned SplatBitSize;
2519 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2520 SplatBitSize, HasAnyUndefs);
2522 // Undef bits can contribute to a possible optimisation if set, so
2524 SplatValue |= SplatUndef;
2526 // The splat value may be something like "0x00FFFFFF", which means 0 for
2527 // the first vector value and FF for the rest, repeating. We need a mask
2528 // that will apply equally to all members of the vector, so AND all the
2529 // lanes of the constant together.
2530 EVT VT = Vector->getValueType(0);
2531 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2533 // If the splat value has been compressed to a bitlength lower
2534 // than the size of the vector lane, we need to re-expand it to
2536 if (BitWidth > SplatBitSize)
2537 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2538 SplatBitSize < BitWidth;
2539 SplatBitSize = SplatBitSize * 2)
2540 SplatValue |= SplatValue.shl(SplatBitSize);
2542 Constant = APInt::getAllOnesValue(BitWidth);
2543 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2544 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2548 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2549 // actually legal and isn't going to get expanded, else this is a false
2551 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2552 Load->getMemoryVT());
2554 // Resize the constant to the same size as the original memory access before
2555 // extension. If it is still the AllOnesValue then this AND is completely
2558 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2561 switch (Load->getExtensionType()) {
2562 default: B = false; break;
2563 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2565 case ISD::NON_EXTLOAD: B = true; break;
2568 if (B && Constant.isAllOnesValue()) {
2569 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2570 // preserve semantics once we get rid of the AND.
2571 SDValue NewLoad(Load, 0);
2572 if (Load->getExtensionType() == ISD::EXTLOAD) {
2573 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2574 Load->getValueType(0), Load->getDebugLoc(),
2575 Load->getChain(), Load->getBasePtr(),
2576 Load->getOffset(), Load->getMemoryVT(),
2577 Load->getMemOperand());
2578 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2579 if (Load->getNumValues() == 3) {
2580 // PRE/POST_INC loads have 3 values.
2581 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2582 NewLoad.getValue(2) };
2583 CombineTo(Load, To, 3, true);
2585 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2589 // Fold the AND away, taking care not to fold to the old load node if we
2591 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2593 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2596 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2597 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2598 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2599 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2601 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2602 LL.getValueType().isInteger()) {
2603 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2604 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2605 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2606 LR.getValueType(), LL, RL);
2607 AddToWorkList(ORNode.getNode());
2608 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2610 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2611 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2612 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2613 LR.getValueType(), LL, RL);
2614 AddToWorkList(ANDNode.getNode());
2615 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2617 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2618 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2619 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2620 LR.getValueType(), LL, RL);
2621 AddToWorkList(ORNode.getNode());
2622 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2625 // canonicalize equivalent to ll == rl
2626 if (LL == RR && LR == RL) {
2627 Op1 = ISD::getSetCCSwappedOperands(Op1);
2630 if (LL == RL && LR == RR) {
2631 bool isInteger = LL.getValueType().isInteger();
2632 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2633 if (Result != ISD::SETCC_INVALID &&
2634 (!LegalOperations ||
2635 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2636 TLI.isOperationLegal(ISD::SETCC,
2637 TLI.getSetCCResultType(N0.getSimpleValueType())))))
2638 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2643 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2644 if (N0.getOpcode() == N1.getOpcode()) {
2645 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2646 if (Tmp.getNode()) return Tmp;
2649 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2650 // fold (and (sra)) -> (and (srl)) when possible.
2651 if (!VT.isVector() &&
2652 SimplifyDemandedBits(SDValue(N, 0)))
2653 return SDValue(N, 0);
2655 // fold (zext_inreg (extload x)) -> (zextload x)
2656 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2657 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2658 EVT MemVT = LN0->getMemoryVT();
2659 // If we zero all the possible extended bits, then we can turn this into
2660 // a zextload if we are running before legalize or the operation is legal.
2661 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2662 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2663 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2664 ((!LegalOperations && !LN0->isVolatile()) ||
2665 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2666 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2667 LN0->getChain(), LN0->getBasePtr(),
2668 LN0->getPointerInfo(), MemVT,
2669 LN0->isVolatile(), LN0->isNonTemporal(),
2670 LN0->getAlignment());
2672 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2673 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2676 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2677 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2679 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2680 EVT MemVT = LN0->getMemoryVT();
2681 // If we zero all the possible extended bits, then we can turn this into
2682 // a zextload if we are running before legalize or the operation is legal.
2683 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2684 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2685 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2686 ((!LegalOperations && !LN0->isVolatile()) ||
2687 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2688 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2690 LN0->getBasePtr(), LN0->getPointerInfo(),
2692 LN0->isVolatile(), LN0->isNonTemporal(),
2693 LN0->getAlignment());
2695 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2696 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2700 // fold (and (load x), 255) -> (zextload x, i8)
2701 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2702 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2703 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2704 (N0.getOpcode() == ISD::ANY_EXTEND &&
2705 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2706 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2707 LoadSDNode *LN0 = HasAnyExt
2708 ? cast<LoadSDNode>(N0.getOperand(0))
2709 : cast<LoadSDNode>(N0);
2710 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2711 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2712 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2713 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2714 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2715 EVT LoadedVT = LN0->getMemoryVT();
2717 if (ExtVT == LoadedVT &&
2718 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2719 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2722 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2723 LN0->getChain(), LN0->getBasePtr(),
2724 LN0->getPointerInfo(),
2725 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2726 LN0->getAlignment());
2728 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2729 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2732 // Do not change the width of a volatile load.
2733 // Do not generate loads of non-round integer types since these can
2734 // be expensive (and would be wrong if the type is not byte sized).
2735 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2736 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2737 EVT PtrType = LN0->getOperand(1).getValueType();
2739 unsigned Alignment = LN0->getAlignment();
2740 SDValue NewPtr = LN0->getBasePtr();
2742 // For big endian targets, we need to add an offset to the pointer
2743 // to load the correct bytes. For little endian systems, we merely
2744 // need to read fewer bytes from the same pointer.
2745 if (TLI.isBigEndian()) {
2746 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2747 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2748 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2749 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2750 NewPtr, DAG.getConstant(PtrOff, PtrType));
2751 Alignment = MinAlign(Alignment, PtrOff);
2754 AddToWorkList(NewPtr.getNode());
2756 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2758 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2759 LN0->getChain(), NewPtr,
2760 LN0->getPointerInfo(),
2761 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2764 CombineTo(LN0, Load, Load.getValue(1));
2765 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2771 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2772 VT.getSizeInBits() <= 64) {
2773 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2774 APInt ADDC = ADDI->getAPIntValue();
2775 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2776 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2777 // immediate for an add, but it is legal if its top c2 bits are set,
2778 // transform the ADD so the immediate doesn't need to be materialized
2780 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2781 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2782 SRLI->getZExtValue());
2783 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2785 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2787 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2788 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2789 CombineTo(N0.getNode(), NewAdd);
2790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2801 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2803 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2804 bool DemandHighBits) {
2805 if (!LegalOperations)
2808 EVT VT = N->getValueType(0);
2809 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2811 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2814 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2815 bool LookPassAnd0 = false;
2816 bool LookPassAnd1 = false;
2817 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2819 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2821 if (N0.getOpcode() == ISD::AND) {
2822 if (!N0.getNode()->hasOneUse())
2824 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2825 if (!N01C || N01C->getZExtValue() != 0xFF00)
2827 N0 = N0.getOperand(0);
2828 LookPassAnd0 = true;
2831 if (N1.getOpcode() == ISD::AND) {
2832 if (!N1.getNode()->hasOneUse())
2834 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2835 if (!N11C || N11C->getZExtValue() != 0xFF)
2837 N1 = N1.getOperand(0);
2838 LookPassAnd1 = true;
2841 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2843 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2845 if (!N0.getNode()->hasOneUse() ||
2846 !N1.getNode()->hasOneUse())
2849 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2850 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2853 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2856 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2857 SDValue N00 = N0->getOperand(0);
2858 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2859 if (!N00.getNode()->hasOneUse())
2861 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2862 if (!N001C || N001C->getZExtValue() != 0xFF)
2864 N00 = N00.getOperand(0);
2865 LookPassAnd0 = true;
2868 SDValue N10 = N1->getOperand(0);
2869 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2870 if (!N10.getNode()->hasOneUse())
2872 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2873 if (!N101C || N101C->getZExtValue() != 0xFF00)
2875 N10 = N10.getOperand(0);
2876 LookPassAnd1 = true;
2882 // Make sure everything beyond the low halfword is zero since the SRL 16
2883 // will clear the top bits.
2884 unsigned OpSizeInBits = VT.getSizeInBits();
2885 if (DemandHighBits && OpSizeInBits > 16 &&
2886 (!LookPassAnd0 || !LookPassAnd1) &&
2887 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2890 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2891 if (OpSizeInBits > 16)
2892 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2893 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2897 /// isBSwapHWordElement - Return true if the specified node is an element
2898 /// that makes up a 32-bit packed halfword byteswap. i.e.
2899 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2900 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2901 if (!N.getNode()->hasOneUse())
2904 unsigned Opc = N.getOpcode();
2905 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2908 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2913 switch (N1C->getZExtValue()) {
2916 case 0xFF: Num = 0; break;
2917 case 0xFF00: Num = 1; break;
2918 case 0xFF0000: Num = 2; break;
2919 case 0xFF000000: Num = 3; break;
2922 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2923 SDValue N0 = N.getOperand(0);
2924 if (Opc == ISD::AND) {
2925 if (Num == 0 || Num == 2) {
2927 // (x >> 8) & 0xff0000
2928 if (N0.getOpcode() != ISD::SRL)
2930 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2931 if (!C || C->getZExtValue() != 8)
2934 // (x << 8) & 0xff00
2935 // (x << 8) & 0xff000000
2936 if (N0.getOpcode() != ISD::SHL)
2938 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2939 if (!C || C->getZExtValue() != 8)
2942 } else if (Opc == ISD::SHL) {
2944 // (x & 0xff0000) << 8
2945 if (Num != 0 && Num != 2)
2947 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2948 if (!C || C->getZExtValue() != 8)
2950 } else { // Opc == ISD::SRL
2951 // (x & 0xff00) >> 8
2952 // (x & 0xff000000) >> 8
2953 if (Num != 1 && Num != 3)
2955 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2956 if (!C || C->getZExtValue() != 8)
2963 Parts[Num] = N0.getOperand(0).getNode();
2967 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2968 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2969 /// => (rotl (bswap x), 16)
2970 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2971 if (!LegalOperations)
2974 EVT VT = N->getValueType(0);
2977 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2980 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2982 // (or (or (and), (and)), (or (and), (and)))
2983 // (or (or (or (and), (and)), (and)), (and))
2984 if (N0.getOpcode() != ISD::OR)
2986 SDValue N00 = N0.getOperand(0);
2987 SDValue N01 = N0.getOperand(1);
2989 if (N1.getOpcode() == ISD::OR &&
2990 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
2991 // (or (or (and), (and)), (or (and), (and)))
2992 SDValue N000 = N00.getOperand(0);
2993 if (!isBSwapHWordElement(N000, Parts))
2996 SDValue N001 = N00.getOperand(1);
2997 if (!isBSwapHWordElement(N001, Parts))
2999 SDValue N010 = N01.getOperand(0);
3000 if (!isBSwapHWordElement(N010, Parts))
3002 SDValue N011 = N01.getOperand(1);
3003 if (!isBSwapHWordElement(N011, Parts))
3006 // (or (or (or (and), (and)), (and)), (and))
3007 if (!isBSwapHWordElement(N1, Parts))
3009 if (!isBSwapHWordElement(N01, Parts))
3011 if (N00.getOpcode() != ISD::OR)
3013 SDValue N000 = N00.getOperand(0);
3014 if (!isBSwapHWordElement(N000, Parts))
3016 SDValue N001 = N00.getOperand(1);
3017 if (!isBSwapHWordElement(N001, Parts))
3021 // Make sure the parts are all coming from the same node.
3022 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3025 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
3026 SDValue(Parts[0],0));
3028 // Result of the bswap should be rotated by 16. If it's not legal, than
3029 // do (x << 16) | (x >> 16).
3030 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3031 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3032 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
3033 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3034 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
3035 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
3036 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
3037 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
3040 SDValue DAGCombiner::visitOR(SDNode *N) {
3041 SDValue N0 = N->getOperand(0);
3042 SDValue N1 = N->getOperand(1);
3043 SDValue LL, LR, RL, RR, CC0, CC1;
3044 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3045 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3046 EVT VT = N1.getValueType();
3049 if (VT.isVector()) {
3050 SDValue FoldedVOp = SimplifyVBinOp(N);
3051 if (FoldedVOp.getNode()) return FoldedVOp;
3053 // fold (or x, 0) -> x, vector edition
3054 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3056 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3059 // fold (or x, -1) -> -1, vector edition
3060 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3062 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3066 // fold (or x, undef) -> -1
3067 if (!LegalOperations &&
3068 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3069 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3070 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3072 // fold (or c1, c2) -> c1|c2
3074 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3075 // canonicalize constant to RHS
3077 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3078 // fold (or x, 0) -> x
3079 if (N1C && N1C->isNullValue())
3081 // fold (or x, -1) -> -1
3082 if (N1C && N1C->isAllOnesValue())
3084 // fold (or x, c) -> c iff (x & ~c) == 0
3085 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3088 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3089 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3090 if (BSwap.getNode() != 0)
3092 BSwap = MatchBSwapHWordLow(N, N0, N1);
3093 if (BSwap.getNode() != 0)
3097 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3098 if (ROR.getNode() != 0)
3100 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3101 // iff (c1 & c2) == 0.
3102 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3103 isa<ConstantSDNode>(N0.getOperand(1))) {
3104 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3105 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3106 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3107 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3108 N0.getOperand(0), N1),
3109 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3111 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3112 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3113 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3114 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3116 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3117 LL.getValueType().isInteger()) {
3118 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3119 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3120 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3121 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3122 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3123 LR.getValueType(), LL, RL);
3124 AddToWorkList(ORNode.getNode());
3125 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3127 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3128 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3129 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3130 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3131 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3132 LR.getValueType(), LL, RL);
3133 AddToWorkList(ANDNode.getNode());
3134 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3137 // canonicalize equivalent to ll == rl
3138 if (LL == RR && LR == RL) {
3139 Op1 = ISD::getSetCCSwappedOperands(Op1);
3142 if (LL == RL && LR == RR) {
3143 bool isInteger = LL.getValueType().isInteger();
3144 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3145 if (Result != ISD::SETCC_INVALID &&
3146 (!LegalOperations ||
3147 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3148 TLI.isOperationLegal(ISD::SETCC,
3149 TLI.getSetCCResultType(N0.getValueType())))))
3150 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3155 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3156 if (N0.getOpcode() == N1.getOpcode()) {
3157 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3158 if (Tmp.getNode()) return Tmp;
3161 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3162 if (N0.getOpcode() == ISD::AND &&
3163 N1.getOpcode() == ISD::AND &&
3164 N0.getOperand(1).getOpcode() == ISD::Constant &&
3165 N1.getOperand(1).getOpcode() == ISD::Constant &&
3166 // Don't increase # computations.
3167 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3168 // We can only do this xform if we know that bits from X that are set in C2
3169 // but not in C1 are already zero. Likewise for Y.
3170 const APInt &LHSMask =
3171 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3172 const APInt &RHSMask =
3173 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3175 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3176 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3177 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3178 N0.getOperand(0), N1.getOperand(0));
3179 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3180 DAG.getConstant(LHSMask | RHSMask, VT));
3184 // See if this is some rotate idiom.
3185 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3186 return SDValue(Rot, 0);
3188 // Simplify the operands using demanded-bits information.
3189 if (!VT.isVector() &&
3190 SimplifyDemandedBits(SDValue(N, 0)))
3191 return SDValue(N, 0);
3196 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3197 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3198 if (Op.getOpcode() == ISD::AND) {
3199 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3200 Mask = Op.getOperand(1);
3201 Op = Op.getOperand(0);
3207 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3215 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3216 // idioms for rotate, and if the target supports rotation instructions, generate
3218 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3219 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3220 EVT VT = LHS.getValueType();
3221 if (!TLI.isTypeLegal(VT)) return 0;
3223 // The target must have at least one rotate flavor.
3224 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3225 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3226 if (!HasROTL && !HasROTR) return 0;
3228 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3229 SDValue LHSShift; // The shift.
3230 SDValue LHSMask; // AND value if any.
3231 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3232 return 0; // Not part of a rotate.
3234 SDValue RHSShift; // The shift.
3235 SDValue RHSMask; // AND value if any.
3236 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3237 return 0; // Not part of a rotate.
3239 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3240 return 0; // Not shifting the same value.
3242 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3243 return 0; // Shifts must disagree.
3245 // Canonicalize shl to left side in a shl/srl pair.
3246 if (RHSShift.getOpcode() == ISD::SHL) {
3247 std::swap(LHS, RHS);
3248 std::swap(LHSShift, RHSShift);
3249 std::swap(LHSMask , RHSMask );
3252 unsigned OpSizeInBits = VT.getSizeInBits();
3253 SDValue LHSShiftArg = LHSShift.getOperand(0);
3254 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3255 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3257 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3258 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3259 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3260 RHSShiftAmt.getOpcode() == ISD::Constant) {
3261 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3262 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3263 if ((LShVal + RShVal) != OpSizeInBits)
3266 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3267 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3269 // If there is an AND of either shifted operand, apply it to the result.
3270 if (LHSMask.getNode() || RHSMask.getNode()) {
3271 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3273 if (LHSMask.getNode()) {
3274 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3275 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3277 if (RHSMask.getNode()) {
3278 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3279 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3282 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3285 return Rot.getNode();
3288 // If there is a mask here, and we have a variable shift, we can't be sure
3289 // that we're masking out the right stuff.
3290 if (LHSMask.getNode() || RHSMask.getNode())
3293 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3294 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3295 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3296 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3297 if (ConstantSDNode *SUBC =
3298 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3299 if (SUBC->getAPIntValue() == OpSizeInBits) {
3300 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3301 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3306 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3307 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3308 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3309 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3310 if (ConstantSDNode *SUBC =
3311 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3312 if (SUBC->getAPIntValue() == OpSizeInBits) {
3313 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3314 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3319 // Look for sign/zext/any-extended or truncate cases:
3320 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3321 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3322 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3323 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3324 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3325 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3326 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3327 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3328 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3329 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3330 if (RExtOp0.getOpcode() == ISD::SUB &&
3331 RExtOp0.getOperand(1) == LExtOp0) {
3332 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3334 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3335 // (rotr x, (sub 32, y))
3336 if (ConstantSDNode *SUBC =
3337 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3338 if (SUBC->getAPIntValue() == OpSizeInBits) {
3339 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3341 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3344 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3345 RExtOp0 == LExtOp0.getOperand(1)) {
3346 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3348 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3349 // (rotl x, (sub 32, y))
3350 if (ConstantSDNode *SUBC =
3351 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3352 if (SUBC->getAPIntValue() == OpSizeInBits) {
3353 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3355 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3364 SDValue DAGCombiner::visitXOR(SDNode *N) {
3365 SDValue N0 = N->getOperand(0);
3366 SDValue N1 = N->getOperand(1);
3367 SDValue LHS, RHS, CC;
3368 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3370 EVT VT = N0.getValueType();
3373 if (VT.isVector()) {
3374 SDValue FoldedVOp = SimplifyVBinOp(N);
3375 if (FoldedVOp.getNode()) return FoldedVOp;
3377 // fold (xor x, 0) -> x, vector edition
3378 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3380 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3384 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3385 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3386 return DAG.getConstant(0, VT);
3387 // fold (xor x, undef) -> undef
3388 if (N0.getOpcode() == ISD::UNDEF)
3390 if (N1.getOpcode() == ISD::UNDEF)
3392 // fold (xor c1, c2) -> c1^c2
3394 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3395 // canonicalize constant to RHS
3397 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3398 // fold (xor x, 0) -> x
3399 if (N1C && N1C->isNullValue())
3402 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3403 if (RXOR.getNode() != 0)
3406 // fold !(x cc y) -> (x !cc y)
3407 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3408 bool isInt = LHS.getValueType().isInteger();
3409 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3412 if (!LegalOperations ||
3413 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3414 switch (N0.getOpcode()) {
3416 llvm_unreachable("Unhandled SetCC Equivalent!");
3418 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3419 case ISD::SELECT_CC:
3420 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3421 N0.getOperand(3), NotCC);
3426 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3427 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3428 N0.getNode()->hasOneUse() &&
3429 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3430 SDValue V = N0.getOperand(0);
3431 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3432 DAG.getConstant(1, V.getValueType()));
3433 AddToWorkList(V.getNode());
3434 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3437 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3438 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3439 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3440 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3441 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3442 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3443 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3444 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3445 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3446 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3449 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3450 if (N1C && N1C->isAllOnesValue() &&
3451 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3452 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3453 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3454 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3455 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3456 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3457 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3458 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3461 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3462 if (N1C && N0.getOpcode() == ISD::XOR) {
3463 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3464 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3466 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3467 DAG.getConstant(N1C->getAPIntValue() ^
3468 N00C->getAPIntValue(), VT));
3470 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3471 DAG.getConstant(N1C->getAPIntValue() ^
3472 N01C->getAPIntValue(), VT));
3474 // fold (xor x, x) -> 0
3476 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3478 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3479 if (N0.getOpcode() == N1.getOpcode()) {
3480 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3481 if (Tmp.getNode()) return Tmp;
3484 // Simplify the expression using non-local knowledge.
3485 if (!VT.isVector() &&
3486 SimplifyDemandedBits(SDValue(N, 0)))
3487 return SDValue(N, 0);
3492 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3493 /// the shift amount is a constant.
3494 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3495 SDNode *LHS = N->getOperand(0).getNode();
3496 if (!LHS->hasOneUse()) return SDValue();
3498 // We want to pull some binops through shifts, so that we have (and (shift))
3499 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3500 // thing happens with address calculations, so it's important to canonicalize
3502 bool HighBitSet = false; // Can we transform this if the high bit is set?
3504 switch (LHS->getOpcode()) {
3505 default: return SDValue();
3508 HighBitSet = false; // We can only transform sra if the high bit is clear.
3511 HighBitSet = true; // We can only transform sra if the high bit is set.
3514 if (N->getOpcode() != ISD::SHL)
3515 return SDValue(); // only shl(add) not sr[al](add).
3516 HighBitSet = false; // We can only transform sra if the high bit is clear.
3520 // We require the RHS of the binop to be a constant as well.
3521 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3522 if (!BinOpCst) return SDValue();
3524 // FIXME: disable this unless the input to the binop is a shift by a constant.
3525 // If it is not a shift, it pessimizes some common cases like:
3527 // void foo(int *X, int i) { X[i & 1235] = 1; }
3528 // int bar(int *X, int i) { return X[i & 255]; }
3529 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3530 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3531 BinOpLHSVal->getOpcode() != ISD::SRA &&
3532 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3533 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3536 EVT VT = N->getValueType(0);
3538 // If this is a signed shift right, and the high bit is modified by the
3539 // logical operation, do not perform the transformation. The highBitSet
3540 // boolean indicates the value of the high bit of the constant which would
3541 // cause it to be modified for this operation.
3542 if (N->getOpcode() == ISD::SRA) {
3543 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3544 if (BinOpRHSSignSet != HighBitSet)
3548 // Fold the constants, shifting the binop RHS by the shift amount.
3549 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3551 LHS->getOperand(1), N->getOperand(1));
3553 // Create the new shift.
3554 SDValue NewShift = DAG.getNode(N->getOpcode(),
3555 LHS->getOperand(0).getDebugLoc(),
3556 VT, LHS->getOperand(0), N->getOperand(1));
3558 // Create the new binop.
3559 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3562 SDValue DAGCombiner::visitSHL(SDNode *N) {
3563 SDValue N0 = N->getOperand(0);
3564 SDValue N1 = N->getOperand(1);
3565 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3566 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3567 EVT VT = N0.getValueType();
3568 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3570 // fold (shl c1, c2) -> c1<<c2
3572 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3573 // fold (shl 0, x) -> 0
3574 if (N0C && N0C->isNullValue())
3576 // fold (shl x, c >= size(x)) -> undef
3577 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3578 return DAG.getUNDEF(VT);
3579 // fold (shl x, 0) -> x
3580 if (N1C && N1C->isNullValue())
3582 // fold (shl undef, x) -> 0
3583 if (N0.getOpcode() == ISD::UNDEF)
3584 return DAG.getConstant(0, VT);
3585 // if (shl x, c) is known to be zero, return 0
3586 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3587 APInt::getAllOnesValue(OpSizeInBits)))
3588 return DAG.getConstant(0, VT);
3589 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3590 if (N1.getOpcode() == ISD::TRUNCATE &&
3591 N1.getOperand(0).getOpcode() == ISD::AND &&
3592 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3593 SDValue N101 = N1.getOperand(0).getOperand(1);
3594 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3595 EVT TruncVT = N1.getValueType();
3596 SDValue N100 = N1.getOperand(0).getOperand(0);
3597 APInt TruncC = N101C->getAPIntValue();
3598 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3599 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3600 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3601 DAG.getNode(ISD::TRUNCATE,
3604 DAG.getConstant(TruncC, TruncVT)));
3608 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3609 return SDValue(N, 0);
3611 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3612 if (N1C && N0.getOpcode() == ISD::SHL &&
3613 N0.getOperand(1).getOpcode() == ISD::Constant) {
3614 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3615 uint64_t c2 = N1C->getZExtValue();
3616 if (c1 + c2 >= OpSizeInBits)
3617 return DAG.getConstant(0, VT);
3618 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3619 DAG.getConstant(c1 + c2, N1.getValueType()));
3622 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3623 // For this to be valid, the second form must not preserve any of the bits
3624 // that are shifted out by the inner shift in the first form. This means
3625 // the outer shift size must be >= the number of bits added by the ext.
3626 // As a corollary, we don't care what kind of ext it is.
3627 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3628 N0.getOpcode() == ISD::ANY_EXTEND ||
3629 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3630 N0.getOperand(0).getOpcode() == ISD::SHL &&
3631 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3633 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3634 uint64_t c2 = N1C->getZExtValue();
3635 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3636 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3637 if (c2 >= OpSizeInBits - InnerShiftSize) {
3638 if (c1 + c2 >= OpSizeInBits)
3639 return DAG.getConstant(0, VT);
3640 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3641 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3642 N0.getOperand(0)->getOperand(0)),
3643 DAG.getConstant(c1 + c2, N1.getValueType()));
3647 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3648 // (and (srl x, (sub c1, c2), MASK)
3649 // Only fold this if the inner shift has no other uses -- if it does, folding
3650 // this will increase the total number of instructions.
3651 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3652 N0.getOperand(1).getOpcode() == ISD::Constant) {
3653 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3654 if (c1 < VT.getSizeInBits()) {
3655 uint64_t c2 = N1C->getZExtValue();
3656 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3657 VT.getSizeInBits() - c1);
3660 Mask = Mask.shl(c2-c1);
3661 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3662 DAG.getConstant(c2-c1, N1.getValueType()));
3664 Mask = Mask.lshr(c1-c2);
3665 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3666 DAG.getConstant(c1-c2, N1.getValueType()));
3668 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3669 DAG.getConstant(Mask, VT));
3672 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3673 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3674 SDValue HiBitsMask =
3675 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3676 VT.getSizeInBits() -
3677 N1C->getZExtValue()),
3679 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3684 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3685 if (NewSHL.getNode())
3692 SDValue DAGCombiner::visitSRA(SDNode *N) {
3693 SDValue N0 = N->getOperand(0);
3694 SDValue N1 = N->getOperand(1);
3695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3697 EVT VT = N0.getValueType();
3698 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3700 // fold (sra c1, c2) -> (sra c1, c2)
3702 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3703 // fold (sra 0, x) -> 0
3704 if (N0C && N0C->isNullValue())
3706 // fold (sra -1, x) -> -1
3707 if (N0C && N0C->isAllOnesValue())
3709 // fold (sra x, (setge c, size(x))) -> undef
3710 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3711 return DAG.getUNDEF(VT);
3712 // fold (sra x, 0) -> x
3713 if (N1C && N1C->isNullValue())
3715 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3717 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3718 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3719 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3721 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3722 ExtVT, VT.getVectorNumElements());
3723 if ((!LegalOperations ||
3724 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3725 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3726 N0.getOperand(0), DAG.getValueType(ExtVT));
3729 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3730 if (N1C && N0.getOpcode() == ISD::SRA) {
3731 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3732 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3733 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3734 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3735 DAG.getConstant(Sum, N1C->getValueType(0)));
3739 // fold (sra (shl X, m), (sub result_size, n))
3740 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3741 // result_size - n != m.
3742 // If truncate is free for the target sext(shl) is likely to result in better
3744 if (N0.getOpcode() == ISD::SHL) {
3745 // Get the two constanst of the shifts, CN0 = m, CN = n.
3746 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3748 // Determine what the truncate's result bitsize and type would be.
3750 EVT::getIntegerVT(*DAG.getContext(),
3751 OpSizeInBits - N1C->getZExtValue());
3752 // Determine the residual right-shift amount.
3753 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3755 // If the shift is not a no-op (in which case this should be just a sign
3756 // extend already), the truncated to type is legal, sign_extend is legal
3757 // on that type, and the truncate to that type is both legal and free,
3758 // perform the transform.
3759 if ((ShiftAmt > 0) &&
3760 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3761 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3762 TLI.isTruncateFree(VT, TruncVT)) {
3764 SDValue Amt = DAG.getConstant(ShiftAmt,
3765 getShiftAmountTy(N0.getOperand(0).getValueType()));
3766 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3767 N0.getOperand(0), Amt);
3768 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3770 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3771 N->getValueType(0), Trunc);
3776 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3777 if (N1.getOpcode() == ISD::TRUNCATE &&
3778 N1.getOperand(0).getOpcode() == ISD::AND &&
3779 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3780 SDValue N101 = N1.getOperand(0).getOperand(1);
3781 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3782 EVT TruncVT = N1.getValueType();
3783 SDValue N100 = N1.getOperand(0).getOperand(0);
3784 APInt TruncC = N101C->getAPIntValue();
3785 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3786 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3787 DAG.getNode(ISD::AND, N->getDebugLoc(),
3789 DAG.getNode(ISD::TRUNCATE,
3792 DAG.getConstant(TruncC, TruncVT)));
3796 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3797 // if c1 is equal to the number of bits the trunc removes
3798 if (N0.getOpcode() == ISD::TRUNCATE &&
3799 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3800 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3801 N0.getOperand(0).hasOneUse() &&
3802 N0.getOperand(0).getOperand(1).hasOneUse() &&
3803 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3804 EVT LargeVT = N0.getOperand(0).getValueType();
3805 ConstantSDNode *LargeShiftAmt =
3806 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3808 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3809 LargeShiftAmt->getZExtValue()) {
3811 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3812 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3813 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3814 N0.getOperand(0).getOperand(0), Amt);
3815 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3819 // Simplify, based on bits shifted out of the LHS.
3820 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3821 return SDValue(N, 0);
3824 // If the sign bit is known to be zero, switch this to a SRL.
3825 if (DAG.SignBitIsZero(N0))
3826 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3829 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3830 if (NewSRA.getNode())
3837 SDValue DAGCombiner::visitSRL(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 (srl c1, c2) -> c1 >>u c2
3847 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3848 // fold (srl 0, x) -> 0
3849 if (N0C && N0C->isNullValue())
3851 // fold (srl x, c >= size(x)) -> undef
3852 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3853 return DAG.getUNDEF(VT);
3854 // fold (srl x, 0) -> x
3855 if (N1C && N1C->isNullValue())
3857 // if (srl x, c) is known to be zero, return 0
3858 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3859 APInt::getAllOnesValue(OpSizeInBits)))
3860 return DAG.getConstant(0, VT);
3862 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3863 if (N1C && N0.getOpcode() == ISD::SRL &&
3864 N0.getOperand(1).getOpcode() == ISD::Constant) {
3865 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3866 uint64_t c2 = N1C->getZExtValue();
3867 if (c1 + c2 >= OpSizeInBits)
3868 return DAG.getConstant(0, VT);
3869 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3870 DAG.getConstant(c1 + c2, N1.getValueType()));
3873 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3874 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3875 N0.getOperand(0).getOpcode() == ISD::SRL &&
3876 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3878 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3879 uint64_t c2 = N1C->getZExtValue();
3880 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3881 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3882 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3883 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3884 if (c1 + OpSizeInBits == InnerShiftSize) {
3885 if (c1 + c2 >= InnerShiftSize)
3886 return DAG.getConstant(0, VT);
3887 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3888 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3889 N0.getOperand(0)->getOperand(0),
3890 DAG.getConstant(c1 + c2, ShiftCountVT)));
3894 // fold (srl (shl x, c), c) -> (and x, cst2)
3895 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3896 N0.getValueSizeInBits() <= 64) {
3897 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3898 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3899 DAG.getConstant(~0ULL >> ShAmt, VT));
3903 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3904 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3905 // Shifting in all undef bits?
3906 EVT SmallVT = N0.getOperand(0).getValueType();
3907 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3908 return DAG.getUNDEF(VT);
3910 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3911 uint64_t ShiftAmt = N1C->getZExtValue();
3912 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3914 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3915 AddToWorkList(SmallShift.getNode());
3916 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3920 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3921 // bit, which is unmodified by sra.
3922 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3923 if (N0.getOpcode() == ISD::SRA)
3924 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3927 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3928 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3929 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3930 APInt KnownZero, KnownOne;
3931 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3933 // If any of the input bits are KnownOne, then the input couldn't be all
3934 // zeros, thus the result of the srl will always be zero.
3935 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3937 // If all of the bits input the to ctlz node are known to be zero, then
3938 // the result of the ctlz is "32" and the result of the shift is one.
3939 APInt UnknownBits = ~KnownZero;
3940 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3942 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3943 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3944 // Okay, we know that only that the single bit specified by UnknownBits
3945 // could be set on input to the CTLZ node. If this bit is set, the SRL
3946 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3947 // to an SRL/XOR pair, which is likely to simplify more.
3948 unsigned ShAmt = UnknownBits.countTrailingZeros();
3949 SDValue Op = N0.getOperand(0);
3952 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3953 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3954 AddToWorkList(Op.getNode());
3957 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3958 Op, DAG.getConstant(1, VT));
3962 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3963 if (N1.getOpcode() == ISD::TRUNCATE &&
3964 N1.getOperand(0).getOpcode() == ISD::AND &&
3965 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3966 SDValue N101 = N1.getOperand(0).getOperand(1);
3967 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3968 EVT TruncVT = N1.getValueType();
3969 SDValue N100 = N1.getOperand(0).getOperand(0);
3970 APInt TruncC = N101C->getAPIntValue();
3971 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3972 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3973 DAG.getNode(ISD::AND, N->getDebugLoc(),
3975 DAG.getNode(ISD::TRUNCATE,
3978 DAG.getConstant(TruncC, TruncVT)));
3982 // fold operands of srl based on knowledge that the low bits are not
3984 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3985 return SDValue(N, 0);
3988 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3989 if (NewSRL.getNode())
3993 // Attempt to convert a srl of a load into a narrower zero-extending load.
3994 SDValue NarrowLoad = ReduceLoadWidth(N);
3995 if (NarrowLoad.getNode())
3998 // Here is a common situation. We want to optimize:
4001 // %b = and i32 %a, 2
4002 // %c = srl i32 %b, 1
4003 // brcond i32 %c ...
4009 // %c = setcc eq %b, 0
4012 // However when after the source operand of SRL is optimized into AND, the SRL
4013 // itself may not be optimized further. Look for it and add the BRCOND into
4015 if (N->hasOneUse()) {
4016 SDNode *Use = *N->use_begin();
4017 if (Use->getOpcode() == ISD::BRCOND)
4019 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4020 // Also look pass the truncate.
4021 Use = *Use->use_begin();
4022 if (Use->getOpcode() == ISD::BRCOND)
4030 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4031 SDValue N0 = N->getOperand(0);
4032 EVT VT = N->getValueType(0);
4034 // fold (ctlz c1) -> c2
4035 if (isa<ConstantSDNode>(N0))
4036 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
4040 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4041 SDValue N0 = N->getOperand(0);
4042 EVT VT = N->getValueType(0);
4044 // fold (ctlz_zero_undef c1) -> c2
4045 if (isa<ConstantSDNode>(N0))
4046 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4050 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4051 SDValue N0 = N->getOperand(0);
4052 EVT VT = N->getValueType(0);
4054 // fold (cttz c1) -> c2
4055 if (isa<ConstantSDNode>(N0))
4056 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
4060 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4061 SDValue N0 = N->getOperand(0);
4062 EVT VT = N->getValueType(0);
4064 // fold (cttz_zero_undef c1) -> c2
4065 if (isa<ConstantSDNode>(N0))
4066 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4070 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4071 SDValue N0 = N->getOperand(0);
4072 EVT VT = N->getValueType(0);
4074 // fold (ctpop c1) -> c2
4075 if (isa<ConstantSDNode>(N0))
4076 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4080 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4081 SDValue N0 = N->getOperand(0);
4082 SDValue N1 = N->getOperand(1);
4083 SDValue N2 = N->getOperand(2);
4084 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4085 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4086 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4087 EVT VT = N->getValueType(0);
4088 EVT VT0 = N0.getValueType();
4090 // fold (select C, X, X) -> X
4093 // fold (select true, X, Y) -> X
4094 if (N0C && !N0C->isNullValue())
4096 // fold (select false, X, Y) -> Y
4097 if (N0C && N0C->isNullValue())
4099 // fold (select C, 1, X) -> (or C, X)
4100 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4101 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4102 // fold (select C, 0, 1) -> (xor C, 1)
4103 if (VT.isInteger() &&
4106 TLI.getBooleanContents(false) ==
4107 TargetLowering::ZeroOrOneBooleanContent)) &&
4108 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4111 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4112 N0, DAG.getConstant(1, VT0));
4113 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4114 N0, DAG.getConstant(1, VT0));
4115 AddToWorkList(XORNode.getNode());
4117 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4118 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4120 // fold (select C, 0, X) -> (and (not C), X)
4121 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4122 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4123 AddToWorkList(NOTNode.getNode());
4124 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4126 // fold (select C, X, 1) -> (or (not C), X)
4127 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4128 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4129 AddToWorkList(NOTNode.getNode());
4130 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4132 // fold (select C, X, 0) -> (and C, X)
4133 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4134 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4135 // fold (select X, X, Y) -> (or X, Y)
4136 // fold (select X, 1, Y) -> (or X, Y)
4137 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4138 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4139 // fold (select X, Y, X) -> (and X, Y)
4140 // fold (select X, Y, 0) -> (and X, Y)
4141 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4142 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4144 // If we can fold this based on the true/false value, do so.
4145 if (SimplifySelectOps(N, N1, N2))
4146 return SDValue(N, 0); // Don't revisit N.
4148 // fold selects based on a setcc into other things, such as min/max/abs
4149 if (N0.getOpcode() == ISD::SETCC) {
4151 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4152 // having to say they don't support SELECT_CC on every type the DAG knows
4153 // about, since there is no way to mark an opcode illegal at all value types
4154 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4155 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4156 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4157 N0.getOperand(0), N0.getOperand(1),
4158 N1, N2, N0.getOperand(2));
4159 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4165 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4166 SDValue N0 = N->getOperand(0);
4167 SDValue N1 = N->getOperand(1);
4168 SDValue N2 = N->getOperand(2);
4169 SDValue N3 = N->getOperand(3);
4170 SDValue N4 = N->getOperand(4);
4171 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4173 // fold select_cc lhs, rhs, x, x, cc -> x
4177 // Determine if the condition we're dealing with is constant
4178 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4179 N0, N1, CC, N->getDebugLoc(), false);
4180 if (SCC.getNode()) AddToWorkList(SCC.getNode());
4182 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4183 if (!SCCC->isNullValue())
4184 return N2; // cond always true -> true val
4186 return N3; // cond always false -> false val
4189 // Fold to a simpler select_cc
4190 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4191 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4192 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4195 // If we can fold this based on the true/false value, do so.
4196 if (SimplifySelectOps(N, N2, N3))
4197 return SDValue(N, 0); // Don't revisit N.
4199 // fold select_cc into other things, such as min/max/abs
4200 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4203 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4204 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4205 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4209 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4210 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4211 // transformation. Returns true if extension are possible and the above
4212 // mentioned transformation is profitable.
4213 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4215 SmallVector<SDNode*, 4> &ExtendNodes,
4216 const TargetLowering &TLI) {
4217 bool HasCopyToRegUses = false;
4218 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4219 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4220 UE = N0.getNode()->use_end();
4225 if (UI.getUse().getResNo() != N0.getResNo())
4227 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4228 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4229 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4230 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4231 // Sign bits will be lost after a zext.
4234 for (unsigned i = 0; i != 2; ++i) {
4235 SDValue UseOp = User->getOperand(i);
4238 if (!isa<ConstantSDNode>(UseOp))
4243 ExtendNodes.push_back(User);
4246 // If truncates aren't free and there are users we can't
4247 // extend, it isn't worthwhile.
4250 // Remember if this value is live-out.
4251 if (User->getOpcode() == ISD::CopyToReg)
4252 HasCopyToRegUses = true;
4255 if (HasCopyToRegUses) {
4256 bool BothLiveOut = false;
4257 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4259 SDUse &Use = UI.getUse();
4260 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4266 // Both unextended and extended values are live out. There had better be
4267 // a good reason for the transformation.
4268 return ExtendNodes.size();
4273 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4274 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4275 ISD::NodeType ExtType) {
4276 // Extend SetCC uses if necessary.
4277 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4278 SDNode *SetCC = SetCCs[i];
4279 SmallVector<SDValue, 4> Ops;
4281 for (unsigned j = 0; j != 2; ++j) {
4282 SDValue SOp = SetCC->getOperand(j);
4284 Ops.push_back(ExtLoad);
4286 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4289 Ops.push_back(SetCC->getOperand(2));
4290 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4291 &Ops[0], Ops.size()));
4295 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4296 SDValue N0 = N->getOperand(0);
4297 EVT VT = N->getValueType(0);
4299 // fold (sext c1) -> c1
4300 if (isa<ConstantSDNode>(N0))
4301 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4303 // fold (sext (sext x)) -> (sext x)
4304 // fold (sext (aext x)) -> (sext x)
4305 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4306 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4309 if (N0.getOpcode() == ISD::TRUNCATE) {
4310 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4311 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4312 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4313 if (NarrowLoad.getNode()) {
4314 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4315 if (NarrowLoad.getNode() != N0.getNode()) {
4316 CombineTo(N0.getNode(), NarrowLoad);
4317 // CombineTo deleted the truncate, if needed, but not what's under it.
4320 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4323 // See if the value being truncated is already sign extended. If so, just
4324 // eliminate the trunc/sext pair.
4325 SDValue Op = N0.getOperand(0);
4326 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4327 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4328 unsigned DestBits = VT.getScalarType().getSizeInBits();
4329 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4331 if (OpBits == DestBits) {
4332 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4333 // bits, it is already ready.
4334 if (NumSignBits > DestBits-MidBits)
4336 } else if (OpBits < DestBits) {
4337 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4338 // bits, just sext from i32.
4339 if (NumSignBits > OpBits-MidBits)
4340 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4342 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4343 // bits, just truncate to i32.
4344 if (NumSignBits > OpBits-MidBits)
4345 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4348 // fold (sext (truncate x)) -> (sextinreg x).
4349 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4350 N0.getValueType())) {
4351 if (OpBits < DestBits)
4352 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4353 else if (OpBits > DestBits)
4354 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4355 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4356 DAG.getValueType(N0.getValueType()));
4360 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4361 // None of the supported targets knows how to perform load and sign extend
4362 // on vectors in one instruction. We only perform this transformation on
4364 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4365 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4366 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4367 bool DoXform = true;
4368 SmallVector<SDNode*, 4> SetCCs;
4369 if (!N0.hasOneUse())
4370 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4372 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4373 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4375 LN0->getBasePtr(), LN0->getPointerInfo(),
4377 LN0->isVolatile(), LN0->isNonTemporal(),
4378 LN0->getAlignment());
4379 CombineTo(N, ExtLoad);
4380 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4381 N0.getValueType(), ExtLoad);
4382 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4383 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4385 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4389 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4390 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4391 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4392 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4393 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4394 EVT MemVT = LN0->getMemoryVT();
4395 if ((!LegalOperations && !LN0->isVolatile()) ||
4396 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4397 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4399 LN0->getBasePtr(), LN0->getPointerInfo(),
4401 LN0->isVolatile(), LN0->isNonTemporal(),
4402 LN0->getAlignment());
4403 CombineTo(N, ExtLoad);
4404 CombineTo(N0.getNode(),
4405 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4406 N0.getValueType(), ExtLoad),
4407 ExtLoad.getValue(1));
4408 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4412 // fold (sext (and/or/xor (load x), cst)) ->
4413 // (and/or/xor (sextload x), (sext cst))
4414 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4415 N0.getOpcode() == ISD::XOR) &&
4416 isa<LoadSDNode>(N0.getOperand(0)) &&
4417 N0.getOperand(1).getOpcode() == ISD::Constant &&
4418 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4419 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4420 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4421 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4422 bool DoXform = true;
4423 SmallVector<SDNode*, 4> SetCCs;
4424 if (!N0.hasOneUse())
4425 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4428 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4429 LN0->getChain(), LN0->getBasePtr(),
4430 LN0->getPointerInfo(),
4433 LN0->isNonTemporal(),
4434 LN0->getAlignment());
4435 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4436 Mask = Mask.sext(VT.getSizeInBits());
4437 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4438 ExtLoad, DAG.getConstant(Mask, VT));
4439 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4440 N0.getOperand(0).getDebugLoc(),
4441 N0.getOperand(0).getValueType(), ExtLoad);
4443 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4444 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4446 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4451 if (N0.getOpcode() == ISD::SETCC) {
4452 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4453 // Only do this before legalize for now.
4454 if (VT.isVector() && !LegalOperations) {
4455 EVT N0VT = N0.getOperand(0).getValueType();
4456 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4457 // of the same size as the compared operands. Only optimize sext(setcc())
4458 // if this is the case.
4459 EVT SVT = TLI.getSetCCResultType(N0VT);
4461 // We know that the # elements of the results is the same as the
4462 // # elements of the compare (and the # elements of the compare result
4463 // for that matter). Check to see that they are the same size. If so,
4464 // we know that the element size of the sext'd result matches the
4465 // element size of the compare operands.
4466 if (VT.getSizeInBits() == SVT.getSizeInBits())
4467 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4469 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4470 // If the desired elements are smaller or larger than the source
4471 // elements we can use a matching integer vector type and then
4472 // truncate/sign extend
4473 EVT MatchingElementType =
4474 EVT::getIntegerVT(*DAG.getContext(),
4475 N0VT.getScalarType().getSizeInBits());
4476 EVT MatchingVectorType =
4477 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4478 N0VT.getVectorNumElements());
4480 if (SVT == MatchingVectorType) {
4481 SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4482 N0.getOperand(0), N0.getOperand(1),
4483 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4484 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4488 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4489 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4491 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4493 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4494 NegOne, DAG.getConstant(0, VT),
4495 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4496 if (SCC.getNode()) return SCC;
4497 if (!VT.isVector() && (!LegalOperations ||
4498 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT))))
4499 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4500 DAG.getSetCC(N->getDebugLoc(),
4501 TLI.getSetCCResultType(VT),
4502 N0.getOperand(0), N0.getOperand(1),
4503 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4504 NegOne, DAG.getConstant(0, VT));
4507 // fold (sext x) -> (zext x) if the sign bit is known zero.
4508 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4509 DAG.SignBitIsZero(N0))
4510 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4515 // isTruncateOf - If N is a truncate of some other value, return true, record
4516 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4517 // This function computes KnownZero to avoid a duplicated call to
4518 // ComputeMaskedBits in the caller.
4519 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4522 if (N->getOpcode() == ISD::TRUNCATE) {
4523 Op = N->getOperand(0);
4524 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4528 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4529 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4532 SDValue Op0 = N->getOperand(0);
4533 SDValue Op1 = N->getOperand(1);
4534 assert(Op0.getValueType() == Op1.getValueType());
4536 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4537 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4538 if (COp0 && COp0->isNullValue())
4540 else if (COp1 && COp1->isNullValue())
4545 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4547 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4553 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4554 SDValue N0 = N->getOperand(0);
4555 EVT VT = N->getValueType(0);
4557 // fold (zext c1) -> c1
4558 if (isa<ConstantSDNode>(N0))
4559 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4560 // fold (zext (zext x)) -> (zext x)
4561 // fold (zext (aext x)) -> (zext x)
4562 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4563 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4566 // fold (zext (truncate x)) -> (zext x) or
4567 // (zext (truncate x)) -> (truncate x)
4568 // This is valid when the truncated bits of x are already zero.
4569 // FIXME: We should extend this to work for vectors too.
4572 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4573 APInt TruncatedBits =
4574 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4575 APInt(Op.getValueSizeInBits(), 0) :
4576 APInt::getBitsSet(Op.getValueSizeInBits(),
4577 N0.getValueSizeInBits(),
4578 std::min(Op.getValueSizeInBits(),
4579 VT.getSizeInBits()));
4580 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4581 if (VT.bitsGT(Op.getValueType()))
4582 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4583 if (VT.bitsLT(Op.getValueType()))
4584 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4590 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4591 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4592 if (N0.getOpcode() == ISD::TRUNCATE) {
4593 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4594 if (NarrowLoad.getNode()) {
4595 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4596 if (NarrowLoad.getNode() != N0.getNode()) {
4597 CombineTo(N0.getNode(), NarrowLoad);
4598 // CombineTo deleted the truncate, if needed, but not what's under it.
4601 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4605 // fold (zext (truncate x)) -> (and x, mask)
4606 if (N0.getOpcode() == ISD::TRUNCATE &&
4607 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4609 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4610 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4611 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4612 if (NarrowLoad.getNode()) {
4613 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4614 if (NarrowLoad.getNode() != N0.getNode()) {
4615 CombineTo(N0.getNode(), NarrowLoad);
4616 // CombineTo deleted the truncate, if needed, but not what's under it.
4619 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4622 SDValue Op = N0.getOperand(0);
4623 if (Op.getValueType().bitsLT(VT)) {
4624 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4625 AddToWorkList(Op.getNode());
4626 } else if (Op.getValueType().bitsGT(VT)) {
4627 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4628 AddToWorkList(Op.getNode());
4630 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4631 N0.getValueType().getScalarType());
4634 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4635 // if either of the casts is not free.
4636 if (N0.getOpcode() == ISD::AND &&
4637 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4638 N0.getOperand(1).getOpcode() == ISD::Constant &&
4639 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4640 N0.getValueType()) ||
4641 !TLI.isZExtFree(N0.getValueType(), VT))) {
4642 SDValue X = N0.getOperand(0).getOperand(0);
4643 if (X.getValueType().bitsLT(VT)) {
4644 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4645 } else if (X.getValueType().bitsGT(VT)) {
4646 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4648 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4649 Mask = Mask.zext(VT.getSizeInBits());
4650 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4651 X, DAG.getConstant(Mask, VT));
4654 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4655 // None of the supported targets knows how to perform load and vector_zext
4656 // on vectors in one instruction. We only perform this transformation on
4658 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4659 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4660 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4661 bool DoXform = true;
4662 SmallVector<SDNode*, 4> SetCCs;
4663 if (!N0.hasOneUse())
4664 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4666 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4667 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4669 LN0->getBasePtr(), LN0->getPointerInfo(),
4671 LN0->isVolatile(), LN0->isNonTemporal(),
4672 LN0->getAlignment());
4673 CombineTo(N, ExtLoad);
4674 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4675 N0.getValueType(), ExtLoad);
4676 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4678 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4680 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4684 // fold (zext (and/or/xor (load x), cst)) ->
4685 // (and/or/xor (zextload x), (zext cst))
4686 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4687 N0.getOpcode() == ISD::XOR) &&
4688 isa<LoadSDNode>(N0.getOperand(0)) &&
4689 N0.getOperand(1).getOpcode() == ISD::Constant &&
4690 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4691 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4692 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4693 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4694 bool DoXform = true;
4695 SmallVector<SDNode*, 4> SetCCs;
4696 if (!N0.hasOneUse())
4697 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4700 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4701 LN0->getChain(), LN0->getBasePtr(),
4702 LN0->getPointerInfo(),
4705 LN0->isNonTemporal(),
4706 LN0->getAlignment());
4707 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4708 Mask = Mask.zext(VT.getSizeInBits());
4709 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4710 ExtLoad, DAG.getConstant(Mask, VT));
4711 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4712 N0.getOperand(0).getDebugLoc(),
4713 N0.getOperand(0).getValueType(), ExtLoad);
4715 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4716 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4718 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4723 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4724 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4725 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4726 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4727 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4728 EVT MemVT = LN0->getMemoryVT();
4729 if ((!LegalOperations && !LN0->isVolatile()) ||
4730 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4731 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4733 LN0->getBasePtr(), LN0->getPointerInfo(),
4735 LN0->isVolatile(), LN0->isNonTemporal(),
4736 LN0->getAlignment());
4737 CombineTo(N, ExtLoad);
4738 CombineTo(N0.getNode(),
4739 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4741 ExtLoad.getValue(1));
4742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4746 if (N0.getOpcode() == ISD::SETCC) {
4747 if (!LegalOperations && VT.isVector()) {
4748 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4749 // Only do this before legalize for now.
4750 EVT N0VT = N0.getOperand(0).getValueType();
4751 EVT EltVT = VT.getVectorElementType();
4752 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4753 DAG.getConstant(1, EltVT));
4754 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4755 // We know that the # elements of the results is the same as the
4756 // # elements of the compare (and the # elements of the compare result
4757 // for that matter). Check to see that they are the same size. If so,
4758 // we know that the element size of the sext'd result matches the
4759 // element size of the compare operands.
4760 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4761 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4763 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4764 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4765 &OneOps[0], OneOps.size()));
4767 // If the desired elements are smaller or larger than the source
4768 // elements we can use a matching integer vector type and then
4769 // truncate/sign extend
4770 EVT MatchingElementType =
4771 EVT::getIntegerVT(*DAG.getContext(),
4772 N0VT.getScalarType().getSizeInBits());
4773 EVT MatchingVectorType =
4774 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4775 N0VT.getVectorNumElements());
4777 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4779 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4780 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4781 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4782 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4783 &OneOps[0], OneOps.size()));
4786 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4788 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4789 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4790 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4791 if (SCC.getNode()) return SCC;
4794 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4795 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4796 isa<ConstantSDNode>(N0.getOperand(1)) &&
4797 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4799 SDValue ShAmt = N0.getOperand(1);
4800 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4801 if (N0.getOpcode() == ISD::SHL) {
4802 SDValue InnerZExt = N0.getOperand(0);
4803 // If the original shl may be shifting out bits, do not perform this
4805 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4806 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4807 if (ShAmtVal > KnownZeroBits)
4811 DebugLoc DL = N->getDebugLoc();
4813 // Ensure that the shift amount is wide enough for the shifted value.
4814 if (VT.getSizeInBits() >= 256)
4815 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4817 return DAG.getNode(N0.getOpcode(), DL, VT,
4818 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4825 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4826 SDValue N0 = N->getOperand(0);
4827 EVT VT = N->getValueType(0);
4829 // fold (aext c1) -> c1
4830 if (isa<ConstantSDNode>(N0))
4831 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4832 // fold (aext (aext x)) -> (aext x)
4833 // fold (aext (zext x)) -> (zext x)
4834 // fold (aext (sext x)) -> (sext x)
4835 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4836 N0.getOpcode() == ISD::ZERO_EXTEND ||
4837 N0.getOpcode() == ISD::SIGN_EXTEND)
4838 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4840 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4841 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4842 if (N0.getOpcode() == ISD::TRUNCATE) {
4843 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4844 if (NarrowLoad.getNode()) {
4845 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4846 if (NarrowLoad.getNode() != N0.getNode()) {
4847 CombineTo(N0.getNode(), NarrowLoad);
4848 // CombineTo deleted the truncate, if needed, but not what's under it.
4851 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4855 // fold (aext (truncate x))
4856 if (N0.getOpcode() == ISD::TRUNCATE) {
4857 SDValue TruncOp = N0.getOperand(0);
4858 if (TruncOp.getValueType() == VT)
4859 return TruncOp; // x iff x size == zext size.
4860 if (TruncOp.getValueType().bitsGT(VT))
4861 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4862 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4865 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4866 // if the trunc is not free.
4867 if (N0.getOpcode() == ISD::AND &&
4868 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4869 N0.getOperand(1).getOpcode() == ISD::Constant &&
4870 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4871 N0.getValueType())) {
4872 SDValue X = N0.getOperand(0).getOperand(0);
4873 if (X.getValueType().bitsLT(VT)) {
4874 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4875 } else if (X.getValueType().bitsGT(VT)) {
4876 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4878 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4879 Mask = Mask.zext(VT.getSizeInBits());
4880 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4881 X, DAG.getConstant(Mask, VT));
4884 // fold (aext (load x)) -> (aext (truncate (extload x)))
4885 // None of the supported targets knows how to perform load and any_ext
4886 // on vectors in one instruction. We only perform this transformation on
4888 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4889 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4890 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4891 bool DoXform = true;
4892 SmallVector<SDNode*, 4> SetCCs;
4893 if (!N0.hasOneUse())
4894 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4896 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4897 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4899 LN0->getBasePtr(), LN0->getPointerInfo(),
4901 LN0->isVolatile(), LN0->isNonTemporal(),
4902 LN0->getAlignment());
4903 CombineTo(N, ExtLoad);
4904 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4905 N0.getValueType(), ExtLoad);
4906 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4907 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4913 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4914 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4915 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4916 if (N0.getOpcode() == ISD::LOAD &&
4917 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4919 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4920 EVT MemVT = LN0->getMemoryVT();
4921 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4922 VT, LN0->getChain(), LN0->getBasePtr(),
4923 LN0->getPointerInfo(), MemVT,
4924 LN0->isVolatile(), LN0->isNonTemporal(),
4925 LN0->getAlignment());
4926 CombineTo(N, ExtLoad);
4927 CombineTo(N0.getNode(),
4928 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4929 N0.getValueType(), ExtLoad),
4930 ExtLoad.getValue(1));
4931 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4934 if (N0.getOpcode() == ISD::SETCC) {
4935 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4936 // Only do this before legalize for now.
4937 if (VT.isVector() && !LegalOperations) {
4938 EVT N0VT = N0.getOperand(0).getValueType();
4939 // We know that the # elements of the results is the same as the
4940 // # elements of the compare (and the # elements of the compare result
4941 // for that matter). Check to see that they are the same size. If so,
4942 // we know that the element size of the sext'd result matches the
4943 // element size of the compare operands.
4944 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4945 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4947 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4948 // If the desired elements are smaller or larger than the source
4949 // elements we can use a matching integer vector type and then
4950 // truncate/sign extend
4952 EVT MatchingElementType =
4953 EVT::getIntegerVT(*DAG.getContext(),
4954 N0VT.getScalarType().getSizeInBits());
4955 EVT MatchingVectorType =
4956 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4957 N0VT.getVectorNumElements());
4959 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4961 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4962 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4966 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4968 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4969 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4970 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4978 /// GetDemandedBits - See if the specified operand can be simplified with the
4979 /// knowledge that only the bits specified by Mask are used. If so, return the
4980 /// simpler operand, otherwise return a null SDValue.
4981 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4982 switch (V.getOpcode()) {
4984 case ISD::Constant: {
4985 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4986 assert(CV != 0 && "Const value should be ConstSDNode.");
4987 const APInt &CVal = CV->getAPIntValue();
4988 APInt NewVal = CVal & Mask;
4989 if (NewVal != CVal) {
4990 return DAG.getConstant(NewVal, V.getValueType());
4996 // If the LHS or RHS don't contribute bits to the or, drop them.
4997 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4998 return V.getOperand(1);
4999 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5000 return V.getOperand(0);
5003 // Only look at single-use SRLs.
5004 if (!V.getNode()->hasOneUse())
5006 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5007 // See if we can recursively simplify the LHS.
5008 unsigned Amt = RHSC->getZExtValue();
5010 // Watch out for shift count overflow though.
5011 if (Amt >= Mask.getBitWidth()) break;
5012 APInt NewMask = Mask << Amt;
5013 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5014 if (SimplifyLHS.getNode())
5015 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
5016 SimplifyLHS, V.getOperand(1));
5022 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5023 /// bits and then truncated to a narrower type and where N is a multiple
5024 /// of number of bits of the narrower type, transform it to a narrower load
5025 /// from address + N / num of bits of new type. If the result is to be
5026 /// extended, also fold the extension to form a extending load.
5027 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5028 unsigned Opc = N->getOpcode();
5030 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5031 SDValue N0 = N->getOperand(0);
5032 EVT VT = N->getValueType(0);
5035 // This transformation isn't valid for vector loads.
5039 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5041 if (Opc == ISD::SIGN_EXTEND_INREG) {
5042 ExtType = ISD::SEXTLOAD;
5043 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5044 } else if (Opc == ISD::SRL) {
5045 // Another special-case: SRL is basically zero-extending a narrower value.
5046 ExtType = ISD::ZEXTLOAD;
5048 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5049 if (!N01) return SDValue();
5050 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5051 VT.getSizeInBits() - N01->getZExtValue());
5053 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5056 unsigned EVTBits = ExtVT.getSizeInBits();
5058 // Do not generate loads of non-round integer types since these can
5059 // be expensive (and would be wrong if the type is not byte sized).
5060 if (!ExtVT.isRound())
5064 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5065 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5066 ShAmt = N01->getZExtValue();
5067 // Is the shift amount a multiple of size of VT?
5068 if ((ShAmt & (EVTBits-1)) == 0) {
5069 N0 = N0.getOperand(0);
5070 // Is the load width a multiple of size of VT?
5071 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5075 // At this point, we must have a load or else we can't do the transform.
5076 if (!isa<LoadSDNode>(N0)) return SDValue();
5078 // Because a SRL must be assumed to *need* to zero-extend the high bits
5079 // (as opposed to anyext the high bits), we can't combine the zextload
5080 // lowering of SRL and an sextload.
5081 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5084 // If the shift amount is larger than the input type then we're not
5085 // accessing any of the loaded bytes. If the load was a zextload/extload
5086 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5087 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5092 // If the load is shifted left (and the result isn't shifted back right),
5093 // we can fold the truncate through the shift.
5094 unsigned ShLeftAmt = 0;
5095 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5096 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5097 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5098 ShLeftAmt = N01->getZExtValue();
5099 N0 = N0.getOperand(0);
5103 // If we haven't found a load, we can't narrow it. Don't transform one with
5104 // multiple uses, this would require adding a new load.
5105 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5108 // Don't change the width of a volatile load.
5109 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5110 if (LN0->isVolatile())
5113 // Verify that we are actually reducing a load width here.
5114 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5117 // For the transform to be legal, the load must produce only two values
5118 // (the value loaded and the chain). Don't transform a pre-increment
5119 // load, for example, which produces an extra value. Otherwise the
5120 // transformation is not equivalent, and the downstream logic to replace
5121 // uses gets things wrong.
5122 if (LN0->getNumValues() > 2)
5125 EVT PtrType = N0.getOperand(1).getValueType();
5127 if (PtrType == MVT::Untyped || PtrType.isExtended())
5128 // It's not possible to generate a constant of extended or untyped type.
5131 // For big endian targets, we need to adjust the offset to the pointer to
5132 // load the correct bytes.
5133 if (TLI.isBigEndian()) {
5134 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5135 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5136 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5139 uint64_t PtrOff = ShAmt / 8;
5140 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5141 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5142 PtrType, LN0->getBasePtr(),
5143 DAG.getConstant(PtrOff, PtrType));
5144 AddToWorkList(NewPtr.getNode());
5147 if (ExtType == ISD::NON_EXTLOAD)
5148 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5149 LN0->getPointerInfo().getWithOffset(PtrOff),
5150 LN0->isVolatile(), LN0->isNonTemporal(),
5151 LN0->isInvariant(), NewAlign);
5153 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5154 LN0->getPointerInfo().getWithOffset(PtrOff),
5155 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5158 // Replace the old load's chain with the new load's chain.
5159 WorkListRemover DeadNodes(*this);
5160 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5162 // Shift the result left, if we've swallowed a left shift.
5163 SDValue Result = Load;
5164 if (ShLeftAmt != 0) {
5165 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5166 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5168 // If the shift amount is as large as the result size (but, presumably,
5169 // no larger than the source) then the useful bits of the result are
5170 // zero; we can't simply return the shortened shift, because the result
5171 // of that operation is undefined.
5172 if (ShLeftAmt >= VT.getSizeInBits())
5173 Result = DAG.getConstant(0, VT);
5175 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5176 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5179 // Return the new loaded value.
5183 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5184 SDValue N0 = N->getOperand(0);
5185 SDValue N1 = N->getOperand(1);
5186 EVT VT = N->getValueType(0);
5187 EVT EVT = cast<VTSDNode>(N1)->getVT();
5188 unsigned VTBits = VT.getScalarType().getSizeInBits();
5189 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5191 // fold (sext_in_reg c1) -> c1
5192 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5193 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5195 // If the input is already sign extended, just drop the extension.
5196 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5199 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5200 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5201 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5202 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5203 N0.getOperand(0), N1);
5206 // fold (sext_in_reg (sext x)) -> (sext x)
5207 // fold (sext_in_reg (aext x)) -> (sext x)
5208 // if x is small enough.
5209 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5210 SDValue N00 = N0.getOperand(0);
5211 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5212 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5213 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5216 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5217 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5218 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5220 // fold operands of sext_in_reg based on knowledge that the top bits are not
5222 if (SimplifyDemandedBits(SDValue(N, 0)))
5223 return SDValue(N, 0);
5225 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5226 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5227 SDValue NarrowLoad = ReduceLoadWidth(N);
5228 if (NarrowLoad.getNode())
5231 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5232 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5233 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5234 if (N0.getOpcode() == ISD::SRL) {
5235 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5236 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5237 // We can turn this into an SRA iff the input to the SRL is already sign
5239 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5240 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5241 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5242 N0.getOperand(0), N0.getOperand(1));
5246 // fold (sext_inreg (extload x)) -> (sextload x)
5247 if (ISD::isEXTLoad(N0.getNode()) &&
5248 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5249 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5250 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5251 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5252 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5253 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5255 LN0->getBasePtr(), LN0->getPointerInfo(),
5257 LN0->isVolatile(), LN0->isNonTemporal(),
5258 LN0->getAlignment());
5259 CombineTo(N, ExtLoad);
5260 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5261 AddToWorkList(ExtLoad.getNode());
5262 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5264 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5265 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5267 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5268 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5269 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5270 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5271 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5273 LN0->getBasePtr(), LN0->getPointerInfo(),
5275 LN0->isVolatile(), LN0->isNonTemporal(),
5276 LN0->getAlignment());
5277 CombineTo(N, ExtLoad);
5278 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5279 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5282 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5283 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5284 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5285 N0.getOperand(1), false);
5286 if (BSwap.getNode() != 0)
5287 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5294 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5295 SDValue N0 = N->getOperand(0);
5296 EVT VT = N->getValueType(0);
5297 bool isLE = TLI.isLittleEndian();
5300 if (N0.getValueType() == N->getValueType(0))
5302 // fold (truncate c1) -> c1
5303 if (isa<ConstantSDNode>(N0))
5304 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5305 // fold (truncate (truncate x)) -> (truncate x)
5306 if (N0.getOpcode() == ISD::TRUNCATE)
5307 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5308 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5309 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5310 N0.getOpcode() == ISD::SIGN_EXTEND ||
5311 N0.getOpcode() == ISD::ANY_EXTEND) {
5312 if (N0.getOperand(0).getValueType().bitsLT(VT))
5313 // if the source is smaller than the dest, we still need an extend
5314 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5316 if (N0.getOperand(0).getValueType().bitsGT(VT))
5317 // if the source is larger than the dest, than we just need the truncate
5318 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5319 // if the source and dest are the same type, we can drop both the extend
5320 // and the truncate.
5321 return N0.getOperand(0);
5324 // Fold extract-and-trunc into a narrow extract. For example:
5325 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5326 // i32 y = TRUNCATE(i64 x)
5328 // v16i8 b = BITCAST (v2i64 val)
5329 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5331 // Note: We only run this optimization after type legalization (which often
5332 // creates this pattern) and before operation legalization after which
5333 // we need to be more careful about the vector instructions that we generate.
5334 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5335 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5337 EVT VecTy = N0.getOperand(0).getValueType();
5338 EVT ExTy = N0.getValueType();
5339 EVT TrTy = N->getValueType(0);
5341 unsigned NumElem = VecTy.getVectorNumElements();
5342 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5344 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5345 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5347 SDValue EltNo = N0->getOperand(1);
5348 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5349 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5350 EVT IndexTy = N0->getOperand(1).getValueType();
5351 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5353 SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5354 NVT, N0.getOperand(0));
5356 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5357 N->getDebugLoc(), TrTy, V,
5358 DAG.getConstant(Index, IndexTy));
5362 // Fold a series of buildvector, bitcast, and truncate if possible.
5364 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5365 // (2xi32 (buildvector x, y)).
5366 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5367 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5368 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5369 N0.getOperand(0).hasOneUse()) {
5371 SDValue BuildVect = N0.getOperand(0);
5372 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5373 EVT TruncVecEltTy = VT.getVectorElementType();
5375 // Check that the element types match.
5376 if (BuildVectEltTy == TruncVecEltTy) {
5377 // Now we only need to compute the offset of the truncated elements.
5378 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5379 unsigned TruncVecNumElts = VT.getVectorNumElements();
5380 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5382 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5383 "Invalid number of elements");
5385 SmallVector<SDValue, 8> Opnds;
5386 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5387 Opnds.push_back(BuildVect.getOperand(i));
5389 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, &Opnds[0],
5394 // See if we can simplify the input to this truncate through knowledge that
5395 // only the low bits are being used.
5396 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5397 // Currently we only perform this optimization on scalars because vectors
5398 // may have different active low bits.
5399 if (!VT.isVector()) {
5401 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5402 VT.getSizeInBits()));
5403 if (Shorter.getNode())
5404 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5406 // fold (truncate (load x)) -> (smaller load x)
5407 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5408 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5409 SDValue Reduced = ReduceLoadWidth(N);
5410 if (Reduced.getNode())
5413 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5414 // where ... are all 'undef'.
5415 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5416 SmallVector<EVT, 8> VTs;
5419 unsigned NumDefs = 0;
5421 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5422 SDValue X = N0.getOperand(i);
5423 if (X.getOpcode() != ISD::UNDEF) {
5428 // Stop if more than one members are non-undef.
5431 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5432 VT.getVectorElementType(),
5433 X.getValueType().getVectorNumElements()));
5437 return DAG.getUNDEF(VT);
5440 assert(V.getNode() && "The single defined operand is empty!");
5441 SmallVector<SDValue, 8> Opnds;
5442 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5444 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5447 SDValue NV = DAG.getNode(ISD::TRUNCATE, V.getDebugLoc(), VTs[i], V);
5448 AddToWorkList(NV.getNode());
5449 Opnds.push_back(NV);
5451 return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
5452 &Opnds[0], Opnds.size());
5456 // Simplify the operands using demanded-bits information.
5457 if (!VT.isVector() &&
5458 SimplifyDemandedBits(SDValue(N, 0)))
5459 return SDValue(N, 0);
5464 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5465 SDValue Elt = N->getOperand(i);
5466 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5467 return Elt.getNode();
5468 return Elt.getOperand(Elt.getResNo()).getNode();
5471 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5472 /// if load locations are consecutive.
5473 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5474 assert(N->getOpcode() == ISD::BUILD_PAIR);
5476 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5477 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5478 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5479 LD1->getPointerInfo().getAddrSpace() !=
5480 LD2->getPointerInfo().getAddrSpace())
5482 EVT LD1VT = LD1->getValueType(0);
5484 if (ISD::isNON_EXTLoad(LD2) &&
5486 // If both are volatile this would reduce the number of volatile loads.
5487 // If one is volatile it might be ok, but play conservative and bail out.
5488 !LD1->isVolatile() &&
5489 !LD2->isVolatile() &&
5490 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5491 unsigned Align = LD1->getAlignment();
5492 unsigned NewAlign = TLI.getDataLayout()->
5493 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5495 if (NewAlign <= Align &&
5496 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5497 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5498 LD1->getBasePtr(), LD1->getPointerInfo(),
5499 false, false, false, Align);
5505 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5506 SDValue N0 = N->getOperand(0);
5507 EVT VT = N->getValueType(0);
5509 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5510 // Only do this before legalize, since afterward the target may be depending
5511 // on the bitconvert.
5512 // First check to see if this is all constant.
5514 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5516 bool isSimple = true;
5517 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5518 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5519 N0.getOperand(i).getOpcode() != ISD::Constant &&
5520 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5525 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5526 assert(!DestEltVT.isVector() &&
5527 "Element type of vector ValueType must not be vector!");
5529 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5532 // If the input is a constant, let getNode fold it.
5533 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5534 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5535 if (Res.getNode() != N) {
5536 if (!LegalOperations ||
5537 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5540 // Folding it resulted in an illegal node, and it's too late to
5541 // do that. Clean up the old node and forego the transformation.
5542 // Ideally this won't happen very often, because instcombine
5543 // and the earlier dagcombine runs (where illegal nodes are
5544 // permitted) should have folded most of them already.
5545 DAG.DeleteNode(Res.getNode());
5549 // (conv (conv x, t1), t2) -> (conv x, t2)
5550 if (N0.getOpcode() == ISD::BITCAST)
5551 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5554 // fold (conv (load x)) -> (load (conv*)x)
5555 // If the resultant load doesn't need a higher alignment than the original!
5556 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5557 // Do not change the width of a volatile load.
5558 !cast<LoadSDNode>(N0)->isVolatile() &&
5559 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5560 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5561 unsigned Align = TLI.getDataLayout()->
5562 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5563 unsigned OrigAlign = LN0->getAlignment();
5565 if (Align <= OrigAlign) {
5566 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5567 LN0->getBasePtr(), LN0->getPointerInfo(),
5568 LN0->isVolatile(), LN0->isNonTemporal(),
5569 LN0->isInvariant(), OrigAlign);
5571 CombineTo(N0.getNode(),
5572 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5573 N0.getValueType(), Load),
5579 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5580 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5581 // This often reduces constant pool loads.
5582 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5583 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5584 N0.getNode()->hasOneUse() && VT.isInteger() &&
5585 !VT.isVector() && !N0.getValueType().isVector()) {
5586 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5588 AddToWorkList(NewConv.getNode());
5590 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5591 if (N0.getOpcode() == ISD::FNEG)
5592 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5593 NewConv, DAG.getConstant(SignBit, VT));
5594 assert(N0.getOpcode() == ISD::FABS);
5595 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5596 NewConv, DAG.getConstant(~SignBit, VT));
5599 // fold (bitconvert (fcopysign cst, x)) ->
5600 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5601 // Note that we don't handle (copysign x, cst) because this can always be
5602 // folded to an fneg or fabs.
5603 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5604 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5605 VT.isInteger() && !VT.isVector()) {
5606 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5607 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5608 if (isTypeLegal(IntXVT)) {
5609 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5610 IntXVT, N0.getOperand(1));
5611 AddToWorkList(X.getNode());
5613 // If X has a different width than the result/lhs, sext it or truncate it.
5614 unsigned VTWidth = VT.getSizeInBits();
5615 if (OrigXWidth < VTWidth) {
5616 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5617 AddToWorkList(X.getNode());
5618 } else if (OrigXWidth > VTWidth) {
5619 // To get the sign bit in the right place, we have to shift it right
5620 // before truncating.
5621 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5622 X.getValueType(), X,
5623 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5624 AddToWorkList(X.getNode());
5625 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5626 AddToWorkList(X.getNode());
5629 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5630 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5631 X, DAG.getConstant(SignBit, VT));
5632 AddToWorkList(X.getNode());
5634 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5635 VT, N0.getOperand(0));
5636 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5637 Cst, DAG.getConstant(~SignBit, VT));
5638 AddToWorkList(Cst.getNode());
5640 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5644 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5645 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5646 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5647 if (CombineLD.getNode())
5654 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5655 EVT VT = N->getValueType(0);
5656 return CombineConsecutiveLoads(N, VT);
5659 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5660 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5661 /// destination element value type.
5662 SDValue DAGCombiner::
5663 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5664 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5666 // If this is already the right type, we're done.
5667 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5669 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5670 unsigned DstBitSize = DstEltVT.getSizeInBits();
5672 // If this is a conversion of N elements of one type to N elements of another
5673 // type, convert each element. This handles FP<->INT cases.
5674 if (SrcBitSize == DstBitSize) {
5675 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5676 BV->getValueType(0).getVectorNumElements());
5678 // Due to the FP element handling below calling this routine recursively,
5679 // we can end up with a scalar-to-vector node here.
5680 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5681 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5682 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5683 DstEltVT, BV->getOperand(0)));
5685 SmallVector<SDValue, 8> Ops;
5686 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5687 SDValue Op = BV->getOperand(i);
5688 // If the vector element type is not legal, the BUILD_VECTOR operands
5689 // are promoted and implicitly truncated. Make that explicit here.
5690 if (Op.getValueType() != SrcEltVT)
5691 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5692 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5694 AddToWorkList(Ops.back().getNode());
5696 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5697 &Ops[0], Ops.size());
5700 // Otherwise, we're growing or shrinking the elements. To avoid having to
5701 // handle annoying details of growing/shrinking FP values, we convert them to
5703 if (SrcEltVT.isFloatingPoint()) {
5704 // Convert the input float vector to a int vector where the elements are the
5706 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5707 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5708 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5712 // Now we know the input is an integer vector. If the output is a FP type,
5713 // convert to integer first, then to FP of the right size.
5714 if (DstEltVT.isFloatingPoint()) {
5715 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5716 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5717 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5719 // Next, convert to FP elements of the same size.
5720 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5723 // Okay, we know the src/dst types are both integers of differing types.
5724 // Handling growing first.
5725 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5726 if (SrcBitSize < DstBitSize) {
5727 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5729 SmallVector<SDValue, 8> Ops;
5730 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5731 i += NumInputsPerOutput) {
5732 bool isLE = TLI.isLittleEndian();
5733 APInt NewBits = APInt(DstBitSize, 0);
5734 bool EltIsUndef = true;
5735 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5736 // Shift the previously computed bits over.
5737 NewBits <<= SrcBitSize;
5738 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5739 if (Op.getOpcode() == ISD::UNDEF) continue;
5742 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5743 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5747 Ops.push_back(DAG.getUNDEF(DstEltVT));
5749 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5752 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5753 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5754 &Ops[0], Ops.size());
5757 // Finally, this must be the case where we are shrinking elements: each input
5758 // turns into multiple outputs.
5759 bool isS2V = ISD::isScalarToVector(BV);
5760 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5761 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5762 NumOutputsPerInput*BV->getNumOperands());
5763 SmallVector<SDValue, 8> Ops;
5765 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5766 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5767 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5768 Ops.push_back(DAG.getUNDEF(DstEltVT));
5772 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5773 getAPIntValue().zextOrTrunc(SrcBitSize);
5775 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5776 APInt ThisVal = OpVal.trunc(DstBitSize);
5777 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5778 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5779 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5780 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5782 OpVal = OpVal.lshr(DstBitSize);
5785 // For big endian targets, swap the order of the pieces of each element.
5786 if (TLI.isBigEndian())
5787 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5790 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5791 &Ops[0], Ops.size());
5794 SDValue DAGCombiner::visitFADD(SDNode *N) {
5795 SDValue N0 = N->getOperand(0);
5796 SDValue N1 = N->getOperand(1);
5797 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5798 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5799 EVT VT = N->getValueType(0);
5802 if (VT.isVector()) {
5803 SDValue FoldedVOp = SimplifyVBinOp(N);
5804 if (FoldedVOp.getNode()) return FoldedVOp;
5807 // fold (fadd c1, c2) -> c1 + c2
5809 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5810 // canonicalize constant to RHS
5811 if (N0CFP && !N1CFP)
5812 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5813 // fold (fadd A, 0) -> A
5814 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5815 N1CFP->getValueAPF().isZero())
5817 // fold (fadd A, (fneg B)) -> (fsub A, B)
5818 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5819 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5820 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5821 GetNegatedExpression(N1, DAG, LegalOperations));
5822 // fold (fadd (fneg A), B) -> (fsub B, A)
5823 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5824 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5825 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5826 GetNegatedExpression(N0, DAG, LegalOperations));
5828 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5829 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5830 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5831 isa<ConstantFPSDNode>(N0.getOperand(1)))
5832 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5833 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5834 N0.getOperand(1), N1));
5836 // No FP constant should be created after legalization as Instruction
5837 // Selection pass has hard time in dealing with FP constant.
5839 // We don't need test this condition for transformation like following, as
5840 // the DAG being transformed implies it is legal to take FP constant as
5843 // (fadd (fmul c, x), x) -> (fmul c+1, x)
5845 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5847 // If allow, fold (fadd (fneg x), x) -> 0.0
5848 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5849 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) {
5850 return DAG.getConstantFP(0.0, VT);
5853 // If allow, fold (fadd x, (fneg x)) -> 0.0
5854 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5855 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) {
5856 return DAG.getConstantFP(0.0, VT);
5859 // In unsafe math mode, we can fold chains of FADD's of the same value
5860 // into multiplications. This transform is not safe in general because
5861 // we are reducing the number of rounding steps.
5862 if (DAG.getTarget().Options.UnsafeFPMath &&
5863 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5865 if (N0.getOpcode() == ISD::FMUL) {
5866 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5867 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5869 // (fadd (fmul c, x), x) -> (fmul c+1, x)
5870 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5871 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5873 DAG.getConstantFP(1.0, VT));
5874 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5878 // (fadd (fmul x, c), x) -> (fmul c+1, x)
5879 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5880 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5882 DAG.getConstantFP(1.0, VT));
5883 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5887 // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x)
5888 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5889 N1.getOperand(0) == N1.getOperand(1) &&
5890 N0.getOperand(1) == N1.getOperand(0)) {
5891 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5893 DAG.getConstantFP(2.0, VT));
5894 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5895 N0.getOperand(1), NewCFP);
5898 // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x)
5899 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5900 N1.getOperand(0) == N1.getOperand(1) &&
5901 N0.getOperand(0) == N1.getOperand(0)) {
5902 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5904 DAG.getConstantFP(2.0, VT));
5905 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5906 N0.getOperand(0), NewCFP);
5910 if (N1.getOpcode() == ISD::FMUL) {
5911 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5912 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
5914 // (fadd x, (fmul c, x)) -> (fmul c+1, x)
5915 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
5916 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5918 DAG.getConstantFP(1.0, VT));
5919 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5923 // (fadd x, (fmul x, c)) -> (fmul c+1, x)
5924 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
5925 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5927 DAG.getConstantFP(1.0, VT));
5928 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5933 // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x)
5934 if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD &&
5935 N1.getOperand(0) == N1.getOperand(1) &&
5936 N0.getOperand(1) == N1.getOperand(0)) {
5937 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5939 DAG.getConstantFP(2.0, VT));
5940 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5941 N0.getOperand(1), NewCFP);
5944 // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x)
5945 if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD &&
5946 N1.getOperand(0) == N1.getOperand(1) &&
5947 N0.getOperand(0) == N1.getOperand(0)) {
5948 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5950 DAG.getConstantFP(2.0, VT));
5951 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5952 N0.getOperand(0), NewCFP);
5956 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
5957 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5958 // (fadd (fadd x, x), x) -> (fmul 3.0, x)
5959 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
5960 (N0.getOperand(0) == N1)) {
5961 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5962 N1, DAG.getConstantFP(3.0, VT));
5966 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
5967 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5968 // (fadd x, (fadd x, x)) -> (fmul 3.0, x)
5969 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
5970 N1.getOperand(0) == N0) {
5971 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5972 N0, DAG.getConstantFP(3.0, VT));
5976 // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x)
5977 if (AllowNewFpConst &&
5978 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
5979 N0.getOperand(0) == N0.getOperand(1) &&
5980 N1.getOperand(0) == N1.getOperand(1) &&
5981 N0.getOperand(0) == N1.getOperand(0)) {
5982 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5984 DAG.getConstantFP(4.0, VT));
5988 // FADD -> FMA combines:
5989 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5990 DAG.getTarget().Options.UnsafeFPMath) &&
5991 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5992 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5994 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5995 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5996 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5997 N0.getOperand(0), N0.getOperand(1), N1);
6000 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6001 // Note: Commutes FADD operands.
6002 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6003 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
6004 N1.getOperand(0), N1.getOperand(1), N0);
6011 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6012 SDValue N0 = N->getOperand(0);
6013 SDValue N1 = N->getOperand(1);
6014 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6015 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6016 EVT VT = N->getValueType(0);
6017 DebugLoc dl = N->getDebugLoc();
6020 if (VT.isVector()) {
6021 SDValue FoldedVOp = SimplifyVBinOp(N);
6022 if (FoldedVOp.getNode()) return FoldedVOp;
6025 // fold (fsub c1, c2) -> c1-c2
6027 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
6028 // fold (fsub A, 0) -> A
6029 if (DAG.getTarget().Options.UnsafeFPMath &&
6030 N1CFP && N1CFP->getValueAPF().isZero())
6032 // fold (fsub 0, B) -> -B
6033 if (DAG.getTarget().Options.UnsafeFPMath &&
6034 N0CFP && N0CFP->getValueAPF().isZero()) {
6035 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6036 return GetNegatedExpression(N1, DAG, LegalOperations);
6037 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6038 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6040 // fold (fsub A, (fneg B)) -> (fadd A, B)
6041 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6042 return DAG.getNode(ISD::FADD, dl, VT, N0,
6043 GetNegatedExpression(N1, DAG, LegalOperations));
6045 // If 'unsafe math' is enabled, fold
6046 // (fsub x, x) -> 0.0 &
6047 // (fsub x, (fadd x, y)) -> (fneg y) &
6048 // (fsub x, (fadd y, x)) -> (fneg y)
6049 if (DAG.getTarget().Options.UnsafeFPMath) {
6051 return DAG.getConstantFP(0.0f, VT);
6053 if (N1.getOpcode() == ISD::FADD) {
6054 SDValue N10 = N1->getOperand(0);
6055 SDValue N11 = N1->getOperand(1);
6057 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6058 &DAG.getTarget().Options))
6059 return GetNegatedExpression(N11, DAG, LegalOperations);
6060 else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6061 &DAG.getTarget().Options))
6062 return GetNegatedExpression(N10, DAG, LegalOperations);
6066 // FSUB -> FMA combines:
6067 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6068 DAG.getTarget().Options.UnsafeFPMath) &&
6069 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6070 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6072 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6073 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6074 return DAG.getNode(ISD::FMA, dl, VT,
6075 N0.getOperand(0), N0.getOperand(1),
6076 DAG.getNode(ISD::FNEG, dl, VT, N1));
6079 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6080 // Note: Commutes FSUB operands.
6081 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6082 return DAG.getNode(ISD::FMA, dl, VT,
6083 DAG.getNode(ISD::FNEG, dl, VT,
6085 N1.getOperand(1), N0);
6088 // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6089 if (N0.getOpcode() == ISD::FNEG &&
6090 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6091 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6092 SDValue N00 = N0.getOperand(0).getOperand(0);
6093 SDValue N01 = N0.getOperand(0).getOperand(1);
6094 return DAG.getNode(ISD::FMA, dl, VT,
6095 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6096 DAG.getNode(ISD::FNEG, dl, VT, N1));
6103 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6104 SDValue N0 = N->getOperand(0);
6105 SDValue N1 = N->getOperand(1);
6106 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6107 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6108 EVT VT = N->getValueType(0);
6109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6112 if (VT.isVector()) {
6113 SDValue FoldedVOp = SimplifyVBinOp(N);
6114 if (FoldedVOp.getNode()) return FoldedVOp;
6117 // fold (fmul c1, c2) -> c1*c2
6119 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
6120 // canonicalize constant to RHS
6121 if (N0CFP && !N1CFP)
6122 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
6123 // fold (fmul A, 0) -> 0
6124 if (DAG.getTarget().Options.UnsafeFPMath &&
6125 N1CFP && N1CFP->getValueAPF().isZero())
6127 // fold (fmul A, 0) -> 0, vector edition.
6128 if (DAG.getTarget().Options.UnsafeFPMath &&
6129 ISD::isBuildVectorAllZeros(N1.getNode()))
6131 // fold (fmul A, 1.0) -> A
6132 if (N1CFP && N1CFP->isExactlyValue(1.0))
6134 // fold (fmul X, 2.0) -> (fadd X, X)
6135 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6136 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
6137 // fold (fmul X, -1.0) -> (fneg X)
6138 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6139 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6140 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
6142 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6143 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6144 &DAG.getTarget().Options)) {
6145 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6146 &DAG.getTarget().Options)) {
6147 // Both can be negated for free, check to see if at least one is cheaper
6149 if (LHSNeg == 2 || RHSNeg == 2)
6150 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6151 GetNegatedExpression(N0, DAG, LegalOperations),
6152 GetNegatedExpression(N1, DAG, LegalOperations));
6156 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6157 if (DAG.getTarget().Options.UnsafeFPMath &&
6158 N1CFP && N0.getOpcode() == ISD::FMUL &&
6159 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6160 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
6161 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6162 N0.getOperand(1), N1));
6167 SDValue DAGCombiner::visitFMA(SDNode *N) {
6168 SDValue N0 = N->getOperand(0);
6169 SDValue N1 = N->getOperand(1);
6170 SDValue N2 = N->getOperand(2);
6171 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6172 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6173 EVT VT = N->getValueType(0);
6174 DebugLoc dl = N->getDebugLoc();
6176 if (DAG.getTarget().Options.UnsafeFPMath) {
6177 if (N0CFP && N0CFP->isZero())
6179 if (N1CFP && N1CFP->isZero())
6182 if (N0CFP && N0CFP->isExactlyValue(1.0))
6183 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
6184 if (N1CFP && N1CFP->isExactlyValue(1.0))
6185 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
6187 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6188 if (N0CFP && !N1CFP)
6189 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
6191 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6192 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6193 N2.getOpcode() == ISD::FMUL &&
6194 N0 == N2.getOperand(0) &&
6195 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6196 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6197 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6201 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6202 if (DAG.getTarget().Options.UnsafeFPMath &&
6203 N0.getOpcode() == ISD::FMUL && N1CFP &&
6204 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6205 return DAG.getNode(ISD::FMA, dl, VT,
6207 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6211 // (fma x, 1, y) -> (fadd x, y)
6212 // (fma x, -1, y) -> (fadd (fneg x), y)
6214 if (N1CFP->isExactlyValue(1.0))
6215 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6217 if (N1CFP->isExactlyValue(-1.0) &&
6218 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6219 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6220 AddToWorkList(RHSNeg.getNode());
6221 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6225 // (fma x, c, x) -> (fmul x, (c+1))
6226 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6227 return DAG.getNode(ISD::FMUL, dl, VT,
6229 DAG.getNode(ISD::FADD, dl, VT,
6230 N1, DAG.getConstantFP(1.0, VT)));
6233 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6234 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6235 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6236 return DAG.getNode(ISD::FMUL, dl, VT,
6238 DAG.getNode(ISD::FADD, dl, VT,
6239 N1, DAG.getConstantFP(-1.0, VT)));
6246 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6247 SDValue N0 = N->getOperand(0);
6248 SDValue N1 = N->getOperand(1);
6249 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6250 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6251 EVT VT = N->getValueType(0);
6252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6255 if (VT.isVector()) {
6256 SDValue FoldedVOp = SimplifyVBinOp(N);
6257 if (FoldedVOp.getNode()) return FoldedVOp;
6260 // fold (fdiv c1, c2) -> c1/c2
6262 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
6264 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6265 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6266 // Compute the reciprocal 1.0 / c2.
6267 APFloat N1APF = N1CFP->getValueAPF();
6268 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6269 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6270 // Only do the transform if the reciprocal is a legal fp immediate that
6271 // isn't too nasty (eg NaN, denormal, ...).
6272 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6273 (!LegalOperations ||
6274 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6275 // backend)... we should handle this gracefully after Legalize.
6276 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6277 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6278 TLI.isFPImmLegal(Recip, VT)))
6279 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
6280 DAG.getConstantFP(Recip, VT));
6283 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6284 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6285 &DAG.getTarget().Options)) {
6286 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6287 &DAG.getTarget().Options)) {
6288 // Both can be negated for free, check to see if at least one is cheaper
6290 if (LHSNeg == 2 || RHSNeg == 2)
6291 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
6292 GetNegatedExpression(N0, DAG, LegalOperations),
6293 GetNegatedExpression(N1, DAG, LegalOperations));
6300 SDValue DAGCombiner::visitFREM(SDNode *N) {
6301 SDValue N0 = N->getOperand(0);
6302 SDValue N1 = N->getOperand(1);
6303 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6304 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6305 EVT VT = N->getValueType(0);
6307 // fold (frem c1, c2) -> fmod(c1,c2)
6309 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
6314 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6315 SDValue N0 = N->getOperand(0);
6316 SDValue N1 = N->getOperand(1);
6317 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6318 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6319 EVT VT = N->getValueType(0);
6321 if (N0CFP && N1CFP) // Constant fold
6322 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
6325 const APFloat& V = N1CFP->getValueAPF();
6326 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6327 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6328 if (!V.isNegative()) {
6329 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6330 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6332 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6333 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6334 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
6338 // copysign(fabs(x), y) -> copysign(x, y)
6339 // copysign(fneg(x), y) -> copysign(x, y)
6340 // copysign(copysign(x,z), y) -> copysign(x, y)
6341 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6342 N0.getOpcode() == ISD::FCOPYSIGN)
6343 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6344 N0.getOperand(0), N1);
6346 // copysign(x, abs(y)) -> abs(x)
6347 if (N1.getOpcode() == ISD::FABS)
6348 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6350 // copysign(x, copysign(y,z)) -> copysign(x, z)
6351 if (N1.getOpcode() == ISD::FCOPYSIGN)
6352 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6353 N0, N1.getOperand(1));
6355 // copysign(x, fp_extend(y)) -> copysign(x, y)
6356 // copysign(x, fp_round(y)) -> copysign(x, y)
6357 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6358 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6359 N0, N1.getOperand(0));
6364 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6365 SDValue N0 = N->getOperand(0);
6366 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6367 EVT VT = N->getValueType(0);
6368 EVT OpVT = N0.getValueType();
6370 // fold (sint_to_fp c1) -> c1fp
6372 // ...but only if the target supports immediate floating-point values
6373 (!LegalOperations ||
6374 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6375 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6377 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6378 // but UINT_TO_FP is legal on this target, try to convert.
6379 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6380 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6381 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6382 if (DAG.SignBitIsZero(N0))
6383 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6386 // The next optimizations are desireable only if SELECT_CC can be lowered.
6387 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6388 // having to say they don't support SELECT_CC on every type the DAG knows
6389 // about, since there is no way to mark an opcode illegal at all value types
6390 // (See also visitSELECT)
6391 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6392 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6393 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6395 (!LegalOperations ||
6396 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6398 { N0.getOperand(0), N0.getOperand(1),
6399 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6401 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6404 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6405 // (select_cc x, y, 1.0, 0.0,, cc)
6406 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6407 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6408 (!LegalOperations ||
6409 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6411 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6412 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6413 N0.getOperand(0).getOperand(2) };
6414 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6421 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6422 SDValue N0 = N->getOperand(0);
6423 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6424 EVT VT = N->getValueType(0);
6425 EVT OpVT = N0.getValueType();
6427 // fold (uint_to_fp c1) -> c1fp
6429 // ...but only if the target supports immediate floating-point values
6430 (!LegalOperations ||
6431 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6432 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6434 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6435 // but SINT_TO_FP is legal on this target, try to convert.
6436 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6437 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6438 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6439 if (DAG.SignBitIsZero(N0))
6440 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6443 // The next optimizations are desireable only if SELECT_CC can be lowered.
6444 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6445 // having to say they don't support SELECT_CC on every type the DAG knows
6446 // about, since there is no way to mark an opcode illegal at all value types
6447 // (See also visitSELECT)
6448 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6449 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6451 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6452 (!LegalOperations ||
6453 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6455 { N0.getOperand(0), N0.getOperand(1),
6456 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6458 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6465 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6466 SDValue N0 = N->getOperand(0);
6467 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6468 EVT VT = N->getValueType(0);
6470 // fold (fp_to_sint c1fp) -> c1
6472 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6477 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6478 SDValue N0 = N->getOperand(0);
6479 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6480 EVT VT = N->getValueType(0);
6482 // fold (fp_to_uint c1fp) -> c1
6484 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6489 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6490 SDValue N0 = N->getOperand(0);
6491 SDValue N1 = N->getOperand(1);
6492 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6493 EVT VT = N->getValueType(0);
6495 // fold (fp_round c1fp) -> c1fp
6497 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6499 // fold (fp_round (fp_extend x)) -> x
6500 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6501 return N0.getOperand(0);
6503 // fold (fp_round (fp_round x)) -> (fp_round x)
6504 if (N0.getOpcode() == ISD::FP_ROUND) {
6505 // This is a value preserving truncation if both round's are.
6506 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6507 N0.getNode()->getConstantOperandVal(1) == 1;
6508 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6509 DAG.getIntPtrConstant(IsTrunc));
6512 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6513 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6514 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6515 N0.getOperand(0), N1);
6516 AddToWorkList(Tmp.getNode());
6517 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6518 Tmp, N0.getOperand(1));
6524 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6525 SDValue N0 = N->getOperand(0);
6526 EVT VT = N->getValueType(0);
6527 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6528 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6530 // fold (fp_round_inreg c1fp) -> c1fp
6531 if (N0CFP && isTypeLegal(EVT)) {
6532 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6533 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6539 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6540 SDValue N0 = N->getOperand(0);
6541 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6542 EVT VT = N->getValueType(0);
6544 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6545 if (N->hasOneUse() &&
6546 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6549 // fold (fp_extend c1fp) -> c1fp
6551 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6553 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6555 if (N0.getOpcode() == ISD::FP_ROUND
6556 && N0.getNode()->getConstantOperandVal(1) == 1) {
6557 SDValue In = N0.getOperand(0);
6558 if (In.getValueType() == VT) return In;
6559 if (VT.bitsLT(In.getValueType()))
6560 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6561 In, N0.getOperand(1));
6562 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6565 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6566 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6567 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6568 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6569 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6570 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6572 LN0->getBasePtr(), LN0->getPointerInfo(),
6574 LN0->isVolatile(), LN0->isNonTemporal(),
6575 LN0->getAlignment());
6576 CombineTo(N, ExtLoad);
6577 CombineTo(N0.getNode(),
6578 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6579 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6580 ExtLoad.getValue(1));
6581 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6587 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6588 SDValue N0 = N->getOperand(0);
6589 EVT VT = N->getValueType(0);
6591 if (VT.isVector()) {
6592 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6593 if (FoldedVOp.getNode()) return FoldedVOp;
6596 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6597 &DAG.getTarget().Options))
6598 return GetNegatedExpression(N0, DAG, LegalOperations);
6600 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6601 // constant pool values.
6602 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6604 N0.getNode()->hasOneUse() &&
6605 N0.getOperand(0).getValueType().isInteger()) {
6606 SDValue Int = N0.getOperand(0);
6607 EVT IntVT = Int.getValueType();
6608 if (IntVT.isInteger() && !IntVT.isVector()) {
6609 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6610 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6611 AddToWorkList(Int.getNode());
6612 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6617 // (fneg (fmul c, x)) -> (fmul -c, x)
6618 if (N0.getOpcode() == ISD::FMUL) {
6619 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6621 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6623 DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6631 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6632 SDValue N0 = N->getOperand(0);
6633 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6634 EVT VT = N->getValueType(0);
6636 // fold (fceil c1) -> fceil(c1)
6638 return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
6643 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6644 SDValue N0 = N->getOperand(0);
6645 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6646 EVT VT = N->getValueType(0);
6648 // fold (ftrunc c1) -> ftrunc(c1)
6650 return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
6655 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6656 SDValue N0 = N->getOperand(0);
6657 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6658 EVT VT = N->getValueType(0);
6660 // fold (ffloor c1) -> ffloor(c1)
6662 return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
6667 SDValue DAGCombiner::visitFABS(SDNode *N) {
6668 SDValue N0 = N->getOperand(0);
6669 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6670 EVT VT = N->getValueType(0);
6672 if (VT.isVector()) {
6673 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6674 if (FoldedVOp.getNode()) return FoldedVOp;
6677 // fold (fabs c1) -> fabs(c1)
6679 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6680 // fold (fabs (fabs x)) -> (fabs x)
6681 if (N0.getOpcode() == ISD::FABS)
6682 return N->getOperand(0);
6683 // fold (fabs (fneg x)) -> (fabs x)
6684 // fold (fabs (fcopysign x, y)) -> (fabs x)
6685 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6686 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6688 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6689 // constant pool values.
6690 if (!TLI.isFAbsFree(VT) &&
6691 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6692 N0.getOperand(0).getValueType().isInteger() &&
6693 !N0.getOperand(0).getValueType().isVector()) {
6694 SDValue Int = N0.getOperand(0);
6695 EVT IntVT = Int.getValueType();
6696 if (IntVT.isInteger() && !IntVT.isVector()) {
6697 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6698 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6699 AddToWorkList(Int.getNode());
6700 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6701 N->getValueType(0), Int);
6708 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6709 SDValue Chain = N->getOperand(0);
6710 SDValue N1 = N->getOperand(1);
6711 SDValue N2 = N->getOperand(2);
6713 // If N is a constant we could fold this into a fallthrough or unconditional
6714 // branch. However that doesn't happen very often in normal code, because
6715 // Instcombine/SimplifyCFG should have handled the available opportunities.
6716 // If we did this folding here, it would be necessary to update the
6717 // MachineBasicBlock CFG, which is awkward.
6719 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6721 if (N1.getOpcode() == ISD::SETCC &&
6722 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6723 N1.getOperand(0).getValueType())) {
6724 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6725 Chain, N1.getOperand(2),
6726 N1.getOperand(0), N1.getOperand(1), N2);
6729 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6730 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6731 (N1.getOperand(0).hasOneUse() &&
6732 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6734 if (N1.getOpcode() == ISD::TRUNCATE) {
6735 // Look pass the truncate.
6736 Trunc = N1.getNode();
6737 N1 = N1.getOperand(0);
6740 // Match this pattern so that we can generate simpler code:
6743 // %b = and i32 %a, 2
6744 // %c = srl i32 %b, 1
6745 // brcond i32 %c ...
6750 // %b = and i32 %a, 2
6751 // %c = setcc eq %b, 0
6754 // This applies only when the AND constant value has one bit set and the
6755 // SRL constant is equal to the log2 of the AND constant. The back-end is
6756 // smart enough to convert the result into a TEST/JMP sequence.
6757 SDValue Op0 = N1.getOperand(0);
6758 SDValue Op1 = N1.getOperand(1);
6760 if (Op0.getOpcode() == ISD::AND &&
6761 Op1.getOpcode() == ISD::Constant) {
6762 SDValue AndOp1 = Op0.getOperand(1);
6764 if (AndOp1.getOpcode() == ISD::Constant) {
6765 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6767 if (AndConst.isPowerOf2() &&
6768 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6770 DAG.getSetCC(N->getDebugLoc(),
6771 TLI.getSetCCResultType(Op0.getValueType()),
6772 Op0, DAG.getConstant(0, Op0.getValueType()),
6775 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6776 MVT::Other, Chain, SetCC, N2);
6777 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6778 // will convert it back to (X & C1) >> C2.
6779 CombineTo(N, NewBRCond, false);
6780 // Truncate is dead.
6782 removeFromWorkList(Trunc);
6783 DAG.DeleteNode(Trunc);
6785 // Replace the uses of SRL with SETCC
6786 WorkListRemover DeadNodes(*this);
6787 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6788 removeFromWorkList(N1.getNode());
6789 DAG.DeleteNode(N1.getNode());
6790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6796 // Restore N1 if the above transformation doesn't match.
6797 N1 = N->getOperand(1);
6800 // Transform br(xor(x, y)) -> br(x != y)
6801 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6802 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6803 SDNode *TheXor = N1.getNode();
6804 SDValue Op0 = TheXor->getOperand(0);
6805 SDValue Op1 = TheXor->getOperand(1);
6806 if (Op0.getOpcode() == Op1.getOpcode()) {
6807 // Avoid missing important xor optimizations.
6808 SDValue Tmp = visitXOR(TheXor);
6809 if (Tmp.getNode()) {
6810 if (Tmp.getNode() != TheXor) {
6811 DEBUG(dbgs() << "\nReplacing.8 ";
6813 dbgs() << "\nWith: ";
6814 Tmp.getNode()->dump(&DAG);
6816 WorkListRemover DeadNodes(*this);
6817 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6818 removeFromWorkList(TheXor);
6819 DAG.DeleteNode(TheXor);
6820 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6821 MVT::Other, Chain, Tmp, N2);
6824 // visitXOR has changed XOR's operands or replaced the XOR completely,
6826 return SDValue(N, 0);
6830 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6832 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6833 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6834 Op0.getOpcode() == ISD::XOR) {
6835 TheXor = Op0.getNode();
6839 EVT SetCCVT = N1.getValueType();
6841 SetCCVT = TLI.getSetCCResultType(SetCCVT);
6842 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6845 Equal ? ISD::SETEQ : ISD::SETNE);
6846 // Replace the uses of XOR with SETCC
6847 WorkListRemover DeadNodes(*this);
6848 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6849 removeFromWorkList(N1.getNode());
6850 DAG.DeleteNode(N1.getNode());
6851 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6852 MVT::Other, Chain, SetCC, N2);
6859 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6861 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6862 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6863 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6865 // If N is a constant we could fold this into a fallthrough or unconditional
6866 // branch. However that doesn't happen very often in normal code, because
6867 // Instcombine/SimplifyCFG should have handled the available opportunities.
6868 // If we did this folding here, it would be necessary to update the
6869 // MachineBasicBlock CFG, which is awkward.
6871 // Use SimplifySetCC to simplify SETCC's.
6872 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6873 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6875 if (Simp.getNode()) AddToWorkList(Simp.getNode());
6877 // fold to a simpler setcc
6878 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6879 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6880 N->getOperand(0), Simp.getOperand(2),
6881 Simp.getOperand(0), Simp.getOperand(1),
6887 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6888 /// uses N as its base pointer and that N may be folded in the load / store
6889 /// addressing mode.
6890 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6892 const TargetLowering &TLI) {
6894 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
6895 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6897 VT = Use->getValueType(0);
6898 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
6899 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6901 VT = ST->getValue().getValueType();
6905 TargetLowering::AddrMode AM;
6906 if (N->getOpcode() == ISD::ADD) {
6907 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6910 AM.BaseOffs = Offset->getSExtValue();
6914 } else if (N->getOpcode() == ISD::SUB) {
6915 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6918 AM.BaseOffs = -Offset->getSExtValue();
6925 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6928 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6929 /// pre-indexed load / store when the base pointer is an add or subtract
6930 /// and it has other uses besides the load / store. After the
6931 /// transformation, the new indexed load / store has effectively folded
6932 /// the add / subtract in and all of its other uses are redirected to the
6933 /// new load / store.
6934 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6935 if (Level < AfterLegalizeDAG)
6941 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6942 if (LD->isIndexed())
6944 VT = LD->getMemoryVT();
6945 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6946 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6948 Ptr = LD->getBasePtr();
6949 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6950 if (ST->isIndexed())
6952 VT = ST->getMemoryVT();
6953 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6954 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6956 Ptr = ST->getBasePtr();
6962 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6963 // out. There is no reason to make this a preinc/predec.
6964 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6965 Ptr.getNode()->hasOneUse())
6968 // Ask the target to do addressing mode selection.
6971 ISD::MemIndexedMode AM = ISD::UNINDEXED;
6972 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6975 // Backends without true r+i pre-indexed forms may need to pass a
6976 // constant base with a variable offset so that constant coercion
6977 // will work with the patterns in canonical form.
6978 bool Swapped = false;
6979 if (isa<ConstantSDNode>(BasePtr)) {
6980 std::swap(BasePtr, Offset);
6984 // Don't create a indexed load / store with zero offset.
6985 if (isa<ConstantSDNode>(Offset) &&
6986 cast<ConstantSDNode>(Offset)->isNullValue())
6989 // Try turning it into a pre-indexed load / store except when:
6990 // 1) The new base ptr is a frame index.
6991 // 2) If N is a store and the new base ptr is either the same as or is a
6992 // predecessor of the value being stored.
6993 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6994 // that would create a cycle.
6995 // 4) All uses are load / store ops that use it as old base ptr.
6997 // Check #1. Preinc'ing a frame index would require copying the stack pointer
6998 // (plus the implicit offset) to a register to preinc anyway.
6999 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7004 SDValue Val = cast<StoreSDNode>(N)->getValue();
7005 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7009 // If the offset is a constant, there may be other adds of constants that
7010 // can be folded with this one. We should do this to avoid having to keep
7011 // a copy of the original base pointer.
7012 SmallVector<SDNode *, 16> OtherUses;
7013 if (isa<ConstantSDNode>(Offset))
7014 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7015 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7017 if (Use == Ptr.getNode())
7020 if (Use->isPredecessorOf(N))
7023 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7028 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7029 if (Op1.getNode() == BasePtr.getNode())
7030 std::swap(Op0, Op1);
7031 assert(Op0.getNode() == BasePtr.getNode() &&
7032 "Use of ADD/SUB but not an operand");
7034 if (!isa<ConstantSDNode>(Op1)) {
7039 // FIXME: In some cases, we can be smarter about this.
7040 if (Op1.getValueType() != Offset.getValueType()) {
7045 OtherUses.push_back(Use);
7049 std::swap(BasePtr, Offset);
7051 // Now check for #3 and #4.
7052 bool RealUse = false;
7054 // Caches for hasPredecessorHelper
7055 SmallPtrSet<const SDNode *, 32> Visited;
7056 SmallVector<const SDNode *, 16> Worklist;
7058 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7059 E = Ptr.getNode()->use_end(); I != E; ++I) {
7063 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7066 // If Ptr may be folded in addressing mode of other use, then it's
7067 // not profitable to do this transformation.
7068 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7077 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7078 BasePtr, Offset, AM);
7080 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7081 BasePtr, Offset, AM);
7084 DEBUG(dbgs() << "\nReplacing.4 ";
7086 dbgs() << "\nWith: ";
7087 Result.getNode()->dump(&DAG);
7089 WorkListRemover DeadNodes(*this);
7091 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7092 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7094 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7097 // Finally, since the node is now dead, remove it from the graph.
7101 std::swap(BasePtr, Offset);
7103 // Replace other uses of BasePtr that can be updated to use Ptr
7104 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7105 unsigned OffsetIdx = 1;
7106 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7108 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7109 BasePtr.getNode() && "Expected BasePtr operand");
7112 cast<ConstantSDNode>(Offset)->getAPIntValue();
7113 if (AM == ISD::PRE_DEC)
7116 ConstantSDNode *CN =
7117 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7118 APInt CNV = CN->getAPIntValue();
7119 if (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1)
7124 SDValue NewOp1 = Result.getValue(isLoad ? 1 : 0);
7125 SDValue NewOp2 = DAG.getConstant(CNV, CN->getValueType(0));
7127 std::swap(NewOp1, NewOp2);
7129 SDValue NewUse = DAG.getNode(OtherUses[i]->getOpcode(),
7130 OtherUses[i]->getDebugLoc(),
7131 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7132 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7133 removeFromWorkList(OtherUses[i]);
7134 DAG.DeleteNode(OtherUses[i]);
7137 // Replace the uses of Ptr with uses of the updated base value.
7138 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7139 removeFromWorkList(Ptr.getNode());
7140 DAG.DeleteNode(Ptr.getNode());
7145 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7146 /// add / sub of the base pointer node into a post-indexed load / store.
7147 /// The transformation folded the add / subtract into the new indexed
7148 /// load / store effectively and all of its uses are redirected to the
7149 /// new load / store.
7150 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7151 if (Level < AfterLegalizeDAG)
7157 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7158 if (LD->isIndexed())
7160 VT = LD->getMemoryVT();
7161 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7162 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7164 Ptr = LD->getBasePtr();
7165 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7166 if (ST->isIndexed())
7168 VT = ST->getMemoryVT();
7169 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7170 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7172 Ptr = ST->getBasePtr();
7178 if (Ptr.getNode()->hasOneUse())
7181 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7182 E = Ptr.getNode()->use_end(); I != E; ++I) {
7185 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7190 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7191 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7192 // Don't create a indexed load / store with zero offset.
7193 if (isa<ConstantSDNode>(Offset) &&
7194 cast<ConstantSDNode>(Offset)->isNullValue())
7197 // Try turning it into a post-indexed load / store except when
7198 // 1) All uses are load / store ops that use it as base ptr (and
7199 // it may be folded as addressing mmode).
7200 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7201 // nor a successor of N. Otherwise, if Op is folded that would
7204 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7208 bool TryNext = false;
7209 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7210 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7212 if (Use == Ptr.getNode())
7215 // If all the uses are load / store addresses, then don't do the
7217 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7218 bool RealUse = false;
7219 for (SDNode::use_iterator III = Use->use_begin(),
7220 EEE = Use->use_end(); III != EEE; ++III) {
7221 SDNode *UseUse = *III;
7222 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7237 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7238 SDValue Result = isLoad
7239 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7240 BasePtr, Offset, AM)
7241 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7242 BasePtr, Offset, AM);
7245 DEBUG(dbgs() << "\nReplacing.5 ";
7247 dbgs() << "\nWith: ";
7248 Result.getNode()->dump(&DAG);
7250 WorkListRemover DeadNodes(*this);
7252 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7253 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7255 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7258 // Finally, since the node is now dead, remove it from the graph.
7261 // Replace the uses of Use with uses of the updated base value.
7262 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7263 Result.getValue(isLoad ? 1 : 0));
7264 removeFromWorkList(Op);
7274 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7275 LoadSDNode *LD = cast<LoadSDNode>(N);
7276 SDValue Chain = LD->getChain();
7277 SDValue Ptr = LD->getBasePtr();
7279 // If load is not volatile and there are no uses of the loaded value (and
7280 // the updated indexed value in case of indexed loads), change uses of the
7281 // chain value into uses of the chain input (i.e. delete the dead load).
7282 if (!LD->isVolatile()) {
7283 if (N->getValueType(1) == MVT::Other) {
7285 if (!N->hasAnyUseOfValue(0)) {
7286 // It's not safe to use the two value CombineTo variant here. e.g.
7287 // v1, chain2 = load chain1, loc
7288 // v2, chain3 = load chain2, loc
7290 // Now we replace use of chain2 with chain1. This makes the second load
7291 // isomorphic to the one we are deleting, and thus makes this load live.
7292 DEBUG(dbgs() << "\nReplacing.6 ";
7294 dbgs() << "\nWith chain: ";
7295 Chain.getNode()->dump(&DAG);
7297 WorkListRemover DeadNodes(*this);
7298 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7300 if (N->use_empty()) {
7301 removeFromWorkList(N);
7305 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7309 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7310 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7311 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7312 DEBUG(dbgs() << "\nReplacing.7 ";
7314 dbgs() << "\nWith: ";
7315 Undef.getNode()->dump(&DAG);
7316 dbgs() << " and 2 other values\n");
7317 WorkListRemover DeadNodes(*this);
7318 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7319 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7320 DAG.getUNDEF(N->getValueType(1)));
7321 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7322 removeFromWorkList(N);
7324 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7329 // If this load is directly stored, replace the load value with the stored
7331 // TODO: Handle store large -> read small portion.
7332 // TODO: Handle TRUNCSTORE/LOADEXT
7333 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7334 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7335 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7336 if (PrevST->getBasePtr() == Ptr &&
7337 PrevST->getValue().getValueType() == N->getValueType(0))
7338 return CombineTo(N, Chain.getOperand(1), Chain);
7342 // Try to infer better alignment information than the load already has.
7343 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7344 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7345 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7347 DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
7348 LD->getValueType(0),
7349 Chain, Ptr, LD->getPointerInfo(),
7351 LD->isVolatile(), LD->isNonTemporal(), Align);
7352 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7358 // Walk up chain skipping non-aliasing memory nodes.
7359 SDValue BetterChain = FindBetterChain(N, Chain);
7361 // If there is a better chain.
7362 if (Chain != BetterChain) {
7365 // Replace the chain to void dependency.
7366 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7367 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
7368 BetterChain, Ptr, LD->getPointerInfo(),
7369 LD->isVolatile(), LD->isNonTemporal(),
7370 LD->isInvariant(), LD->getAlignment());
7372 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
7373 LD->getValueType(0),
7374 BetterChain, Ptr, LD->getPointerInfo(),
7377 LD->isNonTemporal(),
7378 LD->getAlignment());
7381 // Create token factor to keep old chain connected.
7382 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7383 MVT::Other, Chain, ReplLoad.getValue(1));
7385 // Make sure the new and old chains are cleaned up.
7386 AddToWorkList(Token.getNode());
7388 // Replace uses with load result and token factor. Don't add users
7390 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7394 // Try transforming N to an indexed load.
7395 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7396 return SDValue(N, 0);
7401 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7402 /// load is having specific bytes cleared out. If so, return the byte size
7403 /// being masked out and the shift amount.
7404 static std::pair<unsigned, unsigned>
7405 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7406 std::pair<unsigned, unsigned> Result(0, 0);
7408 // Check for the structure we're looking for.
7409 if (V->getOpcode() != ISD::AND ||
7410 !isa<ConstantSDNode>(V->getOperand(1)) ||
7411 !ISD::isNormalLoad(V->getOperand(0).getNode()))
7414 // Check the chain and pointer.
7415 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7416 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
7418 // The store should be chained directly to the load or be an operand of a
7420 if (LD == Chain.getNode())
7422 else if (Chain->getOpcode() != ISD::TokenFactor)
7423 return Result; // Fail.
7426 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7427 if (Chain->getOperand(i).getNode() == LD) {
7431 if (!isOk) return Result;
7434 // This only handles simple types.
7435 if (V.getValueType() != MVT::i16 &&
7436 V.getValueType() != MVT::i32 &&
7437 V.getValueType() != MVT::i64)
7440 // Check the constant mask. Invert it so that the bits being masked out are
7441 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
7442 // follow the sign bit for uniformity.
7443 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7444 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
7445 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
7446 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
7447 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
7448 if (NotMaskLZ == 64) return Result; // All zero mask.
7450 // See if we have a continuous run of bits. If so, we have 0*1+0*
7451 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7454 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7455 if (V.getValueType() != MVT::i64 && NotMaskLZ)
7456 NotMaskLZ -= 64-V.getValueSizeInBits();
7458 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7459 switch (MaskedBytes) {
7463 default: return Result; // All one mask, or 5-byte mask.
7466 // Verify that the first bit starts at a multiple of mask so that the access
7467 // is aligned the same as the access width.
7468 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7470 Result.first = MaskedBytes;
7471 Result.second = NotMaskTZ/8;
7476 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7477 /// provides a value as specified by MaskInfo. If so, replace the specified
7478 /// store with a narrower store of truncated IVal.
7480 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7481 SDValue IVal, StoreSDNode *St,
7483 unsigned NumBytes = MaskInfo.first;
7484 unsigned ByteShift = MaskInfo.second;
7485 SelectionDAG &DAG = DC->getDAG();
7487 // Check to see if IVal is all zeros in the part being masked in by the 'or'
7488 // that uses this. If not, this is not a replacement.
7489 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7490 ByteShift*8, (ByteShift+NumBytes)*8);
7491 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7493 // Check that it is legal on the target to do this. It is legal if the new
7494 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7496 MVT VT = MVT::getIntegerVT(NumBytes*8);
7497 if (!DC->isTypeLegal(VT))
7500 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
7501 // shifted by ByteShift and truncated down to NumBytes.
7503 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
7504 DAG.getConstant(ByteShift*8,
7505 DC->getShiftAmountTy(IVal.getValueType())));
7507 // Figure out the offset for the store and the alignment of the access.
7509 unsigned NewAlign = St->getAlignment();
7511 if (DAG.getTargetLoweringInfo().isLittleEndian())
7512 StOffset = ByteShift;
7514 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7516 SDValue Ptr = St->getBasePtr();
7518 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
7519 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7520 NewAlign = MinAlign(NewAlign, StOffset);
7523 // Truncate down to the new size.
7524 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7527 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7528 St->getPointerInfo().getWithOffset(StOffset),
7529 false, false, NewAlign).getNode();
7533 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7534 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7535 /// of the loaded bits, try narrowing the load and store if it would end up
7536 /// being a win for performance or code size.
7537 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7538 StoreSDNode *ST = cast<StoreSDNode>(N);
7539 if (ST->isVolatile())
7542 SDValue Chain = ST->getChain();
7543 SDValue Value = ST->getValue();
7544 SDValue Ptr = ST->getBasePtr();
7545 EVT VT = Value.getValueType();
7547 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7550 unsigned Opc = Value.getOpcode();
7552 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7553 // is a byte mask indicating a consecutive number of bytes, check to see if
7554 // Y is known to provide just those bytes. If so, we try to replace the
7555 // load + replace + store sequence with a single (narrower) store, which makes
7557 if (Opc == ISD::OR) {
7558 std::pair<unsigned, unsigned> MaskedLoad;
7559 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7560 if (MaskedLoad.first)
7561 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7562 Value.getOperand(1), ST,this))
7563 return SDValue(NewST, 0);
7565 // Or is commutative, so try swapping X and Y.
7566 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7567 if (MaskedLoad.first)
7568 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7569 Value.getOperand(0), ST,this))
7570 return SDValue(NewST, 0);
7573 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7574 Value.getOperand(1).getOpcode() != ISD::Constant)
7577 SDValue N0 = Value.getOperand(0);
7578 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7579 Chain == SDValue(N0.getNode(), 1)) {
7580 LoadSDNode *LD = cast<LoadSDNode>(N0);
7581 if (LD->getBasePtr() != Ptr ||
7582 LD->getPointerInfo().getAddrSpace() !=
7583 ST->getPointerInfo().getAddrSpace())
7586 // Find the type to narrow it the load / op / store to.
7587 SDValue N1 = Value.getOperand(1);
7588 unsigned BitWidth = N1.getValueSizeInBits();
7589 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7590 if (Opc == ISD::AND)
7591 Imm ^= APInt::getAllOnesValue(BitWidth);
7592 if (Imm == 0 || Imm.isAllOnesValue())
7594 unsigned ShAmt = Imm.countTrailingZeros();
7595 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7596 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7597 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7598 while (NewBW < BitWidth &&
7599 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7600 TLI.isNarrowingProfitable(VT, NewVT))) {
7601 NewBW = NextPowerOf2(NewBW);
7602 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7604 if (NewBW >= BitWidth)
7607 // If the lsb changed does not start at the type bitwidth boundary,
7608 // start at the previous one.
7610 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7611 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7612 std::min(BitWidth, ShAmt + NewBW));
7613 if ((Imm & Mask) == Imm) {
7614 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7615 if (Opc == ISD::AND)
7616 NewImm ^= APInt::getAllOnesValue(NewBW);
7617 uint64_t PtrOff = ShAmt / 8;
7618 // For big endian targets, we need to adjust the offset to the pointer to
7619 // load the correct bytes.
7620 if (TLI.isBigEndian())
7621 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7623 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7624 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7625 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7628 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7629 Ptr.getValueType(), Ptr,
7630 DAG.getConstant(PtrOff, Ptr.getValueType()));
7631 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7632 LD->getChain(), NewPtr,
7633 LD->getPointerInfo().getWithOffset(PtrOff),
7634 LD->isVolatile(), LD->isNonTemporal(),
7635 LD->isInvariant(), NewAlign);
7636 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7637 DAG.getConstant(NewImm, NewVT));
7638 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7640 ST->getPointerInfo().getWithOffset(PtrOff),
7641 false, false, NewAlign);
7643 AddToWorkList(NewPtr.getNode());
7644 AddToWorkList(NewLD.getNode());
7645 AddToWorkList(NewVal.getNode());
7646 WorkListRemover DeadNodes(*this);
7647 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7656 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7657 /// if the load value isn't used by any other operations, then consider
7658 /// transforming the pair to integer load / store operations if the target
7659 /// deems the transformation profitable.
7660 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7661 StoreSDNode *ST = cast<StoreSDNode>(N);
7662 SDValue Chain = ST->getChain();
7663 SDValue Value = ST->getValue();
7664 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7665 Value.hasOneUse() &&
7666 Chain == SDValue(Value.getNode(), 1)) {
7667 LoadSDNode *LD = cast<LoadSDNode>(Value);
7668 EVT VT = LD->getMemoryVT();
7669 if (!VT.isFloatingPoint() ||
7670 VT != ST->getMemoryVT() ||
7671 LD->isNonTemporal() ||
7672 ST->isNonTemporal() ||
7673 LD->getPointerInfo().getAddrSpace() != 0 ||
7674 ST->getPointerInfo().getAddrSpace() != 0)
7677 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7678 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7679 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7680 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7681 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7684 unsigned LDAlign = LD->getAlignment();
7685 unsigned STAlign = ST->getAlignment();
7686 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7687 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7688 if (LDAlign < ABIAlign || STAlign < ABIAlign)
7691 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7692 LD->getChain(), LD->getBasePtr(),
7693 LD->getPointerInfo(),
7694 false, false, false, LDAlign);
7696 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7697 NewLD, ST->getBasePtr(),
7698 ST->getPointerInfo(),
7699 false, false, STAlign);
7701 AddToWorkList(NewLD.getNode());
7702 AddToWorkList(NewST.getNode());
7703 WorkListRemover DeadNodes(*this);
7704 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7712 /// Helper struct to parse and store a memory address as base + index + offset.
7713 /// We ignore sign extensions when it is safe to do so.
7714 /// The following two expressions are not equivalent. To differentiate we need
7715 /// to store whether there was a sign extension involved in the index
7717 /// (load (i64 add (i64 copyfromreg %c)
7718 /// (i64 signextend (add (i8 load %index)
7722 /// (load (i64 add (i64 copyfromreg %c)
7723 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
7725 struct BaseIndexOffset {
7729 bool IsIndexSignExt;
7731 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7733 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7734 bool IsIndexSignExt) :
7735 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7737 bool equalBaseIndex(const BaseIndexOffset &Other) {
7738 return Other.Base == Base && Other.Index == Index &&
7739 Other.IsIndexSignExt == IsIndexSignExt;
7742 /// Parses tree in Ptr for base, index, offset addresses.
7743 static BaseIndexOffset match(SDValue Ptr) {
7744 bool IsIndexSignExt = false;
7746 // Just Base or possibly anything else.
7747 if (Ptr->getOpcode() != ISD::ADD)
7748 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7751 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7752 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7753 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7757 // Look at Base + Index + Offset cases.
7758 SDValue Base = Ptr->getOperand(0);
7759 SDValue IndexOffset = Ptr->getOperand(1);
7761 // Skip signextends.
7762 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7763 IndexOffset = IndexOffset->getOperand(0);
7764 IsIndexSignExt = true;
7767 // Either the case of Base + Index (no offset) or something else.
7768 if (IndexOffset->getOpcode() != ISD::ADD)
7769 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7771 // Now we have the case of Base + Index + offset.
7772 SDValue Index = IndexOffset->getOperand(0);
7773 SDValue Offset = IndexOffset->getOperand(1);
7775 if (!isa<ConstantSDNode>(Offset))
7776 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7778 // Ignore signextends.
7779 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7780 Index = Index->getOperand(0);
7781 IsIndexSignExt = true;
7782 } else IsIndexSignExt = false;
7784 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7785 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7789 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7790 /// is located in a sequence of memory operations connected by a chain.
7792 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7793 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7794 // Ptr to the mem node.
7795 LSBaseSDNode *MemNode;
7796 // Offset from the base ptr.
7797 int64_t OffsetFromBase;
7798 // What is the sequence number of this mem node.
7799 // Lowest mem operand in the DAG starts at zero.
7800 unsigned SequenceNum;
7803 /// Sorts store nodes in a link according to their offset from a shared
7805 struct ConsecutiveMemoryChainSorter {
7806 bool operator()(MemOpLink LHS, MemOpLink RHS) {
7807 return LHS.OffsetFromBase < RHS.OffsetFromBase;
7811 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7812 EVT MemVT = St->getMemoryVT();
7813 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7814 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7815 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7817 // Don't merge vectors into wider inputs.
7818 if (MemVT.isVector() || !MemVT.isSimple())
7821 // Perform an early exit check. Do not bother looking at stored values that
7822 // are not constants or loads.
7823 SDValue StoredVal = St->getValue();
7824 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7825 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7829 // Only look at ends of store sequences.
7830 SDValue Chain = SDValue(St, 1);
7831 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7834 // This holds the base pointer, index, and the offset in bytes from the base
7836 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7838 // We must have a base and an offset.
7839 if (!BasePtr.Base.getNode())
7842 // Do not handle stores to undef base pointers.
7843 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7846 // Save the LoadSDNodes that we find in the chain.
7847 // We need to make sure that these nodes do not interfere with
7848 // any of the store nodes.
7849 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7851 // Save the StoreSDNodes that we find in the chain.
7852 SmallVector<MemOpLink, 8> StoreNodes;
7854 // Walk up the chain and look for nodes with offsets from the same
7855 // base pointer. Stop when reaching an instruction with a different kind
7856 // or instruction which has a different base pointer.
7858 StoreSDNode *Index = St;
7860 // If the chain has more than one use, then we can't reorder the mem ops.
7861 if (Index != St && !SDValue(Index, 1)->hasOneUse())
7864 // Find the base pointer and offset for this memory node.
7865 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
7867 // Check that the base pointer is the same as the original one.
7868 if (!Ptr.equalBaseIndex(BasePtr))
7871 // Check that the alignment is the same.
7872 if (Index->getAlignment() != St->getAlignment())
7875 // The memory operands must not be volatile.
7876 if (Index->isVolatile() || Index->isIndexed())
7880 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7881 if (St->isTruncatingStore())
7884 // The stored memory type must be the same.
7885 if (Index->getMemoryVT() != MemVT)
7888 // We do not allow unaligned stores because we want to prevent overriding
7890 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
7893 // We found a potential memory operand to merge.
7894 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
7896 // Find the next memory operand in the chain. If the next operand in the
7897 // chain is a store then move up and continue the scan with the next
7898 // memory operand. If the next operand is a load save it and use alias
7899 // information to check if it interferes with anything.
7900 SDNode *NextInChain = Index->getChain().getNode();
7902 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
7903 // We found a store node. Use it for the next iteration.
7906 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
7907 // Save the load node for later. Continue the scan.
7908 AliasLoadNodes.push_back(Ldn);
7909 NextInChain = Ldn->getChain().getNode();
7918 // Check if there is anything to merge.
7919 if (StoreNodes.size() < 2)
7922 // Sort the memory operands according to their distance from the base pointer.
7923 std::sort(StoreNodes.begin(), StoreNodes.end(),
7924 ConsecutiveMemoryChainSorter());
7926 // Scan the memory operations on the chain and find the first non-consecutive
7927 // store memory address.
7928 unsigned LastConsecutiveStore = 0;
7929 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
7930 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
7932 // Check that the addresses are consecutive starting from the second
7933 // element in the list of stores.
7935 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
7936 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7941 // Check if this store interferes with any of the loads that we found.
7942 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
7943 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
7947 // We found a load that alias with this store. Stop the sequence.
7951 // Mark this node as useful.
7952 LastConsecutiveStore = i;
7955 // The node with the lowest store address.
7956 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
7958 // Store the constants into memory as one consecutive store.
7960 unsigned LastLegalType = 0;
7961 unsigned LastLegalVectorType = 0;
7962 bool NonZero = false;
7963 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
7964 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
7965 SDValue StoredVal = St->getValue();
7967 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
7968 NonZero |= !C->isNullValue();
7969 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
7970 NonZero |= !C->getConstantFPValue()->isNullValue();
7976 // Find a legal type for the constant store.
7977 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
7978 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7979 if (TLI.isTypeLegal(StoreTy))
7980 LastLegalType = i+1;
7981 // Or check whether a truncstore is legal.
7982 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
7983 TargetLowering::TypePromoteInteger) {
7984 EVT LegalizedStoredValueTy =
7985 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
7986 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
7987 LastLegalType = i+1;
7990 // Find a legal type for the vector store.
7991 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
7992 if (TLI.isTypeLegal(Ty))
7993 LastLegalVectorType = i + 1;
7996 // We only use vectors if the constant is known to be zero and the
7997 // function is not marked with the noimplicitfloat attribute.
7998 if (NonZero || NoVectors)
7999 LastLegalVectorType = 0;
8001 // Check if we found a legal integer type to store.
8002 if (LastLegalType == 0 && LastLegalVectorType == 0)
8005 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8006 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8008 // Make sure we have something to merge.
8012 unsigned EarliestNodeUsed = 0;
8013 for (unsigned i=0; i < NumElem; ++i) {
8014 // Find a chain for the new wide-store operand. Notice that some
8015 // of the store nodes that we found may not be selected for inclusion
8016 // in the wide store. The chain we use needs to be the chain of the
8017 // earliest store node which is *used* and replaced by the wide store.
8018 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8019 EarliestNodeUsed = i;
8022 // The earliest Node in the DAG.
8023 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8024 DebugLoc DL = StoreNodes[0].MemNode->getDebugLoc();
8028 // Find a legal type for the vector store.
8029 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8030 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8031 StoredVal = DAG.getConstant(0, Ty);
8033 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8034 APInt StoreInt(StoreBW, 0);
8036 // Construct a single integer constant which is made of the smaller
8038 bool IsLE = TLI.isLittleEndian();
8039 for (unsigned i = 0; i < NumElem ; ++i) {
8040 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8041 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8042 SDValue Val = St->getValue();
8043 StoreInt<<=ElementSizeBytes*8;
8044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8045 StoreInt|=C->getAPIntValue().zext(StoreBW);
8046 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8047 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8049 assert(false && "Invalid constant element type");
8053 // Create the new Load and Store operations.
8054 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8055 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8058 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8059 FirstInChain->getBasePtr(),
8060 FirstInChain->getPointerInfo(),
8062 FirstInChain->getAlignment());
8064 // Replace the first store with the new store
8065 CombineTo(EarliestOp, NewStore);
8066 // Erase all other stores.
8067 for (unsigned i = 0; i < NumElem ; ++i) {
8068 if (StoreNodes[i].MemNode == EarliestOp)
8070 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8071 // ReplaceAllUsesWith will replace all uses that existed when it was
8072 // called, but graph optimizations may cause new ones to appear. For
8073 // example, the case in pr14333 looks like
8075 // St's chain -> St -> another store -> X
8077 // And the only difference from St to the other store is the chain.
8078 // When we change it's chain to be St's chain they become identical,
8079 // get CSEed and the net result is that X is now a use of St.
8080 // Since we know that St is redundant, just iterate.
8081 while (!St->use_empty())
8082 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8083 removeFromWorkList(St);
8090 // Below we handle the case of multiple consecutive stores that
8091 // come from multiple consecutive loads. We merge them into a single
8092 // wide load and a single wide store.
8094 // Look for load nodes which are used by the stored values.
8095 SmallVector<MemOpLink, 8> LoadNodes;
8097 // Find acceptable loads. Loads need to have the same chain (token factor),
8098 // must not be zext, volatile, indexed, and they must be consecutive.
8099 BaseIndexOffset LdBasePtr;
8100 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8101 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8102 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8105 // Loads must only have one use.
8106 if (!Ld->hasNUsesOfValue(1, 0))
8109 // Check that the alignment is the same as the stores.
8110 if (Ld->getAlignment() != St->getAlignment())
8113 // The memory operands must not be volatile.
8114 if (Ld->isVolatile() || Ld->isIndexed())
8117 // We do not accept ext loads.
8118 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8121 // The stored memory type must be the same.
8122 if (Ld->getMemoryVT() != MemVT)
8125 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8126 // If this is not the first ptr that we check.
8127 if (LdBasePtr.Base.getNode()) {
8128 // The base ptr must be the same.
8129 if (!LdPtr.equalBaseIndex(LdBasePtr))
8132 // Check that all other base pointers are the same as this one.
8136 // We found a potential memory operand to merge.
8137 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8140 if (LoadNodes.size() < 2)
8143 // Scan the memory operations on the chain and find the first non-consecutive
8144 // load memory address. These variables hold the index in the store node
8146 unsigned LastConsecutiveLoad = 0;
8147 // This variable refers to the size and not index in the array.
8148 unsigned LastLegalVectorType = 0;
8149 unsigned LastLegalIntegerType = 0;
8150 StartAddress = LoadNodes[0].OffsetFromBase;
8151 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8152 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8153 // All loads much share the same chain.
8154 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8157 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8158 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8160 LastConsecutiveLoad = i;
8162 // Find a legal type for the vector store.
8163 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8164 if (TLI.isTypeLegal(StoreTy))
8165 LastLegalVectorType = i + 1;
8167 // Find a legal type for the integer store.
8168 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8169 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8170 if (TLI.isTypeLegal(StoreTy))
8171 LastLegalIntegerType = i + 1;
8172 // Or check whether a truncstore and extload is legal.
8173 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8174 TargetLowering::TypePromoteInteger) {
8175 EVT LegalizedStoredValueTy =
8176 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8177 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8178 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8179 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8180 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8181 LastLegalIntegerType = i+1;
8185 // Only use vector types if the vector type is larger than the integer type.
8186 // If they are the same, use integers.
8187 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8188 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8190 // We add +1 here because the LastXXX variables refer to location while
8191 // the NumElem refers to array/index size.
8192 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8193 NumElem = std::min(LastLegalType, NumElem);
8198 // The earliest Node in the DAG.
8199 unsigned EarliestNodeUsed = 0;
8200 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8201 for (unsigned i=1; i<NumElem; ++i) {
8202 // Find a chain for the new wide-store operand. Notice that some
8203 // of the store nodes that we found may not be selected for inclusion
8204 // in the wide store. The chain we use needs to be the chain of the
8205 // earliest store node which is *used* and replaced by the wide store.
8206 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8207 EarliestNodeUsed = i;
8210 // Find if it is better to use vectors or integers to load and store
8214 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8216 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8217 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8220 DebugLoc LoadDL = LoadNodes[0].MemNode->getDebugLoc();
8221 DebugLoc StoreDL = StoreNodes[0].MemNode->getDebugLoc();
8223 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8224 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8225 FirstLoad->getChain(),
8226 FirstLoad->getBasePtr(),
8227 FirstLoad->getPointerInfo(),
8228 false, false, false,
8229 FirstLoad->getAlignment());
8231 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8232 FirstInChain->getBasePtr(),
8233 FirstInChain->getPointerInfo(), false, false,
8234 FirstInChain->getAlignment());
8236 // Replace one of the loads with the new load.
8237 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8238 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8239 SDValue(NewLoad.getNode(), 1));
8241 // Remove the rest of the load chains.
8242 for (unsigned i = 1; i < NumElem ; ++i) {
8243 // Replace all chain users of the old load nodes with the chain of the new
8245 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8246 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8249 // Replace the first store with the new store.
8250 CombineTo(EarliestOp, NewStore);
8251 // Erase all other stores.
8252 for (unsigned i = 0; i < NumElem ; ++i) {
8253 // Remove all Store nodes.
8254 if (StoreNodes[i].MemNode == EarliestOp)
8256 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8257 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8258 removeFromWorkList(St);
8265 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8266 StoreSDNode *ST = cast<StoreSDNode>(N);
8267 SDValue Chain = ST->getChain();
8268 SDValue Value = ST->getValue();
8269 SDValue Ptr = ST->getBasePtr();
8271 // If this is a store of a bit convert, store the input value if the
8272 // resultant store does not need a higher alignment than the original.
8273 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8274 ST->isUnindexed()) {
8275 unsigned OrigAlign = ST->getAlignment();
8276 EVT SVT = Value.getOperand(0).getValueType();
8277 unsigned Align = TLI.getDataLayout()->
8278 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8279 if (Align <= OrigAlign &&
8280 ((!LegalOperations && !ST->isVolatile()) ||
8281 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8282 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8283 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8284 ST->isNonTemporal(), OrigAlign);
8287 // Turn 'store undef, Ptr' -> nothing.
8288 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8291 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8292 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8293 // NOTE: If the original store is volatile, this transform must not increase
8294 // the number of stores. For example, on x86-32 an f64 can be stored in one
8295 // processor operation but an i64 (which is not legal) requires two. So the
8296 // transform should not be done in this case.
8297 if (Value.getOpcode() != ISD::TargetConstantFP) {
8299 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
8300 default: llvm_unreachable("Unknown FP type");
8301 case MVT::f16: // We don't do this for these yet.
8307 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8308 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8309 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8310 bitcastToAPInt().getZExtValue(), MVT::i32);
8311 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8312 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8313 ST->isNonTemporal(), ST->getAlignment());
8317 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8318 !ST->isVolatile()) ||
8319 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8320 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8321 getZExtValue(), MVT::i64);
8322 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8323 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8324 ST->isNonTemporal(), ST->getAlignment());
8327 if (!ST->isVolatile() &&
8328 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8329 // Many FP stores are not made apparent until after legalize, e.g. for
8330 // argument passing. Since this is so common, custom legalize the
8331 // 64-bit integer store into two 32-bit stores.
8332 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8333 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8334 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8335 if (TLI.isBigEndian()) std::swap(Lo, Hi);
8337 unsigned Alignment = ST->getAlignment();
8338 bool isVolatile = ST->isVolatile();
8339 bool isNonTemporal = ST->isNonTemporal();
8341 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
8342 Ptr, ST->getPointerInfo(),
8343 isVolatile, isNonTemporal,
8344 ST->getAlignment());
8345 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
8346 DAG.getConstant(4, Ptr.getValueType()));
8347 Alignment = MinAlign(Alignment, 4U);
8348 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
8349 Ptr, ST->getPointerInfo().getWithOffset(4),
8350 isVolatile, isNonTemporal,
8352 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8361 // Try to infer better alignment information than the store already has.
8362 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8363 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8364 if (Align > ST->getAlignment())
8365 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
8366 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8367 ST->isVolatile(), ST->isNonTemporal(), Align);
8371 // Try transforming a pair floating point load / store ops to integer
8372 // load / store ops.
8373 SDValue NewST = TransformFPLoadStorePair(N);
8374 if (NewST.getNode())
8378 // Walk up chain skipping non-aliasing memory nodes.
8379 SDValue BetterChain = FindBetterChain(N, Chain);
8381 // If there is a better chain.
8382 if (Chain != BetterChain) {
8385 // Replace the chain to avoid dependency.
8386 if (ST->isTruncatingStore()) {
8387 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8388 ST->getPointerInfo(),
8389 ST->getMemoryVT(), ST->isVolatile(),
8390 ST->isNonTemporal(), ST->getAlignment());
8392 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8393 ST->getPointerInfo(),
8394 ST->isVolatile(), ST->isNonTemporal(),
8395 ST->getAlignment());
8398 // Create token to keep both nodes around.
8399 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
8400 MVT::Other, Chain, ReplStore);
8402 // Make sure the new and old chains are cleaned up.
8403 AddToWorkList(Token.getNode());
8405 // Don't add users to work list.
8406 return CombineTo(N, Token, false);
8410 // Try transforming N to an indexed store.
8411 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8412 return SDValue(N, 0);
8414 // FIXME: is there such a thing as a truncating indexed store?
8415 if (ST->isTruncatingStore() && ST->isUnindexed() &&
8416 Value.getValueType().isInteger()) {
8417 // See if we can simplify the input to this truncstore with knowledge that
8418 // only the low bits are being used. For example:
8419 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
8421 GetDemandedBits(Value,
8422 APInt::getLowBitsSet(
8423 Value.getValueType().getScalarType().getSizeInBits(),
8424 ST->getMemoryVT().getScalarType().getSizeInBits()));
8425 AddToWorkList(Value.getNode());
8426 if (Shorter.getNode())
8427 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
8428 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8429 ST->isVolatile(), ST->isNonTemporal(),
8430 ST->getAlignment());
8432 // Otherwise, see if we can simplify the operation with
8433 // SimplifyDemandedBits, which only works if the value has a single use.
8434 if (SimplifyDemandedBits(Value,
8435 APInt::getLowBitsSet(
8436 Value.getValueType().getScalarType().getSizeInBits(),
8437 ST->getMemoryVT().getScalarType().getSizeInBits())))
8438 return SDValue(N, 0);
8441 // If this is a load followed by a store to the same location, then the store
8443 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8444 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8445 ST->isUnindexed() && !ST->isVolatile() &&
8446 // There can't be any side effects between the load and store, such as
8448 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8449 // The store is dead, remove it.
8454 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8455 // truncating store. We can do this even if this is already a truncstore.
8456 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8457 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8458 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8459 ST->getMemoryVT())) {
8460 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8461 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8462 ST->isVolatile(), ST->isNonTemporal(),
8463 ST->getAlignment());
8466 // Only perform this optimization before the types are legal, because we
8467 // don't want to perform this optimization on every DAGCombine invocation.
8469 bool EverChanged = false;
8472 // There can be multiple store sequences on the same chain.
8473 // Keep trying to merge store sequences until we are unable to do so
8474 // or until we merge the last store on the chain.
8475 bool Changed = MergeConsecutiveStores(ST);
8476 EverChanged |= Changed;
8477 if (!Changed) break;
8478 } while (ST->getOpcode() != ISD::DELETED_NODE);
8481 return SDValue(N, 0);
8484 return ReduceLoadOpStoreWidth(N);
8487 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8488 SDValue InVec = N->getOperand(0);
8489 SDValue InVal = N->getOperand(1);
8490 SDValue EltNo = N->getOperand(2);
8491 DebugLoc dl = N->getDebugLoc();
8493 // If the inserted element is an UNDEF, just use the input vector.
8494 if (InVal.getOpcode() == ISD::UNDEF)
8497 EVT VT = InVec.getValueType();
8499 // If we can't generate a legal BUILD_VECTOR, exit
8500 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8503 // Check that we know which element is being inserted
8504 if (!isa<ConstantSDNode>(EltNo))
8506 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8508 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8509 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
8511 SmallVector<SDValue, 8> Ops;
8512 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8513 Ops.append(InVec.getNode()->op_begin(),
8514 InVec.getNode()->op_end());
8515 } else if (InVec.getOpcode() == ISD::UNDEF) {
8516 unsigned NElts = VT.getVectorNumElements();
8517 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8522 // Insert the element
8523 if (Elt < Ops.size()) {
8524 // All the operands of BUILD_VECTOR must have the same type;
8525 // we enforce that here.
8526 EVT OpVT = Ops[0].getValueType();
8527 if (InVal.getValueType() != OpVT)
8528 InVal = OpVT.bitsGT(InVal.getValueType()) ?
8529 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8530 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8534 // Return the new vector
8535 return DAG.getNode(ISD::BUILD_VECTOR, dl,
8536 VT, &Ops[0], Ops.size());
8539 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8540 // (vextract (scalar_to_vector val, 0) -> val
8541 SDValue InVec = N->getOperand(0);
8542 EVT VT = InVec.getValueType();
8543 EVT NVT = N->getValueType(0);
8545 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8546 // Check if the result type doesn't match the inserted element type. A
8547 // SCALAR_TO_VECTOR may truncate the inserted element and the
8548 // EXTRACT_VECTOR_ELT may widen the extracted vector.
8549 SDValue InOp = InVec.getOperand(0);
8550 if (InOp.getValueType() != NVT) {
8551 assert(InOp.getValueType().isInteger() && NVT.isInteger());
8552 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
8557 SDValue EltNo = N->getOperand(1);
8558 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8560 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8561 // We only perform this optimization before the op legalization phase because
8562 // we may introduce new vector instructions which are not backed by TD
8563 // patterns. For example on AVX, extracting elements from a wide vector
8564 // without using extract_subvector.
8565 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8566 && ConstEltNo && !LegalOperations) {
8567 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8568 int NumElem = VT.getVectorNumElements();
8569 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8570 // Find the new index to extract from.
8571 int OrigElt = SVOp->getMaskElt(Elt);
8573 // Extracting an undef index is undef.
8575 return DAG.getUNDEF(NVT);
8577 // Select the right vector half to extract from.
8578 if (OrigElt < NumElem) {
8579 InVec = InVec->getOperand(0);
8581 InVec = InVec->getOperand(1);
8585 EVT IndexTy = N->getOperand(1).getValueType();
8586 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
8587 InVec, DAG.getConstant(OrigElt, IndexTy));
8590 // Perform only after legalization to ensure build_vector / vector_shuffle
8591 // optimizations have already been done.
8592 if (!LegalOperations) return SDValue();
8594 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8595 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8596 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8599 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8600 bool NewLoad = false;
8601 bool BCNumEltsChanged = false;
8602 EVT ExtVT = VT.getVectorElementType();
8605 // If the result of load has to be truncated, then it's not necessarily
8607 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8610 if (InVec.getOpcode() == ISD::BITCAST) {
8611 // Don't duplicate a load with other uses.
8612 if (!InVec.hasOneUse())
8615 EVT BCVT = InVec.getOperand(0).getValueType();
8616 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8618 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8619 BCNumEltsChanged = true;
8620 InVec = InVec.getOperand(0);
8621 ExtVT = BCVT.getVectorElementType();
8625 LoadSDNode *LN0 = NULL;
8626 const ShuffleVectorSDNode *SVN = NULL;
8627 if (ISD::isNormalLoad(InVec.getNode())) {
8628 LN0 = cast<LoadSDNode>(InVec);
8629 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8630 InVec.getOperand(0).getValueType() == ExtVT &&
8631 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8632 // Don't duplicate a load with other uses.
8633 if (!InVec.hasOneUse())
8636 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8637 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8638 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8640 // (load $addr+1*size)
8642 // Don't duplicate a load with other uses.
8643 if (!InVec.hasOneUse())
8646 // If the bit convert changed the number of elements, it is unsafe
8647 // to examine the mask.
8648 if (BCNumEltsChanged)
8651 // Select the input vector, guarding against out of range extract vector.
8652 unsigned NumElems = VT.getVectorNumElements();
8653 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8654 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8656 if (InVec.getOpcode() == ISD::BITCAST) {
8657 // Don't duplicate a load with other uses.
8658 if (!InVec.hasOneUse())
8661 InVec = InVec.getOperand(0);
8663 if (ISD::isNormalLoad(InVec.getNode())) {
8664 LN0 = cast<LoadSDNode>(InVec);
8665 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8669 // Make sure we found a non-volatile load and the extractelement is
8671 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8674 // If Idx was -1 above, Elt is going to be -1, so just return undef.
8676 return DAG.getUNDEF(LVT);
8678 unsigned Align = LN0->getAlignment();
8680 // Check the resultant load doesn't need a higher alignment than the
8684 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8686 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8692 SDValue NewPtr = LN0->getBasePtr();
8693 unsigned PtrOff = 0;
8696 PtrOff = LVT.getSizeInBits() * Elt / 8;
8697 EVT PtrType = NewPtr.getValueType();
8698 if (TLI.isBigEndian())
8699 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8700 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
8701 DAG.getConstant(PtrOff, PtrType));
8704 // The replacement we need to do here is a little tricky: we need to
8705 // replace an extractelement of a load with a load.
8706 // Use ReplaceAllUsesOfValuesWith to do the replacement.
8707 // Note that this replacement assumes that the extractvalue is the only
8708 // use of the load; that's okay because we don't want to perform this
8709 // transformation in other cases anyway.
8712 if (NVT.bitsGT(LVT)) {
8713 // If the result type of vextract is wider than the load, then issue an
8714 // extending load instead.
8715 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8716 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8717 Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
8718 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8719 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8720 Chain = Load.getValue(1);
8722 Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
8723 LN0->getPointerInfo().getWithOffset(PtrOff),
8724 LN0->isVolatile(), LN0->isNonTemporal(),
8725 LN0->isInvariant(), Align);
8726 Chain = Load.getValue(1);
8727 if (NVT.bitsLT(LVT))
8728 Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
8730 Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
8732 WorkListRemover DeadNodes(*this);
8733 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8734 SDValue To[] = { Load, Chain };
8735 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8736 // Since we're explcitly calling ReplaceAllUses, add the new node to the
8737 // worklist explicitly as well.
8738 AddToWorkList(Load.getNode());
8739 AddUsersToWorkList(Load.getNode()); // Add users too
8740 // Make sure to revisit this node to clean it up; it will usually be dead.
8742 return SDValue(N, 0);
8748 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8749 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8750 // We perform this optimization post type-legalization because
8751 // the type-legalizer often scalarizes integer-promoted vectors.
8752 // Performing this optimization before may create bit-casts which
8753 // will be type-legalized to complex code sequences.
8754 // We perform this optimization only before the operation legalizer because we
8755 // may introduce illegal operations.
8756 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8759 unsigned NumInScalars = N->getNumOperands();
8760 DebugLoc dl = N->getDebugLoc();
8761 EVT VT = N->getValueType(0);
8763 // Check to see if this is a BUILD_VECTOR of a bunch of values
8764 // which come from any_extend or zero_extend nodes. If so, we can create
8765 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8766 // optimizations. We do not handle sign-extend because we can't fill the sign
8768 EVT SourceType = MVT::Other;
8769 bool AllAnyExt = true;
8771 for (unsigned i = 0; i != NumInScalars; ++i) {
8772 SDValue In = N->getOperand(i);
8773 // Ignore undef inputs.
8774 if (In.getOpcode() == ISD::UNDEF) continue;
8776 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
8777 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8779 // Abort if the element is not an extension.
8780 if (!ZeroExt && !AnyExt) {
8781 SourceType = MVT::Other;
8785 // The input is a ZeroExt or AnyExt. Check the original type.
8786 EVT InTy = In.getOperand(0).getValueType();
8788 // Check that all of the widened source types are the same.
8789 if (SourceType == MVT::Other)
8792 else if (InTy != SourceType) {
8793 // Multiple income types. Abort.
8794 SourceType = MVT::Other;
8798 // Check if all of the extends are ANY_EXTENDs.
8799 AllAnyExt &= AnyExt;
8802 // In order to have valid types, all of the inputs must be extended from the
8803 // same source type and all of the inputs must be any or zero extend.
8804 // Scalar sizes must be a power of two.
8805 EVT OutScalarTy = VT.getScalarType();
8806 bool ValidTypes = SourceType != MVT::Other &&
8807 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8808 isPowerOf2_32(SourceType.getSizeInBits());
8810 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8811 // turn into a single shuffle instruction.
8815 bool isLE = TLI.isLittleEndian();
8816 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8817 assert(ElemRatio > 1 && "Invalid element size ratio");
8818 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8819 DAG.getConstant(0, SourceType);
8821 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8822 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8824 // Populate the new build_vector
8825 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8826 SDValue Cast = N->getOperand(i);
8827 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8828 Cast.getOpcode() == ISD::ZERO_EXTEND ||
8829 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8831 if (Cast.getOpcode() == ISD::UNDEF)
8832 In = DAG.getUNDEF(SourceType);
8834 In = Cast->getOperand(0);
8835 unsigned Index = isLE ? (i * ElemRatio) :
8836 (i * ElemRatio + (ElemRatio - 1));
8838 assert(Index < Ops.size() && "Invalid index");
8842 // The type of the new BUILD_VECTOR node.
8843 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8844 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8845 "Invalid vector size");
8846 // Check if the new vector type is legal.
8847 if (!isTypeLegal(VecVT)) return SDValue();
8849 // Make the new BUILD_VECTOR.
8850 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8852 // The new BUILD_VECTOR node has the potential to be further optimized.
8853 AddToWorkList(BV.getNode());
8854 // Bitcast to the desired type.
8855 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8858 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8859 EVT VT = N->getValueType(0);
8861 unsigned NumInScalars = N->getNumOperands();
8862 DebugLoc dl = N->getDebugLoc();
8864 EVT SrcVT = MVT::Other;
8865 unsigned Opcode = ISD::DELETED_NODE;
8866 unsigned NumDefs = 0;
8868 for (unsigned i = 0; i != NumInScalars; ++i) {
8869 SDValue In = N->getOperand(i);
8870 unsigned Opc = In.getOpcode();
8872 if (Opc == ISD::UNDEF)
8875 // If all scalar values are floats and converted from integers.
8876 if (Opcode == ISD::DELETED_NODE &&
8877 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8884 EVT InVT = In.getOperand(0).getValueType();
8886 // If all scalar values are typed differently, bail out. It's chosen to
8887 // simplify BUILD_VECTOR of integer types.
8888 if (SrcVT == MVT::Other)
8895 // If the vector has just one element defined, it's not worth to fold it into
8896 // a vectorized one.
8900 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
8901 && "Should only handle conversion from integer to float.");
8902 assert(SrcVT != MVT::Other && "Cannot determine source type!");
8904 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
8906 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
8909 SmallVector<SDValue, 8> Opnds;
8910 for (unsigned i = 0; i != NumInScalars; ++i) {
8911 SDValue In = N->getOperand(i);
8913 if (In.getOpcode() == ISD::UNDEF)
8914 Opnds.push_back(DAG.getUNDEF(SrcVT));
8916 Opnds.push_back(In.getOperand(0));
8918 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
8919 &Opnds[0], Opnds.size());
8920 AddToWorkList(BV.getNode());
8922 return DAG.getNode(Opcode, dl, VT, BV);
8925 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
8926 unsigned NumInScalars = N->getNumOperands();
8927 DebugLoc dl = N->getDebugLoc();
8928 EVT VT = N->getValueType(0);
8930 // A vector built entirely of undefs is undef.
8931 if (ISD::allOperandsUndef(N))
8932 return DAG.getUNDEF(VT);
8934 SDValue V = reduceBuildVecExtToExtBuildVec(N);
8938 V = reduceBuildVecConvertToConvertBuildVec(N);
8942 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
8943 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
8944 // at most two distinct vectors, turn this into a shuffle node.
8946 // May only combine to shuffle after legalize if shuffle is legal.
8947 if (LegalOperations &&
8948 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
8951 SDValue VecIn1, VecIn2;
8952 for (unsigned i = 0; i != NumInScalars; ++i) {
8953 // Ignore undef inputs.
8954 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
8956 // If this input is something other than a EXTRACT_VECTOR_ELT with a
8957 // constant index, bail out.
8958 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8959 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
8960 VecIn1 = VecIn2 = SDValue(0, 0);
8964 // We allow up to two distinct input vectors.
8965 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
8966 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
8969 if (VecIn1.getNode() == 0) {
8970 VecIn1 = ExtractedFromVec;
8971 } else if (VecIn2.getNode() == 0) {
8972 VecIn2 = ExtractedFromVec;
8975 VecIn1 = VecIn2 = SDValue(0, 0);
8980 // If everything is good, we can make a shuffle operation.
8981 if (VecIn1.getNode()) {
8982 SmallVector<int, 8> Mask;
8983 for (unsigned i = 0; i != NumInScalars; ++i) {
8984 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
8989 // If extracting from the first vector, just use the index directly.
8990 SDValue Extract = N->getOperand(i);
8991 SDValue ExtVal = Extract.getOperand(1);
8992 if (Extract.getOperand(0) == VecIn1) {
8993 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
8994 if (ExtIndex > VT.getVectorNumElements())
8997 Mask.push_back(ExtIndex);
9001 // Otherwise, use InIdx + VecSize
9002 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9003 Mask.push_back(Idx+NumInScalars);
9006 // We can't generate a shuffle node with mismatched input and output types.
9007 // Attempt to transform a single input vector to the correct type.
9008 if ((VT != VecIn1.getValueType())) {
9009 // We don't support shuffeling between TWO values of different types.
9010 if (VecIn2.getNode() != 0)
9013 // We only support widening of vectors which are half the size of the
9014 // output registers. For example XMM->YMM widening on X86 with AVX.
9015 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9018 // If the input vector type has a different base type to the output
9019 // vector type, bail out.
9020 if (VecIn1.getValueType().getVectorElementType() !=
9021 VT.getVectorElementType())
9024 // Widen the input vector by adding undef values.
9025 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9026 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9029 // If VecIn2 is unused then change it to undef.
9030 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9032 // Check that we were able to transform all incoming values to the same
9034 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9035 VecIn1.getValueType() != VT)
9038 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9039 if (!isTypeLegal(VT))
9042 // Return the new VECTOR_SHUFFLE node.
9046 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9052 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9053 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9054 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9055 // inputs come from at most two distinct vectors, turn this into a shuffle
9058 // If we only have one input vector, we don't need to do any concatenation.
9059 if (N->getNumOperands() == 1)
9060 return N->getOperand(0);
9062 // Check if all of the operands are undefs.
9063 if (ISD::allOperandsUndef(N))
9064 return DAG.getUNDEF(N->getValueType(0));
9069 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9070 EVT NVT = N->getValueType(0);
9071 SDValue V = N->getOperand(0);
9073 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9075 // (extract_subvec (concat V1, V2, ...), i)
9078 // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9079 if (V->getOperand(0).getValueType() != NVT)
9081 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9082 unsigned NumElems = NVT.getVectorNumElements();
9083 assert((Idx % NumElems) == 0 &&
9084 "IDX in concat is not a multiple of the result vector length.");
9085 return V->getOperand(Idx / NumElems);
9089 if (V->getOpcode() == ISD::BITCAST)
9090 V = V.getOperand(0);
9092 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9093 DebugLoc dl = N->getDebugLoc();
9094 // Handle only simple case where vector being inserted and vector
9095 // being extracted are of same type, and are half size of larger vectors.
9096 EVT BigVT = V->getOperand(0).getValueType();
9097 EVT SmallVT = V->getOperand(1).getValueType();
9098 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9101 // Only handle cases where both indexes are constants with the same type.
9102 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9103 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9105 if (InsIdx && ExtIdx &&
9106 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9107 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9109 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9111 // indices are equal or bit offsets are equal => V1
9112 // otherwise => (extract_subvec V1, ExtIdx)
9113 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9114 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9115 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9116 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9117 DAG.getNode(ISD::BITCAST, dl,
9118 N->getOperand(0).getValueType(),
9119 V->getOperand(0)), N->getOperand(1));
9126 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9127 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9128 EVT VT = N->getValueType(0);
9129 unsigned NumElts = VT.getVectorNumElements();
9131 SDValue N0 = N->getOperand(0);
9132 SDValue N1 = N->getOperand(1);
9133 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9135 SmallVector<SDValue, 4> Ops;
9136 EVT ConcatVT = N0.getOperand(0).getValueType();
9137 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9138 unsigned NumConcats = NumElts / NumElemsPerConcat;
9140 // Look at every vector that's inserted. We're looking for exact
9141 // subvector-sized copies from a concatenated vector
9142 for (unsigned I = 0; I != NumConcats; ++I) {
9143 // Make sure we're dealing with a copy.
9144 unsigned Begin = I * NumElemsPerConcat;
9145 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9148 for (unsigned J = 1; J != NumElemsPerConcat; ++J) {
9149 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9153 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9154 if (FirstElt < N0.getNumOperands())
9155 Ops.push_back(N0.getOperand(FirstElt));
9157 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9160 return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT, Ops.data(),
9164 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9165 EVT VT = N->getValueType(0);
9166 unsigned NumElts = VT.getVectorNumElements();
9168 SDValue N0 = N->getOperand(0);
9169 SDValue N1 = N->getOperand(1);
9171 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9173 // Canonicalize shuffle undef, undef -> undef
9174 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9175 return DAG.getUNDEF(VT);
9177 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9179 // Canonicalize shuffle v, v -> v, undef
9181 SmallVector<int, 8> NewMask;
9182 for (unsigned i = 0; i != NumElts; ++i) {
9183 int Idx = SVN->getMaskElt(i);
9184 if (Idx >= (int)NumElts) Idx -= NumElts;
9185 NewMask.push_back(Idx);
9187 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
9191 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
9192 if (N0.getOpcode() == ISD::UNDEF) {
9193 SmallVector<int, 8> NewMask;
9194 for (unsigned i = 0; i != NumElts; ++i) {
9195 int Idx = SVN->getMaskElt(i);
9197 if (Idx < (int)NumElts)
9202 NewMask.push_back(Idx);
9204 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
9208 // Remove references to rhs if it is undef
9209 if (N1.getOpcode() == ISD::UNDEF) {
9210 bool Changed = false;
9211 SmallVector<int, 8> NewMask;
9212 for (unsigned i = 0; i != NumElts; ++i) {
9213 int Idx = SVN->getMaskElt(i);
9214 if (Idx >= (int)NumElts) {
9218 NewMask.push_back(Idx);
9221 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
9224 // If it is a splat, check if the argument vector is another splat or a
9225 // build_vector with all scalar elements the same.
9226 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9227 SDNode *V = N0.getNode();
9229 // If this is a bit convert that changes the element type of the vector but
9230 // not the number of vector elements, look through it. Be careful not to
9231 // look though conversions that change things like v4f32 to v2f64.
9232 if (V->getOpcode() == ISD::BITCAST) {
9233 SDValue ConvInput = V->getOperand(0);
9234 if (ConvInput.getValueType().isVector() &&
9235 ConvInput.getValueType().getVectorNumElements() == NumElts)
9236 V = ConvInput.getNode();
9239 if (V->getOpcode() == ISD::BUILD_VECTOR) {
9240 assert(V->getNumOperands() == NumElts &&
9241 "BUILD_VECTOR has wrong number of operands");
9243 bool AllSame = true;
9244 for (unsigned i = 0; i != NumElts; ++i) {
9245 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9246 Base = V->getOperand(i);
9250 // Splat of <u, u, u, u>, return <u, u, u, u>
9251 if (!Base.getNode())
9253 for (unsigned i = 0; i != NumElts; ++i) {
9254 if (V->getOperand(i) != Base) {
9259 // Splat of <x, x, x, x>, return <x, x, x, x>
9265 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9266 Level < AfterLegalizeVectorOps &&
9267 (N1.getOpcode() == ISD::UNDEF ||
9268 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9269 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9270 SDValue V = partitionShuffleOfConcats(N, DAG);
9276 // If this shuffle node is simply a swizzle of another shuffle node,
9277 // and it reverses the swizzle of the previous shuffle then we can
9278 // optimize shuffle(shuffle(x, undef), undef) -> x.
9279 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9280 N1.getOpcode() == ISD::UNDEF) {
9282 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9284 // Shuffle nodes can only reverse shuffles with a single non-undef value.
9285 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9288 // The incoming shuffle must be of the same type as the result of the
9290 assert(OtherSV->getOperand(0).getValueType() == VT &&
9291 "Shuffle types don't match");
9293 for (unsigned i = 0; i != NumElts; ++i) {
9294 int Idx = SVN->getMaskElt(i);
9295 assert(Idx < (int)NumElts && "Index references undef operand");
9296 // Next, this index comes from the first value, which is the incoming
9297 // shuffle. Adopt the incoming index.
9299 Idx = OtherSV->getMaskElt(Idx);
9301 // The combined shuffle must map each index to itself.
9302 if (Idx >= 0 && (unsigned)Idx != i)
9306 return OtherSV->getOperand(0);
9312 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9313 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9314 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9315 /// vector_shuffle V, Zero, <0, 4, 2, 4>
9316 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9317 EVT VT = N->getValueType(0);
9318 DebugLoc dl = N->getDebugLoc();
9319 SDValue LHS = N->getOperand(0);
9320 SDValue RHS = N->getOperand(1);
9321 if (N->getOpcode() == ISD::AND) {
9322 if (RHS.getOpcode() == ISD::BITCAST)
9323 RHS = RHS.getOperand(0);
9324 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9325 SmallVector<int, 8> Indices;
9326 unsigned NumElts = RHS.getNumOperands();
9327 for (unsigned i = 0; i != NumElts; ++i) {
9328 SDValue Elt = RHS.getOperand(i);
9329 if (!isa<ConstantSDNode>(Elt))
9332 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9333 Indices.push_back(i);
9334 else if (cast<ConstantSDNode>(Elt)->isNullValue())
9335 Indices.push_back(NumElts);
9340 // Let's see if the target supports this vector_shuffle.
9341 EVT RVT = RHS.getValueType();
9342 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9345 // Return the new VECTOR_SHUFFLE node.
9346 EVT EltVT = RVT.getVectorElementType();
9347 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9348 DAG.getConstant(0, EltVT));
9349 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9350 RVT, &ZeroOps[0], ZeroOps.size());
9351 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9352 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9353 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9360 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9361 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9362 assert(N->getValueType(0).isVector() &&
9363 "SimplifyVBinOp only works on vectors!");
9365 SDValue LHS = N->getOperand(0);
9366 SDValue RHS = N->getOperand(1);
9367 SDValue Shuffle = XformToShuffleWithZero(N);
9368 if (Shuffle.getNode()) return Shuffle;
9370 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9372 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9373 RHS.getOpcode() == ISD::BUILD_VECTOR) {
9374 SmallVector<SDValue, 8> Ops;
9375 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9376 SDValue LHSOp = LHS.getOperand(i);
9377 SDValue RHSOp = RHS.getOperand(i);
9378 // If these two elements can't be folded, bail out.
9379 if ((LHSOp.getOpcode() != ISD::UNDEF &&
9380 LHSOp.getOpcode() != ISD::Constant &&
9381 LHSOp.getOpcode() != ISD::ConstantFP) ||
9382 (RHSOp.getOpcode() != ISD::UNDEF &&
9383 RHSOp.getOpcode() != ISD::Constant &&
9384 RHSOp.getOpcode() != ISD::ConstantFP))
9387 // Can't fold divide by zero.
9388 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9389 N->getOpcode() == ISD::FDIV) {
9390 if ((RHSOp.getOpcode() == ISD::Constant &&
9391 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9392 (RHSOp.getOpcode() == ISD::ConstantFP &&
9393 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9397 EVT VT = LHSOp.getValueType();
9398 EVT RVT = RHSOp.getValueType();
9400 // Integer BUILD_VECTOR operands may have types larger than the element
9401 // size (e.g., when the element type is not legal). Prior to type
9402 // legalization, the types may not match between the two BUILD_VECTORS.
9403 // Truncate one of the operands to make them match.
9404 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9405 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
9407 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
9411 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
9413 if (FoldOp.getOpcode() != ISD::UNDEF &&
9414 FoldOp.getOpcode() != ISD::Constant &&
9415 FoldOp.getOpcode() != ISD::ConstantFP)
9417 Ops.push_back(FoldOp);
9418 AddToWorkList(FoldOp.getNode());
9421 if (Ops.size() == LHS.getNumOperands())
9422 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9423 LHS.getValueType(), &Ops[0], Ops.size());
9429 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9430 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9431 assert(N->getValueType(0).isVector() &&
9432 "SimplifyVUnaryOp only works on vectors!");
9434 SDValue N0 = N->getOperand(0);
9436 if (N0.getOpcode() != ISD::BUILD_VECTOR)
9439 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9440 SmallVector<SDValue, 8> Ops;
9441 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9442 SDValue Op = N0.getOperand(i);
9443 if (Op.getOpcode() != ISD::UNDEF &&
9444 Op.getOpcode() != ISD::ConstantFP)
9446 EVT EltVT = Op.getValueType();
9447 SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op);
9448 if (FoldOp.getOpcode() != ISD::UNDEF &&
9449 FoldOp.getOpcode() != ISD::ConstantFP)
9451 Ops.push_back(FoldOp);
9452 AddToWorkList(FoldOp.getNode());
9455 if (Ops.size() != N0.getNumOperands())
9458 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9459 N0.getValueType(), &Ops[0], Ops.size());
9462 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
9463 SDValue N1, SDValue N2){
9464 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9466 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9467 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9469 // If we got a simplified select_cc node back from SimplifySelectCC, then
9470 // break it down into a new SETCC node, and a new SELECT node, and then return
9471 // the SELECT node, since we were called with a SELECT node.
9472 if (SCC.getNode()) {
9473 // Check to see if we got a select_cc back (to turn into setcc/select).
9474 // Otherwise, just return whatever node we got back, like fabs.
9475 if (SCC.getOpcode() == ISD::SELECT_CC) {
9476 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
9478 SCC.getOperand(0), SCC.getOperand(1),
9480 AddToWorkList(SETCC.getNode());
9481 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
9482 SCC.getOperand(2), SCC.getOperand(3), SETCC);
9490 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9491 /// are the two values being selected between, see if we can simplify the
9492 /// select. Callers of this should assume that TheSelect is deleted if this
9493 /// returns true. As such, they should return the appropriate thing (e.g. the
9494 /// node) back to the top-level of the DAG combiner loop to avoid it being
9496 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9499 // Cannot simplify select with vector condition
9500 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9502 // If this is a select from two identical things, try to pull the operation
9503 // through the select.
9504 if (LHS.getOpcode() != RHS.getOpcode() ||
9505 !LHS.hasOneUse() || !RHS.hasOneUse())
9508 // If this is a load and the token chain is identical, replace the select
9509 // of two loads with a load through a select of the address to load from.
9510 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9511 // constants have been dropped into the constant pool.
9512 if (LHS.getOpcode() == ISD::LOAD) {
9513 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9514 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9516 // Token chains must be identical.
9517 if (LHS.getOperand(0) != RHS.getOperand(0) ||
9518 // Do not let this transformation reduce the number of volatile loads.
9519 LLD->isVolatile() || RLD->isVolatile() ||
9520 // If this is an EXTLOAD, the VT's must match.
9521 LLD->getMemoryVT() != RLD->getMemoryVT() ||
9522 // If this is an EXTLOAD, the kind of extension must match.
9523 (LLD->getExtensionType() != RLD->getExtensionType() &&
9524 // The only exception is if one of the extensions is anyext.
9525 LLD->getExtensionType() != ISD::EXTLOAD &&
9526 RLD->getExtensionType() != ISD::EXTLOAD) ||
9527 // FIXME: this discards src value information. This is
9528 // over-conservative. It would be beneficial to be able to remember
9529 // both potential memory locations. Since we are discarding
9530 // src value info, don't do the transformation if the memory
9531 // locations are not in the default address space.
9532 LLD->getPointerInfo().getAddrSpace() != 0 ||
9533 RLD->getPointerInfo().getAddrSpace() != 0 ||
9534 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9535 LLD->getBasePtr().getValueType()))
9538 // Check that the select condition doesn't reach either load. If so,
9539 // folding this will induce a cycle into the DAG. If not, this is safe to
9540 // xform, so create a select of the addresses.
9542 if (TheSelect->getOpcode() == ISD::SELECT) {
9543 SDNode *CondNode = TheSelect->getOperand(0).getNode();
9544 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9545 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9547 // The loads must not depend on one another.
9548 if (LLD->isPredecessorOf(RLD) ||
9549 RLD->isPredecessorOf(LLD))
9551 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
9552 LLD->getBasePtr().getValueType(),
9553 TheSelect->getOperand(0), LLD->getBasePtr(),
9555 } else { // Otherwise SELECT_CC
9556 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9557 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9559 if ((LLD->hasAnyUseOfValue(1) &&
9560 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9561 (RLD->hasAnyUseOfValue(1) &&
9562 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9565 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
9566 LLD->getBasePtr().getValueType(),
9567 TheSelect->getOperand(0),
9568 TheSelect->getOperand(1),
9569 LLD->getBasePtr(), RLD->getBasePtr(),
9570 TheSelect->getOperand(4));
9574 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9575 Load = DAG.getLoad(TheSelect->getValueType(0),
9576 TheSelect->getDebugLoc(),
9577 // FIXME: Discards pointer info.
9578 LLD->getChain(), Addr, MachinePointerInfo(),
9579 LLD->isVolatile(), LLD->isNonTemporal(),
9580 LLD->isInvariant(), LLD->getAlignment());
9582 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9583 RLD->getExtensionType() : LLD->getExtensionType(),
9584 TheSelect->getDebugLoc(),
9585 TheSelect->getValueType(0),
9586 // FIXME: Discards pointer info.
9587 LLD->getChain(), Addr, MachinePointerInfo(),
9588 LLD->getMemoryVT(), LLD->isVolatile(),
9589 LLD->isNonTemporal(), LLD->getAlignment());
9592 // Users of the select now use the result of the load.
9593 CombineTo(TheSelect, Load);
9595 // Users of the old loads now use the new load's chain. We know the
9596 // old-load value is dead now.
9597 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9598 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9605 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9606 /// where 'cond' is the comparison specified by CC.
9607 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
9608 SDValue N2, SDValue N3,
9609 ISD::CondCode CC, bool NotExtCompare) {
9610 // (x ? y : y) -> y.
9611 if (N2 == N3) return N2;
9613 EVT VT = N2.getValueType();
9614 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9615 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9616 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9618 // Determine if the condition we're dealing with is constant
9619 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
9620 N0, N1, CC, DL, false);
9621 if (SCC.getNode()) AddToWorkList(SCC.getNode());
9622 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9624 // fold select_cc true, x, y -> x
9625 if (SCCC && !SCCC->isNullValue())
9627 // fold select_cc false, x, y -> y
9628 if (SCCC && SCCC->isNullValue())
9631 // Check to see if we can simplify the select into an fabs node
9632 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9633 // Allow either -0.0 or 0.0
9634 if (CFP->getValueAPF().isZero()) {
9635 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9636 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9637 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9638 N2 == N3.getOperand(0))
9639 return DAG.getNode(ISD::FABS, DL, VT, N0);
9641 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9642 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9643 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9644 N2.getOperand(0) == N3)
9645 return DAG.getNode(ISD::FABS, DL, VT, N3);
9649 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9650 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9651 // in it. This is a win when the constant is not otherwise available because
9652 // it replaces two constant pool loads with one. We only do this if the FP
9653 // type is known to be legal, because if it isn't, then we are before legalize
9654 // types an we want the other legalization to happen first (e.g. to avoid
9655 // messing with soft float) and if the ConstantFP is not legal, because if
9656 // it is legal, we may not need to store the FP constant in a constant pool.
9657 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9658 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9659 if (TLI.isTypeLegal(N2.getValueType()) &&
9660 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9661 TargetLowering::Legal) &&
9662 // If both constants have multiple uses, then we won't need to do an
9663 // extra load, they are likely around in registers for other users.
9664 (TV->hasOneUse() || FV->hasOneUse())) {
9665 Constant *Elts[] = {
9666 const_cast<ConstantFP*>(FV->getConstantFPValue()),
9667 const_cast<ConstantFP*>(TV->getConstantFPValue())
9669 Type *FPTy = Elts[0]->getType();
9670 const DataLayout &TD = *TLI.getDataLayout();
9672 // Create a ConstantArray of the two constants.
9673 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9674 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9675 TD.getPrefTypeAlignment(FPTy));
9676 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9678 // Get the offsets to the 0 and 1 element of the array so that we can
9679 // select between them.
9680 SDValue Zero = DAG.getIntPtrConstant(0);
9681 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9682 SDValue One = DAG.getIntPtrConstant(EltSize);
9684 SDValue Cond = DAG.getSetCC(DL,
9685 TLI.getSetCCResultType(N0.getValueType()),
9687 AddToWorkList(Cond.getNode());
9688 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
9690 AddToWorkList(CstOffset.getNode());
9691 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9693 AddToWorkList(CPIdx.getNode());
9694 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9695 MachinePointerInfo::getConstantPool(), false,
9696 false, false, Alignment);
9701 // Check to see if we can perform the "gzip trick", transforming
9702 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9703 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9704 (N1C->isNullValue() || // (a < 0) ? b : 0
9705 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
9706 EVT XType = N0.getValueType();
9707 EVT AType = N2.getValueType();
9708 if (XType.bitsGE(AType)) {
9709 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9710 // single-bit constant.
9711 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9712 unsigned ShCtV = N2C->getAPIntValue().logBase2();
9713 ShCtV = XType.getSizeInBits()-ShCtV-1;
9714 SDValue ShCt = DAG.getConstant(ShCtV,
9715 getShiftAmountTy(N0.getValueType()));
9716 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
9718 AddToWorkList(Shift.getNode());
9720 if (XType.bitsGT(AType)) {
9721 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9722 AddToWorkList(Shift.getNode());
9725 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9728 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
9730 DAG.getConstant(XType.getSizeInBits()-1,
9731 getShiftAmountTy(N0.getValueType())));
9732 AddToWorkList(Shift.getNode());
9734 if (XType.bitsGT(AType)) {
9735 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9736 AddToWorkList(Shift.getNode());
9739 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9743 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9744 // where y is has a single bit set.
9745 // A plaintext description would be, we can turn the SELECT_CC into an AND
9746 // when the condition can be materialized as an all-ones register. Any
9747 // single bit-test can be materialized as an all-ones register with
9748 // shift-left and shift-right-arith.
9749 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9750 N0->getValueType(0) == VT &&
9751 N1C && N1C->isNullValue() &&
9752 N2C && N2C->isNullValue()) {
9753 SDValue AndLHS = N0->getOperand(0);
9754 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9755 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9756 // Shift the tested bit over the sign bit.
9757 APInt AndMask = ConstAndRHS->getAPIntValue();
9759 DAG.getConstant(AndMask.countLeadingZeros(),
9760 getShiftAmountTy(AndLHS.getValueType()));
9761 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
9763 // Now arithmetic right shift it all the way over, so the result is either
9764 // all-ones, or zero.
9766 DAG.getConstant(AndMask.getBitWidth()-1,
9767 getShiftAmountTy(Shl.getValueType()));
9768 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
9770 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9774 // fold select C, 16, 0 -> shl C, 4
9775 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9776 TLI.getBooleanContents(N0.getValueType().isVector()) ==
9777 TargetLowering::ZeroOrOneBooleanContent) {
9779 // If the caller doesn't want us to simplify this into a zext of a compare,
9781 if (NotExtCompare && N2C->getAPIntValue() == 1)
9784 // Get a SetCC of the condition
9785 // NOTE: Don't create a SETCC if it's not legal on this target.
9786 if (!LegalOperations ||
9787 TLI.isOperationLegal(ISD::SETCC,
9788 LegalTypes ? TLI.getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9790 // cast from setcc result type to select result type
9792 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
9794 if (N2.getValueType().bitsLT(SCC.getValueType()))
9795 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(),
9798 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9799 N2.getValueType(), SCC);
9801 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
9802 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9803 N2.getValueType(), SCC);
9806 AddToWorkList(SCC.getNode());
9807 AddToWorkList(Temp.getNode());
9809 if (N2C->getAPIntValue() == 1)
9812 // shl setcc result by log2 n2c
9813 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9814 DAG.getConstant(N2C->getAPIntValue().logBase2(),
9815 getShiftAmountTy(Temp.getValueType())));
9819 // Check to see if this is the equivalent of setcc
9820 // FIXME: Turn all of these into setcc if setcc if setcc is legal
9821 // otherwise, go ahead with the folds.
9822 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9823 EVT XType = N0.getValueType();
9824 if (!LegalOperations ||
9825 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
9826 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
9827 if (Res.getValueType() != VT)
9828 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9832 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9833 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9834 (!LegalOperations ||
9835 TLI.isOperationLegal(ISD::CTLZ, XType))) {
9836 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
9837 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9838 DAG.getConstant(Log2_32(XType.getSizeInBits()),
9839 getShiftAmountTy(Ctlz.getValueType())));
9841 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9842 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9843 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
9844 XType, DAG.getConstant(0, XType), N0);
9845 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
9846 return DAG.getNode(ISD::SRL, DL, XType,
9847 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
9848 DAG.getConstant(XType.getSizeInBits()-1,
9849 getShiftAmountTy(XType)));
9851 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
9852 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
9853 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
9854 DAG.getConstant(XType.getSizeInBits()-1,
9855 getShiftAmountTy(N0.getValueType())));
9856 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
9860 // Check to see if this is an integer abs.
9861 // select_cc setg[te] X, 0, X, -X ->
9862 // select_cc setgt X, -1, X, -X ->
9863 // select_cc setl[te] X, 0, -X, X ->
9864 // select_cc setlt X, 1, -X, X ->
9865 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9867 ConstantSDNode *SubC = NULL;
9868 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
9869 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
9870 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
9871 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
9872 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
9873 (N1C->isOne() && CC == ISD::SETLT)) &&
9874 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
9875 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
9877 EVT XType = N0.getValueType();
9878 if (SubC && SubC->isNullValue() && XType.isInteger()) {
9879 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
9881 DAG.getConstant(XType.getSizeInBits()-1,
9882 getShiftAmountTy(N0.getValueType())));
9883 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
9885 AddToWorkList(Shift.getNode());
9886 AddToWorkList(Add.getNode());
9887 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
9894 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
9895 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
9896 SDValue N1, ISD::CondCode Cond,
9897 DebugLoc DL, bool foldBooleans) {
9898 TargetLowering::DAGCombinerInfo
9899 DagCombineInfo(DAG, Level, false, this);
9900 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
9903 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
9904 /// return a DAG expression to select that will generate the same value by
9905 /// multiplying by a magic number. See:
9906 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9907 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
9908 std::vector<SDNode*> Built;
9909 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
9911 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9917 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
9918 /// return a DAG expression to select that will generate the same value by
9919 /// multiplying by a magic number. See:
9920 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9921 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
9922 std::vector<SDNode*> Built;
9923 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
9925 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9931 /// FindBaseOffset - Return true if base is a frame index, which is known not
9932 // to alias with anything but itself. Provides base object and offset as
9934 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
9935 const GlobalValue *&GV, const void *&CV) {
9936 // Assume it is a primitive operation.
9937 Base = Ptr; Offset = 0; GV = 0; CV = 0;
9939 // If it's an adding a simple constant then integrate the offset.
9940 if (Base.getOpcode() == ISD::ADD) {
9941 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
9942 Base = Base.getOperand(0);
9943 Offset += C->getZExtValue();
9947 // Return the underlying GlobalValue, and update the Offset. Return false
9948 // for GlobalAddressSDNode since the same GlobalAddress may be represented
9949 // by multiple nodes with different offsets.
9950 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
9951 GV = G->getGlobal();
9952 Offset += G->getOffset();
9956 // Return the underlying Constant value, and update the Offset. Return false
9957 // for ConstantSDNodes since the same constant pool entry may be represented
9958 // by multiple nodes with different offsets.
9959 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
9960 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
9961 : (const void *)C->getConstVal();
9962 Offset += C->getOffset();
9965 // If it's any of the following then it can't alias with anything but itself.
9966 return isa<FrameIndexSDNode>(Base);
9969 /// isAlias - Return true if there is any possibility that the two addresses
9971 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
9972 const Value *SrcValue1, int SrcValueOffset1,
9973 unsigned SrcValueAlign1,
9974 const MDNode *TBAAInfo1,
9975 SDValue Ptr2, int64_t Size2,
9976 const Value *SrcValue2, int SrcValueOffset2,
9977 unsigned SrcValueAlign2,
9978 const MDNode *TBAAInfo2) const {
9979 // If they are the same then they must be aliases.
9980 if (Ptr1 == Ptr2) return true;
9982 // Gather base node and offset information.
9983 SDValue Base1, Base2;
9984 int64_t Offset1, Offset2;
9985 const GlobalValue *GV1, *GV2;
9986 const void *CV1, *CV2;
9987 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
9988 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
9990 // If they have a same base address then check to see if they overlap.
9991 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
9992 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
9994 // It is possible for different frame indices to alias each other, mostly
9995 // when tail call optimization reuses return address slots for arguments.
9996 // To catch this case, look up the actual index of frame indices to compute
9997 // the real alias relationship.
9998 if (isFrameIndex1 && isFrameIndex2) {
9999 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10000 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10001 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10002 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10005 // Otherwise, if we know what the bases are, and they aren't identical, then
10006 // we know they cannot alias.
10007 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10010 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10011 // compared to the size and offset of the access, we may be able to prove they
10012 // do not alias. This check is conservative for now to catch cases created by
10013 // splitting vector types.
10014 if ((SrcValueAlign1 == SrcValueAlign2) &&
10015 (SrcValueOffset1 != SrcValueOffset2) &&
10016 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10017 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10018 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10020 // There is no overlap between these relatively aligned accesses of similar
10021 // size, return no alias.
10022 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10026 if (CombinerGlobalAA) {
10027 // Use alias analysis information.
10028 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10029 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10030 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10031 AliasAnalysis::AliasResult AAResult =
10032 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10033 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10034 if (AAResult == AliasAnalysis::NoAlias)
10038 // Otherwise we have to assume they alias.
10042 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10043 SDValue Ptr0, Ptr1;
10044 int64_t Size0, Size1;
10045 const Value *SrcValue0, *SrcValue1;
10046 int SrcValueOffset0, SrcValueOffset1;
10047 unsigned SrcValueAlign0, SrcValueAlign1;
10048 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10049 FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10050 SrcValueAlign0, SrcTBAAInfo0);
10051 FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10052 SrcValueAlign1, SrcTBAAInfo1);
10053 return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10054 SrcValueAlign0, SrcTBAAInfo0,
10055 Ptr1, Size1, SrcValue1, SrcValueOffset1,
10056 SrcValueAlign1, SrcTBAAInfo1);
10059 /// FindAliasInfo - Extracts the relevant alias information from the memory
10060 /// node. Returns true if the operand was a load.
10061 bool DAGCombiner::FindAliasInfo(SDNode *N,
10062 SDValue &Ptr, int64_t &Size,
10063 const Value *&SrcValue,
10064 int &SrcValueOffset,
10065 unsigned &SrcValueAlign,
10066 const MDNode *&TBAAInfo) const {
10067 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10069 Ptr = LS->getBasePtr();
10070 Size = LS->getMemoryVT().getSizeInBits() >> 3;
10071 SrcValue = LS->getSrcValue();
10072 SrcValueOffset = LS->getSrcValueOffset();
10073 SrcValueAlign = LS->getOriginalAlignment();
10074 TBAAInfo = LS->getTBAAInfo();
10075 return isa<LoadSDNode>(LS);
10078 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10079 /// looking for aliasing nodes and adding them to the Aliases vector.
10080 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10081 SmallVector<SDValue, 8> &Aliases) {
10082 SmallVector<SDValue, 8> Chains; // List of chains to visit.
10083 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
10085 // Get alias information for node.
10088 const Value *SrcValue;
10089 int SrcValueOffset;
10090 unsigned SrcValueAlign;
10091 const MDNode *SrcTBAAInfo;
10092 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10093 SrcValueAlign, SrcTBAAInfo);
10096 Chains.push_back(OriginalChain);
10097 unsigned Depth = 0;
10099 // Look at each chain and determine if it is an alias. If so, add it to the
10100 // aliases list. If not, then continue up the chain looking for the next
10102 while (!Chains.empty()) {
10103 SDValue Chain = Chains.back();
10106 // For TokenFactor nodes, look at each operand and only continue up the
10107 // chain until we find two aliases. If we've seen two aliases, assume we'll
10108 // find more and revert to original chain since the xform is unlikely to be
10111 // FIXME: The depth check could be made to return the last non-aliasing
10112 // chain we found before we hit a tokenfactor rather than the original
10114 if (Depth > 6 || Aliases.size() == 2) {
10116 Aliases.push_back(OriginalChain);
10120 // Don't bother if we've been before.
10121 if (!Visited.insert(Chain.getNode()))
10124 switch (Chain.getOpcode()) {
10125 case ISD::EntryToken:
10126 // Entry token is ideal chain operand, but handled in FindBetterChain.
10131 // Get alias information for Chain.
10134 const Value *OpSrcValue;
10135 int OpSrcValueOffset;
10136 unsigned OpSrcValueAlign;
10137 const MDNode *OpSrcTBAAInfo;
10138 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10139 OpSrcValue, OpSrcValueOffset,
10143 // If chain is alias then stop here.
10144 if (!(IsLoad && IsOpLoad) &&
10145 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10147 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10148 OpSrcValueAlign, OpSrcTBAAInfo)) {
10149 Aliases.push_back(Chain);
10151 // Look further up the chain.
10152 Chains.push_back(Chain.getOperand(0));
10158 case ISD::TokenFactor:
10159 // We have to check each of the operands of the token factor for "small"
10160 // token factors, so we queue them up. Adding the operands to the queue
10161 // (stack) in reverse order maintains the original order and increases the
10162 // likelihood that getNode will find a matching token factor (CSE.)
10163 if (Chain.getNumOperands() > 16) {
10164 Aliases.push_back(Chain);
10167 for (unsigned n = Chain.getNumOperands(); n;)
10168 Chains.push_back(Chain.getOperand(--n));
10173 // For all other instructions we will just have to take what we can get.
10174 Aliases.push_back(Chain);
10180 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10181 /// for a better chain (aliasing node.)
10182 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10183 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
10185 // Accumulate all the aliases to this node.
10186 GatherAllAliases(N, OldChain, Aliases);
10188 // If no operands then chain to entry token.
10189 if (Aliases.size() == 0)
10190 return DAG.getEntryNode();
10192 // If a single operand then chain to it. We don't need to revisit it.
10193 if (Aliases.size() == 1)
10196 // Construct a custom tailored token factor.
10197 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
10198 &Aliases[0], Aliases.size());
10201 // SelectionDAG::Combine - This is the entry point for the file.
10203 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10204 CodeGenOpt::Level OptLevel) {
10205 /// run - This is the main entry point to this class.
10207 DAGCombiner(*this, AA, OptLevel).Run(Level);