Teach DAG combine to fold (buildvec (Xint2fp x)) to (Xint2fp (buildvec x))
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
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.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/DataLayout.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 using namespace llvm;
39
40 STATISTIC(NodesCombined   , "Number of dag nodes combined");
41 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
42 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
43 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
44 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
45
46 namespace {
47   static cl::opt<bool>
48     CombinerAA("combiner-alias-analysis", cl::Hidden,
49                cl::desc("Turn on alias analysis during testing"));
50
51   static cl::opt<bool>
52     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53                cl::desc("Include global information in alias analysis"));
54
55 //------------------------------ DAGCombiner ---------------------------------//
56
57   class DAGCombiner {
58     SelectionDAG &DAG;
59     const TargetLowering &TLI;
60     CombineLevel Level;
61     CodeGenOpt::Level OptLevel;
62     bool LegalOperations;
63     bool LegalTypes;
64
65     // Worklist of all of the nodes that need to be simplified.
66     //
67     // This has the semantics that when adding to the worklist,
68     // the item added must be next to be processed. It should
69     // also only appear once. The naive approach to this takes
70     // linear time.
71     //
72     // To reduce the insert/remove time to logarithmic, we use
73     // a set and a vector to maintain our worklist.
74     //
75     // The set contains the items on the worklist, but does not
76     // maintain the order they should be visited.
77     //
78     // The vector maintains the order nodes should be visited, but may
79     // contain duplicate or removed nodes. When choosing a node to
80     // visit, we pop off the order stack until we find an item that is
81     // also in the contents set. All operations are O(log N).
82     SmallPtrSet<SDNode*, 64> WorkListContents;
83     SmallVector<SDNode*, 64> WorkListOrder;
84
85     // AA - Used for DAG load/store alias analysis.
86     AliasAnalysis &AA;
87
88     /// AddUsersToWorkList - When an instruction is simplified, add all users of
89     /// the instruction to the work lists because they might get more simplified
90     /// now.
91     ///
92     void AddUsersToWorkList(SDNode *N) {
93       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
94            UI != UE; ++UI)
95         AddToWorkList(*UI);
96     }
97
98     /// visit - call the node-specific routine that knows how to fold each
99     /// particular type of node.
100     SDValue visit(SDNode *N);
101
102   public:
103     /// AddToWorkList - Add to the work list making sure its instance is at the
104     /// back (next to be processed.)
105     void AddToWorkList(SDNode *N) {
106       WorkListContents.insert(N);
107       WorkListOrder.push_back(N);
108     }
109
110     /// removeFromWorkList - remove all instances of N from the worklist.
111     ///
112     void removeFromWorkList(SDNode *N) {
113       WorkListContents.erase(N);
114     }
115
116     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
117                       bool AddTo = true);
118
119     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
120       return CombineTo(N, &Res, 1, AddTo);
121     }
122
123     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
124                       bool AddTo = true) {
125       SDValue To[] = { Res0, Res1 };
126       return CombineTo(N, To, 2, AddTo);
127     }
128
129     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
130
131   private:
132
133     /// SimplifyDemandedBits - Check the specified integer node value to see if
134     /// it can be simplified or if things it uses can be simplified by bit
135     /// propagation.  If so, return true.
136     bool SimplifyDemandedBits(SDValue Op) {
137       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
138       APInt Demanded = APInt::getAllOnesValue(BitWidth);
139       return SimplifyDemandedBits(Op, Demanded);
140     }
141
142     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
143
144     bool CombineToPreIndexedLoadStore(SDNode *N);
145     bool CombineToPostIndexedLoadStore(SDNode *N);
146
147     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
148     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
149     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
150     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
151     SDValue PromoteIntBinOp(SDValue Op);
152     SDValue PromoteIntShiftOp(SDValue Op);
153     SDValue PromoteExtend(SDValue Op);
154     bool PromoteLoad(SDValue Op);
155
156     void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
157                          SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
158                          ISD::NodeType ExtType);
159
160     /// combine - call the node-specific routine that knows how to fold each
161     /// particular type of node. If that doesn't do anything, try the
162     /// target-specific DAG combines.
163     SDValue combine(SDNode *N);
164
165     // Visitation implementation - Implement dag node combining for different
166     // node types.  The semantics are as follows:
167     // Return Value:
168     //   SDValue.getNode() == 0 - No change was made
169     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
170     //   otherwise              - N should be replaced by the returned Operand.
171     //
172     SDValue visitTokenFactor(SDNode *N);
173     SDValue visitMERGE_VALUES(SDNode *N);
174     SDValue visitADD(SDNode *N);
175     SDValue visitSUB(SDNode *N);
176     SDValue visitADDC(SDNode *N);
177     SDValue visitSUBC(SDNode *N);
178     SDValue visitADDE(SDNode *N);
179     SDValue visitSUBE(SDNode *N);
180     SDValue visitMUL(SDNode *N);
181     SDValue visitSDIV(SDNode *N);
182     SDValue visitUDIV(SDNode *N);
183     SDValue visitSREM(SDNode *N);
184     SDValue visitUREM(SDNode *N);
185     SDValue visitMULHU(SDNode *N);
186     SDValue visitMULHS(SDNode *N);
187     SDValue visitSMUL_LOHI(SDNode *N);
188     SDValue visitUMUL_LOHI(SDNode *N);
189     SDValue visitSMULO(SDNode *N);
190     SDValue visitUMULO(SDNode *N);
191     SDValue visitSDIVREM(SDNode *N);
192     SDValue visitUDIVREM(SDNode *N);
193     SDValue visitAND(SDNode *N);
194     SDValue visitOR(SDNode *N);
195     SDValue visitXOR(SDNode *N);
196     SDValue SimplifyVBinOp(SDNode *N);
197     SDValue SimplifyVUnaryOp(SDNode *N);
198     SDValue visitSHL(SDNode *N);
199     SDValue visitSRA(SDNode *N);
200     SDValue visitSRL(SDNode *N);
201     SDValue visitCTLZ(SDNode *N);
202     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
203     SDValue visitCTTZ(SDNode *N);
204     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
205     SDValue visitCTPOP(SDNode *N);
206     SDValue visitSELECT(SDNode *N);
207     SDValue visitSELECT_CC(SDNode *N);
208     SDValue visitSETCC(SDNode *N);
209     SDValue visitSIGN_EXTEND(SDNode *N);
210     SDValue visitZERO_EXTEND(SDNode *N);
211     SDValue visitANY_EXTEND(SDNode *N);
212     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
213     SDValue visitTRUNCATE(SDNode *N);
214     SDValue visitBITCAST(SDNode *N);
215     SDValue visitBUILD_PAIR(SDNode *N);
216     SDValue visitFADD(SDNode *N);
217     SDValue visitFSUB(SDNode *N);
218     SDValue visitFMUL(SDNode *N);
219     SDValue visitFMA(SDNode *N);
220     SDValue visitFDIV(SDNode *N);
221     SDValue visitFREM(SDNode *N);
222     SDValue visitFCOPYSIGN(SDNode *N);
223     SDValue visitSINT_TO_FP(SDNode *N);
224     SDValue visitUINT_TO_FP(SDNode *N);
225     SDValue visitFP_TO_SINT(SDNode *N);
226     SDValue visitFP_TO_UINT(SDNode *N);
227     SDValue visitFP_ROUND(SDNode *N);
228     SDValue visitFP_ROUND_INREG(SDNode *N);
229     SDValue visitFP_EXTEND(SDNode *N);
230     SDValue visitFNEG(SDNode *N);
231     SDValue visitFABS(SDNode *N);
232     SDValue visitFCEIL(SDNode *N);
233     SDValue visitFTRUNC(SDNode *N);
234     SDValue visitFFLOOR(SDNode *N);
235     SDValue visitBRCOND(SDNode *N);
236     SDValue visitBR_CC(SDNode *N);
237     SDValue visitLOAD(SDNode *N);
238     SDValue visitSTORE(SDNode *N);
239     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
240     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
241     SDValue visitBUILD_VECTOR(SDNode *N);
242     SDValue visitCONCAT_VECTORS(SDNode *N);
243     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
244     SDValue visitVECTOR_SHUFFLE(SDNode *N);
245     SDValue visitMEMBARRIER(SDNode *N);
246
247     SDValue XformToShuffleWithZero(SDNode *N);
248     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
249
250     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
251
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,
261                                          unsigned HiOp);
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);
275
276     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
277
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);
282
283     /// isAlias - Return true if there is any possibility that the two addresses
284     /// overlap.
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;
293
294     /// FindAliasInfo - Extracts the relevant alias information from the memory
295     /// node.  Returns true if the operand was a load.
296     bool FindAliasInfo(SDNode *N,
297                        SDValue &Ptr, int64_t &Size,
298                        const Value *&SrcValue, int &SrcValueOffset,
299                        unsigned &SrcValueAlignment,
300                        const MDNode *&TBAAInfo) const;
301
302     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
303     /// looking for a better chain (aliasing node.)
304     SDValue FindBetterChain(SDNode *N, SDValue Chain);
305
306     /// Merge consecutive store operations into a wide store.
307     /// This optimization uses wide integers or vectors when possible.
308     /// \return True if some memory operations were changed.
309     bool MergeConsecutiveStores(StoreSDNode *N);
310
311   public:
312     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
313       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
314         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
315
316     /// Run - runs the dag combiner on all nodes in the work list
317     void Run(CombineLevel AtLevel);
318
319     SelectionDAG &getDAG() const { return DAG; }
320
321     /// getShiftAmountTy - Returns a type large enough to hold any valid
322     /// shift amount - before type legalization these can be huge.
323     EVT getShiftAmountTy(EVT LHSTy) {
324       return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
325     }
326
327     /// isTypeLegal - This method returns true if we are running before type
328     /// legalization or if the specified VT is legal.
329     bool isTypeLegal(const EVT &VT) {
330       if (!LegalTypes) return true;
331       return TLI.isTypeLegal(VT);
332     }
333   };
334 }
335
336
337 namespace {
338 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
339 /// nodes from the worklist.
340 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
341   DAGCombiner &DC;
342 public:
343   explicit WorkListRemover(DAGCombiner &dc)
344     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
345
346   virtual void NodeDeleted(SDNode *N, SDNode *E) {
347     DC.removeFromWorkList(N);
348   }
349 };
350 }
351
352 //===----------------------------------------------------------------------===//
353 //  TargetLowering::DAGCombinerInfo implementation
354 //===----------------------------------------------------------------------===//
355
356 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
357   ((DAGCombiner*)DC)->AddToWorkList(N);
358 }
359
360 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
361   ((DAGCombiner*)DC)->removeFromWorkList(N);
362 }
363
364 SDValue TargetLowering::DAGCombinerInfo::
365 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
366   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
367 }
368
369 SDValue TargetLowering::DAGCombinerInfo::
370 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
371   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
372 }
373
374
375 SDValue TargetLowering::DAGCombinerInfo::
376 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
377   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
378 }
379
380 void TargetLowering::DAGCombinerInfo::
381 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
382   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
383 }
384
385 //===----------------------------------------------------------------------===//
386 // Helper Functions
387 //===----------------------------------------------------------------------===//
388
389 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
390 /// specified expression for the same cost as the expression itself, or 2 if we
391 /// can compute the negated form more cheaply than the expression itself.
392 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
393                                const TargetLowering &TLI,
394                                const TargetOptions *Options,
395                                unsigned Depth = 0) {
396   // No compile time optimizations on this type.
397   if (Op.getValueType() == MVT::ppcf128)
398     return 0;
399
400   // fneg is removable even if it has multiple uses.
401   if (Op.getOpcode() == ISD::FNEG) return 2;
402
403   // Don't allow anything with multiple uses.
404   if (!Op.hasOneUse()) return 0;
405
406   // Don't recurse exponentially.
407   if (Depth > 6) return 0;
408
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;
415   case ISD::FADD:
416     // FIXME: determine better conditions for this xform.
417     if (!Options->UnsafeFPMath) return 0;
418
419     // After operation legalization, it might not be legal to create new FSUBs.
420     if (LegalOperations &&
421         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
422       return 0;
423
424     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
425     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
426                                     Options, Depth + 1))
427       return V;
428     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
429     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
430                               Depth + 1);
431   case ISD::FSUB:
432     // We can't turn -(A-B) into B-A when we honor signed zeros.
433     if (!Options->UnsafeFPMath) return 0;
434
435     // fold (fneg (fsub A, B)) -> (fsub B, A)
436     return 1;
437
438   case ISD::FMUL:
439   case ISD::FDIV:
440     if (Options->HonorSignDependentRoundingFPMath()) return 0;
441
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,
444                                     Options, Depth + 1))
445       return V;
446
447     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
448                               Depth + 1);
449
450   case ISD::FP_EXTEND:
451   case ISD::FP_ROUND:
452   case ISD::FSIN:
453     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
454                               Depth + 1);
455   }
456 }
457
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);
464
465   // Don't allow anything with multiple uses.
466   assert(Op.hasOneUse() && "Unknown reuse!");
467
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();
473     V.changeSign();
474     return DAG.getConstantFP(V, Op.getValueType());
475   }
476   case ISD::FADD:
477     // FIXME: determine better conditions for this xform.
478     assert(DAG.getTarget().Options.UnsafeFPMath);
479
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),
487                          Op.getOperand(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),
492                        Op.getOperand(0));
493   case ISD::FSUB:
494     // We can't turn -(A-B) into B-A when we honor signed zeros.
495     assert(DAG.getTarget().Options.UnsafeFPMath);
496
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);
501
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));
505
506   case ISD::FMUL:
507   case ISD::FDIV:
508     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
509
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),
517                          Op.getOperand(1));
518
519     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
520     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
521                        Op.getOperand(0),
522                        GetNegatedExpression(Op.getOperand(1), DAG,
523                                             LegalOperations, Depth+1));
524
525   case ISD::FP_EXTEND:
526   case ISD::FSIN:
527     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
528                        GetNegatedExpression(Op.getOperand(0), DAG,
529                                             LegalOperations, Depth+1));
530   case ISD::FP_ROUND:
531       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
532                          GetNegatedExpression(Op.getOperand(0), DAG,
533                                               LegalOperations, Depth+1),
534                          Op.getOperand(1));
535   }
536 }
537
538
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,
545                               SDValue &CC) {
546   if (N.getOpcode() == ISD::SETCC) {
547     LHS = N.getOperand(0);
548     RHS = N.getOperand(1);
549     CC  = N.getOperand(2);
550     return true;
551   }
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);
560     return true;
561   }
562   return false;
563 }
564
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) {
569   SDValue N0, N1, N2;
570   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
571     return true;
572   return false;
573 }
574
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))
581       SDValue OpNode =
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);
586     }
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));
593     }
594   }
595
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))
599       SDValue OpNode =
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);
604     }
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));
611     }
612   }
613
614   return SDValue();
615 }
616
617 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
618                                bool AddTo) {
619   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
620   ++NodesCombined;
621   DEBUG(dbgs() << "\nReplacing.1 ";
622         N->dump(&DAG);
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);
632   if (AddTo) {
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());
638       }
639     }
640   }
641
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);
649
650     // Finally, since the node is now dead, remove it from the graph.
651     DAG.DeleteNode(N);
652   }
653   return SDValue(N, 0);
654 }
655
656 void DAGCombiner::
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);
662
663   // Push the new node and any (possibly new) users onto the worklist.
664   AddToWorkList(TLO.New.getNode());
665   AddUsersToWorkList(TLO.New.getNode());
666
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());
672
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());
678
679     DAG.DeleteNode(TLO.Old.getNode());
680   }
681 }
682
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))
690     return false;
691
692   // Revisit the node.
693   AddToWorkList(Op.getNode());
694
695   // Replace the old value with the new one.
696   ++NodesCombined;
697   DEBUG(dbgs() << "\nReplacing.2 ";
698         TLO.Old.getNode()->dump(&DAG);
699         dbgs() << "\nWith: ";
700         TLO.New.getNode()->dump(&DAG);
701         dbgs() << '\n');
702
703   CommitTargetLoweringOpt(TLO);
704   return true;
705 }
706
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));
711
712   DEBUG(dbgs() << "\nReplacing.9 ";
713         Load->dump(&DAG);
714         dbgs() << "\nWith: ";
715         Trunc.getNode()->dump(&DAG);
716         dbgs() << '\n');
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());
723 }
724
725 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
726   Replace = false;
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
732                                                   : ISD::EXTLOAD)
733       : LD->getExtensionType();
734     Replace = true;
735     return DAG.getExtLoad(ExtType, dl, PVT,
736                           LD->getChain(), LD->getBasePtr(),
737                           LD->getPointerInfo(),
738                           MemVT, LD->isVolatile(),
739                           LD->isNonTemporal(), LD->getAlignment());
740   }
741
742   unsigned Opc = Op.getOpcode();
743   switch (Opc) {
744   default: break;
745   case ISD::AssertSext:
746     return DAG.getNode(ISD::AssertSext, dl, PVT,
747                        SExtPromoteOperand(Op.getOperand(0), PVT),
748                        Op.getOperand(1));
749   case ISD::AssertZext:
750     return DAG.getNode(ISD::AssertZext, dl, PVT,
751                        ZExtPromoteOperand(Op.getOperand(0), PVT),
752                        Op.getOperand(1));
753   case ISD::Constant: {
754     unsigned ExtOpc =
755       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
756     return DAG.getNode(ExtOpc, dl, PVT, Op);
757   }
758   }
759
760   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
761     return SDValue();
762   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
763 }
764
765 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
766   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
767     return SDValue();
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)
773     return SDValue();
774   AddToWorkList(NewOp.getNode());
775
776   if (Replace)
777     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
778   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
779                      DAG.getValueType(OldVT));
780 }
781
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)
788     return SDValue();
789   AddToWorkList(NewOp.getNode());
790
791   if (Replace)
792     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
793   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
794 }
795
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)
801     return SDValue();
802
803   EVT VT = Op.getValueType();
804   if (VT.isVector() || !VT.isInteger())
805     return SDValue();
806
807   // If operation type is 'undesirable', e.g. i16 on x86, consider
808   // promoting it.
809   unsigned Opc = Op.getOpcode();
810   if (TLI.isTypeDesirableForOp(Opc, VT))
811     return SDValue();
812
813   EVT PVT = 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!");
818
819     bool Replace0 = false;
820     SDValue N0 = Op.getOperand(0);
821     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
822     if (NN0.getNode() == 0)
823       return SDValue();
824
825     bool Replace1 = false;
826     SDValue N1 = Op.getOperand(1);
827     SDValue NN1;
828     if (N0 == N1)
829       NN1 = NN0;
830     else {
831       NN1 = PromoteOperand(N1, PVT, Replace1);
832       if (NN1.getNode() == 0)
833         return SDValue();
834     }
835
836     AddToWorkList(NN0.getNode());
837     if (NN1.getNode())
838       AddToWorkList(NN1.getNode());
839
840     if (Replace0)
841       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
842     if (Replace1)
843       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
844
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));
850   }
851   return SDValue();
852 }
853
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)
859     return SDValue();
860
861   EVT VT = Op.getValueType();
862   if (VT.isVector() || !VT.isInteger())
863     return SDValue();
864
865   // If operation type is 'undesirable', e.g. i16 on x86, consider
866   // promoting it.
867   unsigned Opc = Op.getOpcode();
868   if (TLI.isTypeDesirableForOp(Opc, VT))
869     return SDValue();
870
871   EVT PVT = 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!");
876
877     bool Replace = false;
878     SDValue N0 = Op.getOperand(0);
879     if (Opc == ISD::SRA)
880       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
881     else if (Opc == ISD::SRL)
882       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
883     else
884       N0 = PromoteOperand(N0, PVT, Replace);
885     if (N0.getNode() == 0)
886       return SDValue();
887
888     AddToWorkList(N0.getNode());
889     if (Replace)
890       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
891
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)));
897   }
898   return SDValue();
899 }
900
901 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
902   if (!LegalOperations)
903     return SDValue();
904
905   EVT VT = Op.getValueType();
906   if (VT.isVector() || !VT.isInteger())
907     return SDValue();
908
909   // If operation type is 'undesirable', e.g. i16 on x86, consider
910   // promoting it.
911   unsigned Opc = Op.getOpcode();
912   if (TLI.isTypeDesirableForOp(Opc, VT))
913     return SDValue();
914
915   EVT PVT = 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));
926   }
927   return SDValue();
928 }
929
930 bool DAGCombiner::PromoteLoad(SDValue Op) {
931   if (!LegalOperations)
932     return false;
933
934   EVT VT = Op.getValueType();
935   if (VT.isVector() || !VT.isInteger())
936     return false;
937
938   // If operation type is 'undesirable', e.g. i16 on x86, consider
939   // promoting it.
940   unsigned Opc = Op.getOpcode();
941   if (TLI.isTypeDesirableForOp(Opc, VT))
942     return false;
943
944   EVT PVT = VT;
945   // Consult target whether it is a good idea to promote this operation and
946   // what's the right type to promote it to.
947   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
948     assert(PVT != VT && "Don't know what type to promote to!");
949
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
956                                                   : ISD::EXTLOAD)
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);
964
965     DEBUG(dbgs() << "\nPromoting ";
966           N->dump(&DAG);
967           dbgs() << "\nTo: ";
968           Result.getNode()->dump(&DAG);
969           dbgs() << '\n');
970     WorkListRemover DeadNodes(*this);
971     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
972     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
973     removeFromWorkList(N);
974     DAG.DeleteNode(N);
975     AddToWorkList(Result.getNode());
976     return true;
977   }
978   return false;
979 }
980
981
982 //===----------------------------------------------------------------------===//
983 //  Main DAG Combiner implementation
984 //===----------------------------------------------------------------------===//
985
986 void DAGCombiner::Run(CombineLevel AtLevel) {
987   // set the instance variables, so that the various visit routines may use it.
988   Level = AtLevel;
989   LegalOperations = Level >= AfterLegalizeVectorOps;
990   LegalTypes = Level >= AfterLegalizeTypes;
991
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)
995     AddToWorkList(I);
996
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());
1001
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());
1005
1006   // while the worklist isn't empty, find a node and
1007   // try and combine it.
1008   while (!WorkListContents.empty()) {
1009     SDNode *N;
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.
1014     do {
1015       N = WorkListOrder.pop_back_val();
1016     } while (!WorkListContents.erase(N));
1017
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());
1024
1025       DAG.DeleteNode(N);
1026       continue;
1027     }
1028
1029     SDValue RV = combine(N);
1030
1031     if (RV.getNode() == 0)
1032       continue;
1033
1034     ++NodesCombined;
1035
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)
1041       continue;
1042
1043     assert(N->getOpcode() != ISD::DELETED_NODE &&
1044            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1045            "Node was deleted but visit returned new node!");
1046
1047     DEBUG(dbgs() << "\nReplacing.3 ";
1048           N->dump(&DAG);
1049           dbgs() << "\nWith: ";
1050           RV.getNode()->dump(&DAG);
1051           dbgs() << '\n');
1052
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());
1058     else {
1059       assert(N->getValueType(0) == RV.getValueType() &&
1060              N->getNumValues() == 1 && "Type mismatch");
1061       SDValue OpV = RV;
1062       DAG.ReplaceAllUsesWith(N, &OpV);
1063     }
1064
1065     // Push the new node and any users onto the worklist
1066     AddToWorkList(RV.getNode());
1067     AddUsersToWorkList(RV.getNode());
1068
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
1071     // deleted.
1072     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1073       AddToWorkList(N->getOperand(i).getNode());
1074
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);
1082
1083       // Finally, since the node is now dead, remove it from the graph.
1084       DAG.DeleteNode(N);
1085     }
1086   }
1087
1088   // If the root changed (e.g. it was a dead load, update the root).
1089   DAG.setRoot(Dummy.getValue());
1090   DAG.RemoveDeadNodes();
1091 }
1092
1093 SDValue DAGCombiner::visit(SDNode *N) {
1094   switch (N->getOpcode()) {
1095   default: break;
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);
1167   case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
1168   }
1169   return SDValue();
1170 }
1171
1172 SDValue DAGCombiner::combine(SDNode *N) {
1173   SDValue RV = visit(N);
1174
1175   // If nothing happened, try a target-specific DAG combine.
1176   if (RV.getNode() == 0) {
1177     assert(N->getOpcode() != ISD::DELETED_NODE &&
1178            "Node was deleted but visit returned NULL!");
1179
1180     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1181         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1182
1183       // Expose the DAG combiner to the target combiner impls.
1184       TargetLowering::DAGCombinerInfo
1185         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1186
1187       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1188     }
1189   }
1190
1191   // If nothing happened still, try promoting the operation.
1192   if (RV.getNode() == 0) {
1193     switch (N->getOpcode()) {
1194     default: break;
1195     case ISD::ADD:
1196     case ISD::SUB:
1197     case ISD::MUL:
1198     case ISD::AND:
1199     case ISD::OR:
1200     case ISD::XOR:
1201       RV = PromoteIntBinOp(SDValue(N, 0));
1202       break;
1203     case ISD::SHL:
1204     case ISD::SRA:
1205     case ISD::SRL:
1206       RV = PromoteIntShiftOp(SDValue(N, 0));
1207       break;
1208     case ISD::SIGN_EXTEND:
1209     case ISD::ZERO_EXTEND:
1210     case ISD::ANY_EXTEND:
1211       RV = PromoteExtend(SDValue(N, 0));
1212       break;
1213     case ISD::LOAD:
1214       if (PromoteLoad(SDValue(N, 0)))
1215         RV = SDValue(N, 0);
1216       break;
1217     }
1218   }
1219
1220   // If N is a commutative binary node, try commuting it to enable more
1221   // sdisel CSE.
1222   if (RV.getNode() == 0 &&
1223       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1224       N->getNumValues() == 1) {
1225     SDValue N0 = N->getOperand(0);
1226     SDValue N1 = N->getOperand(1);
1227
1228     // Constant operands are canonicalized to RHS.
1229     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1230       SDValue Ops[] = { N1, N0 };
1231       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1232                                             Ops, 2);
1233       if (CSENode)
1234         return SDValue(CSENode, 0);
1235     }
1236   }
1237
1238   return RV;
1239 }
1240
1241 /// getInputChainForNode - Given a node, return its input chain if it has one,
1242 /// otherwise return a null sd operand.
1243 static SDValue getInputChainForNode(SDNode *N) {
1244   if (unsigned NumOps = N->getNumOperands()) {
1245     if (N->getOperand(0).getValueType() == MVT::Other)
1246       return N->getOperand(0);
1247     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1248       return N->getOperand(NumOps-1);
1249     for (unsigned i = 1; i < NumOps-1; ++i)
1250       if (N->getOperand(i).getValueType() == MVT::Other)
1251         return N->getOperand(i);
1252   }
1253   return SDValue();
1254 }
1255
1256 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1257   // If N has two operands, where one has an input chain equal to the other,
1258   // the 'other' chain is redundant.
1259   if (N->getNumOperands() == 2) {
1260     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1261       return N->getOperand(0);
1262     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1263       return N->getOperand(1);
1264   }
1265
1266   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1267   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1268   SmallPtrSet<SDNode*, 16> SeenOps;
1269   bool Changed = false;             // If we should replace this token factor.
1270
1271   // Start out with this token factor.
1272   TFs.push_back(N);
1273
1274   // Iterate through token factors.  The TFs grows when new token factors are
1275   // encountered.
1276   for (unsigned i = 0; i < TFs.size(); ++i) {
1277     SDNode *TF = TFs[i];
1278
1279     // Check each of the operands.
1280     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1281       SDValue Op = TF->getOperand(i);
1282
1283       switch (Op.getOpcode()) {
1284       case ISD::EntryToken:
1285         // Entry tokens don't need to be added to the list. They are
1286         // rededundant.
1287         Changed = true;
1288         break;
1289
1290       case ISD::TokenFactor:
1291         if (Op.hasOneUse() &&
1292             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1293           // Queue up for processing.
1294           TFs.push_back(Op.getNode());
1295           // Clean up in case the token factor is removed.
1296           AddToWorkList(Op.getNode());
1297           Changed = true;
1298           break;
1299         }
1300         // Fall thru
1301
1302       default:
1303         // Only add if it isn't already in the list.
1304         if (SeenOps.insert(Op.getNode()))
1305           Ops.push_back(Op);
1306         else
1307           Changed = true;
1308         break;
1309       }
1310     }
1311   }
1312
1313   SDValue Result;
1314
1315   // If we've change things around then replace token factor.
1316   if (Changed) {
1317     if (Ops.empty()) {
1318       // The entry token is the only possible outcome.
1319       Result = DAG.getEntryNode();
1320     } else {
1321       // New and improved token factor.
1322       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1323                            MVT::Other, &Ops[0], Ops.size());
1324     }
1325
1326     // Don't add users to work list.
1327     return CombineTo(N, Result, false);
1328   }
1329
1330   return Result;
1331 }
1332
1333 /// MERGE_VALUES can always be eliminated.
1334 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1335   WorkListRemover DeadNodes(*this);
1336   // Replacing results may cause a different MERGE_VALUES to suddenly
1337   // be CSE'd with N, and carry its uses with it. Iterate until no
1338   // uses remain, to ensure that the node can be safely deleted.
1339   // First add the users of this node to the work list so that they
1340   // can be tried again once they have new operands.
1341   AddUsersToWorkList(N);
1342   do {
1343     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1344       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1345   } while (!N->use_empty());
1346   removeFromWorkList(N);
1347   DAG.DeleteNode(N);
1348   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1349 }
1350
1351 static
1352 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1353                               SelectionDAG &DAG) {
1354   EVT VT = N0.getValueType();
1355   SDValue N00 = N0.getOperand(0);
1356   SDValue N01 = N0.getOperand(1);
1357   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1358
1359   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1360       isa<ConstantSDNode>(N00.getOperand(1))) {
1361     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1362     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1363                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1364                                  N00.getOperand(0), N01),
1365                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1366                                  N00.getOperand(1), N01));
1367     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1368   }
1369
1370   return SDValue();
1371 }
1372
1373 SDValue DAGCombiner::visitADD(SDNode *N) {
1374   SDValue N0 = N->getOperand(0);
1375   SDValue N1 = N->getOperand(1);
1376   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1377   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1378   EVT VT = N0.getValueType();
1379
1380   // fold vector ops
1381   if (VT.isVector()) {
1382     SDValue FoldedVOp = SimplifyVBinOp(N);
1383     if (FoldedVOp.getNode()) return FoldedVOp;
1384   }
1385
1386   // fold (add x, undef) -> undef
1387   if (N0.getOpcode() == ISD::UNDEF)
1388     return N0;
1389   if (N1.getOpcode() == ISD::UNDEF)
1390     return N1;
1391   // fold (add c1, c2) -> c1+c2
1392   if (N0C && N1C)
1393     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1394   // canonicalize constant to RHS
1395   if (N0C && !N1C)
1396     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1397   // fold (add x, 0) -> x
1398   if (N1C && N1C->isNullValue())
1399     return N0;
1400   // fold (add Sym, c) -> Sym+c
1401   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1402     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1403         GA->getOpcode() == ISD::GlobalAddress)
1404       return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1405                                   GA->getOffset() +
1406                                     (uint64_t)N1C->getSExtValue());
1407   // fold ((c1-A)+c2) -> (c1+c2)-A
1408   if (N1C && N0.getOpcode() == ISD::SUB)
1409     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1410       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1411                          DAG.getConstant(N1C->getAPIntValue()+
1412                                          N0C->getAPIntValue(), VT),
1413                          N0.getOperand(1));
1414   // reassociate add
1415   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1416   if (RADD.getNode() != 0)
1417     return RADD;
1418   // fold ((0-A) + B) -> B-A
1419   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1420       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1421     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1422   // fold (A + (0-B)) -> A-B
1423   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1424       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1425     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1426   // fold (A+(B-A)) -> B
1427   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1428     return N1.getOperand(0);
1429   // fold ((B-A)+A) -> B
1430   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1431     return N0.getOperand(0);
1432   // fold (A+(B-(A+C))) to (B-C)
1433   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1434       N0 == N1.getOperand(1).getOperand(0))
1435     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1436                        N1.getOperand(1).getOperand(1));
1437   // fold (A+(B-(C+A))) to (B-C)
1438   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1439       N0 == N1.getOperand(1).getOperand(1))
1440     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1441                        N1.getOperand(1).getOperand(0));
1442   // fold (A+((B-A)+or-C)) to (B+or-C)
1443   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1444       N1.getOperand(0).getOpcode() == ISD::SUB &&
1445       N0 == N1.getOperand(0).getOperand(1))
1446     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1447                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1448
1449   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1450   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1451     SDValue N00 = N0.getOperand(0);
1452     SDValue N01 = N0.getOperand(1);
1453     SDValue N10 = N1.getOperand(0);
1454     SDValue N11 = N1.getOperand(1);
1455
1456     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1457       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1458                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1459                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1460   }
1461
1462   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1463     return SDValue(N, 0);
1464
1465   // fold (a+b) -> (a|b) iff a and b share no bits.
1466   if (VT.isInteger() && !VT.isVector()) {
1467     APInt LHSZero, LHSOne;
1468     APInt RHSZero, RHSOne;
1469     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1470
1471     if (LHSZero.getBoolValue()) {
1472       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1473
1474       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1475       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1476       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1477         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1478     }
1479   }
1480
1481   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1482   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1483     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1484     if (Result.getNode()) return Result;
1485   }
1486   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1487     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1488     if (Result.getNode()) return Result;
1489   }
1490
1491   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1492   if (N1.getOpcode() == ISD::SHL &&
1493       N1.getOperand(0).getOpcode() == ISD::SUB)
1494     if (ConstantSDNode *C =
1495           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1496       if (C->getAPIntValue() == 0)
1497         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1498                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1499                                        N1.getOperand(0).getOperand(1),
1500                                        N1.getOperand(1)));
1501   if (N0.getOpcode() == ISD::SHL &&
1502       N0.getOperand(0).getOpcode() == ISD::SUB)
1503     if (ConstantSDNode *C =
1504           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1505       if (C->getAPIntValue() == 0)
1506         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1507                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1508                                        N0.getOperand(0).getOperand(1),
1509                                        N0.getOperand(1)));
1510
1511   if (N1.getOpcode() == ISD::AND) {
1512     SDValue AndOp0 = N1.getOperand(0);
1513     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1514     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1515     unsigned DestBits = VT.getScalarType().getSizeInBits();
1516
1517     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1518     // and similar xforms where the inner op is either ~0 or 0.
1519     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1520       DebugLoc DL = N->getDebugLoc();
1521       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1522     }
1523   }
1524
1525   // add (sext i1), X -> sub X, (zext i1)
1526   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1527       N0.getOperand(0).getValueType() == MVT::i1 &&
1528       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1529     DebugLoc DL = N->getDebugLoc();
1530     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1531     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1532   }
1533
1534   return SDValue();
1535 }
1536
1537 SDValue DAGCombiner::visitADDC(SDNode *N) {
1538   SDValue N0 = N->getOperand(0);
1539   SDValue N1 = N->getOperand(1);
1540   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1541   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1542   EVT VT = N0.getValueType();
1543
1544   // If the flag result is dead, turn this into an ADD.
1545   if (!N->hasAnyUseOfValue(1))
1546     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1547                      DAG.getNode(ISD::CARRY_FALSE,
1548                                  N->getDebugLoc(), MVT::Glue));
1549
1550   // canonicalize constant to RHS.
1551   if (N0C && !N1C)
1552     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1553
1554   // fold (addc x, 0) -> x + no carry out
1555   if (N1C && N1C->isNullValue())
1556     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1557                                         N->getDebugLoc(), MVT::Glue));
1558
1559   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1560   APInt LHSZero, LHSOne;
1561   APInt RHSZero, RHSOne;
1562   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1563
1564   if (LHSZero.getBoolValue()) {
1565     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1566
1567     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1568     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1569     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1570       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1571                        DAG.getNode(ISD::CARRY_FALSE,
1572                                    N->getDebugLoc(), MVT::Glue));
1573   }
1574
1575   return SDValue();
1576 }
1577
1578 SDValue DAGCombiner::visitADDE(SDNode *N) {
1579   SDValue N0 = N->getOperand(0);
1580   SDValue N1 = N->getOperand(1);
1581   SDValue CarryIn = N->getOperand(2);
1582   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1583   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1584
1585   // canonicalize constant to RHS
1586   if (N0C && !N1C)
1587     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1588                        N1, N0, CarryIn);
1589
1590   // fold (adde x, y, false) -> (addc x, y)
1591   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1592     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1593
1594   return SDValue();
1595 }
1596
1597 // Since it may not be valid to emit a fold to zero for vector initializers
1598 // check if we can before folding.
1599 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1600                              SelectionDAG &DAG, bool LegalOperations) {
1601   if (!VT.isVector()) {
1602     return DAG.getConstant(0, VT);
1603   }
1604   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1605     // Produce a vector of zeros.
1606     SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1607     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1608     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1609       &Ops[0], Ops.size());
1610   }
1611   return SDValue();
1612 }
1613
1614 SDValue DAGCombiner::visitSUB(SDNode *N) {
1615   SDValue N0 = N->getOperand(0);
1616   SDValue N1 = N->getOperand(1);
1617   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1618   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1619   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1620     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1621   EVT VT = N0.getValueType();
1622
1623   // fold vector ops
1624   if (VT.isVector()) {
1625     SDValue FoldedVOp = SimplifyVBinOp(N);
1626     if (FoldedVOp.getNode()) return FoldedVOp;
1627   }
1628
1629   // fold (sub x, x) -> 0
1630   // FIXME: Refactor this and xor and other similar operations together.
1631   if (N0 == N1)
1632     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1633   // fold (sub c1, c2) -> c1-c2
1634   if (N0C && N1C)
1635     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1636   // fold (sub x, c) -> (add x, -c)
1637   if (N1C)
1638     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1639                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1640   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1641   if (N0C && N0C->isAllOnesValue())
1642     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1643   // fold A-(A-B) -> B
1644   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1645     return N1.getOperand(1);
1646   // fold (A+B)-A -> B
1647   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1648     return N0.getOperand(1);
1649   // fold (A+B)-B -> A
1650   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1651     return N0.getOperand(0);
1652   // fold C2-(A+C1) -> (C2-C1)-A
1653   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1654     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1655                                    VT);
1656     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1657                        N1.getOperand(0));
1658   }
1659   // fold ((A+(B+or-C))-B) -> A+or-C
1660   if (N0.getOpcode() == ISD::ADD &&
1661       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1662        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1663       N0.getOperand(1).getOperand(0) == N1)
1664     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1665                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1666   // fold ((A+(C+B))-B) -> A+C
1667   if (N0.getOpcode() == ISD::ADD &&
1668       N0.getOperand(1).getOpcode() == ISD::ADD &&
1669       N0.getOperand(1).getOperand(1) == N1)
1670     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1671                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1672   // fold ((A-(B-C))-C) -> A-B
1673   if (N0.getOpcode() == ISD::SUB &&
1674       N0.getOperand(1).getOpcode() == ISD::SUB &&
1675       N0.getOperand(1).getOperand(1) == N1)
1676     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1677                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1678
1679   // If either operand of a sub is undef, the result is undef
1680   if (N0.getOpcode() == ISD::UNDEF)
1681     return N0;
1682   if (N1.getOpcode() == ISD::UNDEF)
1683     return N1;
1684
1685   // If the relocation model supports it, consider symbol offsets.
1686   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1687     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1688       // fold (sub Sym, c) -> Sym-c
1689       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1690         return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1691                                     GA->getOffset() -
1692                                       (uint64_t)N1C->getSExtValue());
1693       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1694       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1695         if (GA->getGlobal() == GB->getGlobal())
1696           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1697                                  VT);
1698     }
1699
1700   return SDValue();
1701 }
1702
1703 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1704   SDValue N0 = N->getOperand(0);
1705   SDValue N1 = N->getOperand(1);
1706   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1707   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1708   EVT VT = N0.getValueType();
1709
1710   // If the flag result is dead, turn this into an SUB.
1711   if (!N->hasAnyUseOfValue(1))
1712     return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1713                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1714                                  MVT::Glue));
1715
1716   // fold (subc x, x) -> 0 + no borrow
1717   if (N0 == N1)
1718     return CombineTo(N, DAG.getConstant(0, VT),
1719                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1720                                  MVT::Glue));
1721
1722   // fold (subc x, 0) -> x + no borrow
1723   if (N1C && N1C->isNullValue())
1724     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1725                                         MVT::Glue));
1726
1727   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1728   if (N0C && N0C->isAllOnesValue())
1729     return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1730                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1731                                  MVT::Glue));
1732
1733   return SDValue();
1734 }
1735
1736 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1737   SDValue N0 = N->getOperand(0);
1738   SDValue N1 = N->getOperand(1);
1739   SDValue CarryIn = N->getOperand(2);
1740
1741   // fold (sube x, y, false) -> (subc x, y)
1742   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1743     return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1744
1745   return SDValue();
1746 }
1747
1748 SDValue DAGCombiner::visitMUL(SDNode *N) {
1749   SDValue N0 = N->getOperand(0);
1750   SDValue N1 = N->getOperand(1);
1751   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1752   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1753   EVT VT = N0.getValueType();
1754
1755   // fold vector ops
1756   if (VT.isVector()) {
1757     SDValue FoldedVOp = SimplifyVBinOp(N);
1758     if (FoldedVOp.getNode()) return FoldedVOp;
1759   }
1760
1761   // fold (mul x, undef) -> 0
1762   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1763     return DAG.getConstant(0, VT);
1764   // fold (mul c1, c2) -> c1*c2
1765   if (N0C && N1C)
1766     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1767   // canonicalize constant to RHS
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1770   // fold (mul x, 0) -> 0
1771   if (N1C && N1C->isNullValue())
1772     return N1;
1773   // fold (mul x, -1) -> 0-x
1774   if (N1C && N1C->isAllOnesValue())
1775     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1776                        DAG.getConstant(0, VT), N0);
1777   // fold (mul x, (1 << c)) -> x << c
1778   if (N1C && N1C->getAPIntValue().isPowerOf2())
1779     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1780                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1781                                        getShiftAmountTy(N0.getValueType())));
1782   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1783   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1784     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1785     // FIXME: If the input is something that is easily negated (e.g. a
1786     // single-use add), we should put the negate there.
1787     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1788                        DAG.getConstant(0, VT),
1789                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1790                             DAG.getConstant(Log2Val,
1791                                       getShiftAmountTy(N0.getValueType()))));
1792   }
1793   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1794   if (N1C && N0.getOpcode() == ISD::SHL &&
1795       isa<ConstantSDNode>(N0.getOperand(1))) {
1796     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1797                              N1, N0.getOperand(1));
1798     AddToWorkList(C3.getNode());
1799     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1800                        N0.getOperand(0), C3);
1801   }
1802
1803   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1804   // use.
1805   {
1806     SDValue Sh(0,0), Y(0,0);
1807     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1808     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1809         N0.getNode()->hasOneUse()) {
1810       Sh = N0; Y = N1;
1811     } else if (N1.getOpcode() == ISD::SHL &&
1812                isa<ConstantSDNode>(N1.getOperand(1)) &&
1813                N1.getNode()->hasOneUse()) {
1814       Sh = N1; Y = N0;
1815     }
1816
1817     if (Sh.getNode()) {
1818       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1819                                 Sh.getOperand(0), Y);
1820       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1821                          Mul, Sh.getOperand(1));
1822     }
1823   }
1824
1825   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1826   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1827       isa<ConstantSDNode>(N0.getOperand(1)))
1828     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1829                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1830                                    N0.getOperand(0), N1),
1831                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1832                                    N0.getOperand(1), N1));
1833
1834   // reassociate mul
1835   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1836   if (RMUL.getNode() != 0)
1837     return RMUL;
1838
1839   return SDValue();
1840 }
1841
1842 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1843   SDValue N0 = N->getOperand(0);
1844   SDValue N1 = N->getOperand(1);
1845   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1846   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1847   EVT VT = N->getValueType(0);
1848
1849   // fold vector ops
1850   if (VT.isVector()) {
1851     SDValue FoldedVOp = SimplifyVBinOp(N);
1852     if (FoldedVOp.getNode()) return FoldedVOp;
1853   }
1854
1855   // fold (sdiv c1, c2) -> c1/c2
1856   if (N0C && N1C && !N1C->isNullValue())
1857     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1858   // fold (sdiv X, 1) -> X
1859   if (N1C && N1C->getAPIntValue() == 1LL)
1860     return N0;
1861   // fold (sdiv X, -1) -> 0-X
1862   if (N1C && N1C->isAllOnesValue())
1863     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1864                        DAG.getConstant(0, VT), N0);
1865   // If we know the sign bits of both operands are zero, strength reduce to a
1866   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1867   if (!VT.isVector()) {
1868     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1869       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1870                          N0, N1);
1871   }
1872   // fold (sdiv X, pow2) -> simple ops after legalize
1873   if (N1C && !N1C->isNullValue() &&
1874       (N1C->getAPIntValue().isPowerOf2() ||
1875        (-N1C->getAPIntValue()).isPowerOf2())) {
1876     // If dividing by powers of two is cheap, then don't perform the following
1877     // fold.
1878     if (TLI.isPow2DivCheap())
1879       return SDValue();
1880
1881     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1882
1883     // Splat the sign bit into the register
1884     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1885                               DAG.getConstant(VT.getSizeInBits()-1,
1886                                        getShiftAmountTy(N0.getValueType())));
1887     AddToWorkList(SGN.getNode());
1888
1889     // Add (N0 < 0) ? abs2 - 1 : 0;
1890     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1891                               DAG.getConstant(VT.getSizeInBits() - lg2,
1892                                        getShiftAmountTy(SGN.getValueType())));
1893     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1894     AddToWorkList(SRL.getNode());
1895     AddToWorkList(ADD.getNode());    // Divide by pow2
1896     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1897                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1898
1899     // If we're dividing by a positive value, we're done.  Otherwise, we must
1900     // negate the result.
1901     if (N1C->getAPIntValue().isNonNegative())
1902       return SRA;
1903
1904     AddToWorkList(SRA.getNode());
1905     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1906                        DAG.getConstant(0, VT), SRA);
1907   }
1908
1909   // if integer divide is expensive and we satisfy the requirements, emit an
1910   // alternate sequence.
1911   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1912     SDValue Op = BuildSDIV(N);
1913     if (Op.getNode()) return Op;
1914   }
1915
1916   // undef / X -> 0
1917   if (N0.getOpcode() == ISD::UNDEF)
1918     return DAG.getConstant(0, VT);
1919   // X / undef -> undef
1920   if (N1.getOpcode() == ISD::UNDEF)
1921     return N1;
1922
1923   return SDValue();
1924 }
1925
1926 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1927   SDValue N0 = N->getOperand(0);
1928   SDValue N1 = N->getOperand(1);
1929   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1930   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1931   EVT VT = N->getValueType(0);
1932
1933   // fold vector ops
1934   if (VT.isVector()) {
1935     SDValue FoldedVOp = SimplifyVBinOp(N);
1936     if (FoldedVOp.getNode()) return FoldedVOp;
1937   }
1938
1939   // fold (udiv c1, c2) -> c1/c2
1940   if (N0C && N1C && !N1C->isNullValue())
1941     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1942   // fold (udiv x, (1 << c)) -> x >>u c
1943   if (N1C && N1C->getAPIntValue().isPowerOf2())
1944     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1945                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1946                                        getShiftAmountTy(N0.getValueType())));
1947   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1948   if (N1.getOpcode() == ISD::SHL) {
1949     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1950       if (SHC->getAPIntValue().isPowerOf2()) {
1951         EVT ADDVT = N1.getOperand(1).getValueType();
1952         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1953                                   N1.getOperand(1),
1954                                   DAG.getConstant(SHC->getAPIntValue()
1955                                                                   .logBase2(),
1956                                                   ADDVT));
1957         AddToWorkList(Add.getNode());
1958         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1959       }
1960     }
1961   }
1962   // fold (udiv x, c) -> alternate
1963   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1964     SDValue Op = BuildUDIV(N);
1965     if (Op.getNode()) return Op;
1966   }
1967
1968   // undef / X -> 0
1969   if (N0.getOpcode() == ISD::UNDEF)
1970     return DAG.getConstant(0, VT);
1971   // X / undef -> undef
1972   if (N1.getOpcode() == ISD::UNDEF)
1973     return N1;
1974
1975   return SDValue();
1976 }
1977
1978 SDValue DAGCombiner::visitSREM(SDNode *N) {
1979   SDValue N0 = N->getOperand(0);
1980   SDValue N1 = N->getOperand(1);
1981   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1982   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1983   EVT VT = N->getValueType(0);
1984
1985   // fold (srem c1, c2) -> c1%c2
1986   if (N0C && N1C && !N1C->isNullValue())
1987     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1988   // If we know the sign bits of both operands are zero, strength reduce to a
1989   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1990   if (!VT.isVector()) {
1991     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1992       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1993   }
1994
1995   // If X/C can be simplified by the division-by-constant logic, lower
1996   // X%C to the equivalent of X-X/C*C.
1997   if (N1C && !N1C->isNullValue()) {
1998     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1999     AddToWorkList(Div.getNode());
2000     SDValue OptimizedDiv = combine(Div.getNode());
2001     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2002       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2003                                 OptimizedDiv, N1);
2004       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2005       AddToWorkList(Mul.getNode());
2006       return Sub;
2007     }
2008   }
2009
2010   // undef % X -> 0
2011   if (N0.getOpcode() == ISD::UNDEF)
2012     return DAG.getConstant(0, VT);
2013   // X % undef -> undef
2014   if (N1.getOpcode() == ISD::UNDEF)
2015     return N1;
2016
2017   return SDValue();
2018 }
2019
2020 SDValue DAGCombiner::visitUREM(SDNode *N) {
2021   SDValue N0 = N->getOperand(0);
2022   SDValue N1 = N->getOperand(1);
2023   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2024   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2025   EVT VT = N->getValueType(0);
2026
2027   // fold (urem c1, c2) -> c1%c2
2028   if (N0C && N1C && !N1C->isNullValue())
2029     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2030   // fold (urem x, pow2) -> (and x, pow2-1)
2031   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2032     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2033                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2034   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2035   if (N1.getOpcode() == ISD::SHL) {
2036     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2037       if (SHC->getAPIntValue().isPowerOf2()) {
2038         SDValue Add =
2039           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2040                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2041                                  VT));
2042         AddToWorkList(Add.getNode());
2043         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2044       }
2045     }
2046   }
2047
2048   // If X/C can be simplified by the division-by-constant logic, lower
2049   // X%C to the equivalent of X-X/C*C.
2050   if (N1C && !N1C->isNullValue()) {
2051     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2052     AddToWorkList(Div.getNode());
2053     SDValue OptimizedDiv = combine(Div.getNode());
2054     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2055       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2056                                 OptimizedDiv, N1);
2057       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2058       AddToWorkList(Mul.getNode());
2059       return Sub;
2060     }
2061   }
2062
2063   // undef % X -> 0
2064   if (N0.getOpcode() == ISD::UNDEF)
2065     return DAG.getConstant(0, VT);
2066   // X % undef -> undef
2067   if (N1.getOpcode() == ISD::UNDEF)
2068     return N1;
2069
2070   return SDValue();
2071 }
2072
2073 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2074   SDValue N0 = N->getOperand(0);
2075   SDValue N1 = N->getOperand(1);
2076   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2077   EVT VT = N->getValueType(0);
2078   DebugLoc DL = N->getDebugLoc();
2079
2080   // fold (mulhs x, 0) -> 0
2081   if (N1C && N1C->isNullValue())
2082     return N1;
2083   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2084   if (N1C && N1C->getAPIntValue() == 1)
2085     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2086                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2087                                        getShiftAmountTy(N0.getValueType())));
2088   // fold (mulhs x, undef) -> 0
2089   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2090     return DAG.getConstant(0, VT);
2091
2092   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2093   // plus a shift.
2094   if (VT.isSimple() && !VT.isVector()) {
2095     MVT Simple = VT.getSimpleVT();
2096     unsigned SimpleSize = Simple.getSizeInBits();
2097     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2098     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2099       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2100       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2101       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2102       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2103             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2104       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2105     }
2106   }
2107
2108   return SDValue();
2109 }
2110
2111 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2112   SDValue N0 = N->getOperand(0);
2113   SDValue N1 = N->getOperand(1);
2114   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2115   EVT VT = N->getValueType(0);
2116   DebugLoc DL = N->getDebugLoc();
2117
2118   // fold (mulhu x, 0) -> 0
2119   if (N1C && N1C->isNullValue())
2120     return N1;
2121   // fold (mulhu x, 1) -> 0
2122   if (N1C && N1C->getAPIntValue() == 1)
2123     return DAG.getConstant(0, N0.getValueType());
2124   // fold (mulhu x, undef) -> 0
2125   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2126     return DAG.getConstant(0, VT);
2127
2128   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2129   // plus a shift.
2130   if (VT.isSimple() && !VT.isVector()) {
2131     MVT Simple = VT.getSimpleVT();
2132     unsigned SimpleSize = Simple.getSizeInBits();
2133     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2134     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2135       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2136       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2137       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2138       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2139             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2140       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2141     }
2142   }
2143
2144   return SDValue();
2145 }
2146
2147 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2148 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2149 /// that are being performed. Return true if a simplification was made.
2150 ///
2151 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2152                                                 unsigned HiOp) {
2153   // If the high half is not needed, just compute the low half.
2154   bool HiExists = N->hasAnyUseOfValue(1);
2155   if (!HiExists &&
2156       (!LegalOperations ||
2157        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2158     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2159                               N->op_begin(), N->getNumOperands());
2160     return CombineTo(N, Res, Res);
2161   }
2162
2163   // If the low half is not needed, just compute the high half.
2164   bool LoExists = N->hasAnyUseOfValue(0);
2165   if (!LoExists &&
2166       (!LegalOperations ||
2167        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2168     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2169                               N->op_begin(), N->getNumOperands());
2170     return CombineTo(N, Res, Res);
2171   }
2172
2173   // If both halves are used, return as it is.
2174   if (LoExists && HiExists)
2175     return SDValue();
2176
2177   // If the two computed results can be simplified separately, separate them.
2178   if (LoExists) {
2179     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2180                              N->op_begin(), N->getNumOperands());
2181     AddToWorkList(Lo.getNode());
2182     SDValue LoOpt = combine(Lo.getNode());
2183     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2184         (!LegalOperations ||
2185          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2186       return CombineTo(N, LoOpt, LoOpt);
2187   }
2188
2189   if (HiExists) {
2190     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2191                              N->op_begin(), N->getNumOperands());
2192     AddToWorkList(Hi.getNode());
2193     SDValue HiOpt = combine(Hi.getNode());
2194     if (HiOpt.getNode() && HiOpt != Hi &&
2195         (!LegalOperations ||
2196          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2197       return CombineTo(N, HiOpt, HiOpt);
2198   }
2199
2200   return SDValue();
2201 }
2202
2203 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2204   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2205   if (Res.getNode()) return Res;
2206
2207   EVT VT = N->getValueType(0);
2208   DebugLoc DL = N->getDebugLoc();
2209
2210   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2211   // plus a shift.
2212   if (VT.isSimple() && !VT.isVector()) {
2213     MVT Simple = VT.getSimpleVT();
2214     unsigned SimpleSize = Simple.getSizeInBits();
2215     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2216     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2217       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2218       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2219       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2220       // Compute the high part as N1.
2221       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2222             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2223       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2224       // Compute the low part as N0.
2225       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2226       return CombineTo(N, Lo, Hi);
2227     }
2228   }
2229
2230   return SDValue();
2231 }
2232
2233 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2234   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2235   if (Res.getNode()) return Res;
2236
2237   EVT VT = N->getValueType(0);
2238   DebugLoc DL = N->getDebugLoc();
2239
2240   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2241   // plus a shift.
2242   if (VT.isSimple() && !VT.isVector()) {
2243     MVT Simple = VT.getSimpleVT();
2244     unsigned SimpleSize = Simple.getSizeInBits();
2245     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2246     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2247       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2248       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2249       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2250       // Compute the high part as N1.
2251       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2252             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2253       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2254       // Compute the low part as N0.
2255       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2256       return CombineTo(N, Lo, Hi);
2257     }
2258   }
2259
2260   return SDValue();
2261 }
2262
2263 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2264   // (smulo x, 2) -> (saddo x, x)
2265   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2266     if (C2->getAPIntValue() == 2)
2267       return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2268                          N->getOperand(0), N->getOperand(0));
2269
2270   return SDValue();
2271 }
2272
2273 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2274   // (umulo x, 2) -> (uaddo x, x)
2275   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2276     if (C2->getAPIntValue() == 2)
2277       return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2278                          N->getOperand(0), N->getOperand(0));
2279
2280   return SDValue();
2281 }
2282
2283 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2284   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2285   if (Res.getNode()) return Res;
2286
2287   return SDValue();
2288 }
2289
2290 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2291   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2292   if (Res.getNode()) return Res;
2293
2294   return SDValue();
2295 }
2296
2297 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2298 /// two operands of the same opcode, try to simplify it.
2299 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2300   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2301   EVT VT = N0.getValueType();
2302   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2303
2304   // Bail early if none of these transforms apply.
2305   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2306
2307   // For each of OP in AND/OR/XOR:
2308   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2309   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2310   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2311   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2312   //
2313   // do not sink logical op inside of a vector extend, since it may combine
2314   // into a vsetcc.
2315   EVT Op0VT = N0.getOperand(0).getValueType();
2316   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2317        N0.getOpcode() == ISD::SIGN_EXTEND ||
2318        // Avoid infinite looping with PromoteIntBinOp.
2319        (N0.getOpcode() == ISD::ANY_EXTEND &&
2320         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2321        (N0.getOpcode() == ISD::TRUNCATE &&
2322         (!TLI.isZExtFree(VT, Op0VT) ||
2323          !TLI.isTruncateFree(Op0VT, VT)) &&
2324         TLI.isTypeLegal(Op0VT))) &&
2325       !VT.isVector() &&
2326       Op0VT == N1.getOperand(0).getValueType() &&
2327       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2328     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2329                                  N0.getOperand(0).getValueType(),
2330                                  N0.getOperand(0), N1.getOperand(0));
2331     AddToWorkList(ORNode.getNode());
2332     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2333   }
2334
2335   // For each of OP in SHL/SRL/SRA/AND...
2336   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2337   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2338   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2339   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2340        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2341       N0.getOperand(1) == N1.getOperand(1)) {
2342     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2343                                  N0.getOperand(0).getValueType(),
2344                                  N0.getOperand(0), N1.getOperand(0));
2345     AddToWorkList(ORNode.getNode());
2346     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2347                        ORNode, N0.getOperand(1));
2348   }
2349
2350   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2351   // Only perform this optimization after type legalization and before
2352   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2353   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2354   // we don't want to undo this promotion.
2355   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2356   // on scalars.
2357   if ((N0.getOpcode() == ISD::BITCAST ||
2358        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2359       Level == AfterLegalizeTypes) {
2360     SDValue In0 = N0.getOperand(0);
2361     SDValue In1 = N1.getOperand(0);
2362     EVT In0Ty = In0.getValueType();
2363     EVT In1Ty = In1.getValueType();
2364     DebugLoc DL = N->getDebugLoc();
2365     // If both incoming values are integers, and the original types are the
2366     // same.
2367     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2368       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2369       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2370       AddToWorkList(Op.getNode());
2371       return BC;
2372     }
2373   }
2374
2375   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2376   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2377   // If both shuffles use the same mask, and both shuffle within a single
2378   // vector, then it is worthwhile to move the swizzle after the operation.
2379   // The type-legalizer generates this pattern when loading illegal
2380   // vector types from memory. In many cases this allows additional shuffle
2381   // optimizations.
2382   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2383       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2384       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2385     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2386     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2387
2388     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2389            "Inputs to shuffles are not the same type");
2390
2391     unsigned NumElts = VT.getVectorNumElements();
2392
2393     // Check that both shuffles use the same mask. The masks are known to be of
2394     // the same length because the result vector type is the same.
2395     bool SameMask = true;
2396     for (unsigned i = 0; i != NumElts; ++i) {
2397       int Idx0 = SVN0->getMaskElt(i);
2398       int Idx1 = SVN1->getMaskElt(i);
2399       if (Idx0 != Idx1) {
2400         SameMask = false;
2401         break;
2402       }
2403     }
2404
2405     if (SameMask) {
2406       SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2407                                N0.getOperand(0), N1.getOperand(0));
2408       AddToWorkList(Op.getNode());
2409       return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2410                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2411     }
2412   }
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitAND(SDNode *N) {
2418   SDValue N0 = N->getOperand(0);
2419   SDValue N1 = N->getOperand(1);
2420   SDValue LL, LR, RL, RR, CC0, CC1;
2421   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2422   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2423   EVT VT = N1.getValueType();
2424   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2425
2426   // fold vector ops
2427   if (VT.isVector()) {
2428     SDValue FoldedVOp = SimplifyVBinOp(N);
2429     if (FoldedVOp.getNode()) return FoldedVOp;
2430   }
2431
2432   // fold (and x, undef) -> 0
2433   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2434     return DAG.getConstant(0, VT);
2435   // fold (and c1, c2) -> c1&c2
2436   if (N0C && N1C)
2437     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2438   // canonicalize constant to RHS
2439   if (N0C && !N1C)
2440     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2441   // fold (and x, -1) -> x
2442   if (N1C && N1C->isAllOnesValue())
2443     return N0;
2444   // if (and x, c) is known to be zero, return 0
2445   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2446                                    APInt::getAllOnesValue(BitWidth)))
2447     return DAG.getConstant(0, VT);
2448   // reassociate and
2449   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2450   if (RAND.getNode() != 0)
2451     return RAND;
2452   // fold (and (or x, C), D) -> D if (C & D) == D
2453   if (N1C && N0.getOpcode() == ISD::OR)
2454     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2455       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2456         return N1;
2457   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2458   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2459     SDValue N0Op0 = N0.getOperand(0);
2460     APInt Mask = ~N1C->getAPIntValue();
2461     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2462     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2463       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2464                                  N0.getValueType(), N0Op0);
2465
2466       // Replace uses of the AND with uses of the Zero extend node.
2467       CombineTo(N, Zext);
2468
2469       // We actually want to replace all uses of the any_extend with the
2470       // zero_extend, to avoid duplicating things.  This will later cause this
2471       // AND to be folded.
2472       CombineTo(N0.getNode(), Zext);
2473       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2474     }
2475   }
2476   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 
2477   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2478   // already be zero by virtue of the width of the base type of the load.
2479   //
2480   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2481   // more cases.
2482   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2483        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2484       N0.getOpcode() == ISD::LOAD) {
2485     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2486                                          N0 : N0.getOperand(0) );
2487
2488     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2489     // This can be a pure constant or a vector splat, in which case we treat the
2490     // vector as a scalar and use the splat value.
2491     APInt Constant = APInt::getNullValue(1);
2492     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2493       Constant = C->getAPIntValue();
2494     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2495       APInt SplatValue, SplatUndef;
2496       unsigned SplatBitSize;
2497       bool HasAnyUndefs;
2498       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2499                                              SplatBitSize, HasAnyUndefs);
2500       if (IsSplat) {
2501         // Undef bits can contribute to a possible optimisation if set, so
2502         // set them.
2503         SplatValue |= SplatUndef;
2504
2505         // The splat value may be something like "0x00FFFFFF", which means 0 for
2506         // the first vector value and FF for the rest, repeating. We need a mask
2507         // that will apply equally to all members of the vector, so AND all the
2508         // lanes of the constant together.
2509         EVT VT = Vector->getValueType(0);
2510         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2511
2512         // If the splat value has been compressed to a bitlength lower
2513         // than the size of the vector lane, we need to re-expand it to
2514         // the lane size.
2515         if (BitWidth > SplatBitSize)
2516           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2517                SplatBitSize < BitWidth;
2518                SplatBitSize = SplatBitSize * 2)
2519             SplatValue |= SplatValue.shl(SplatBitSize);
2520
2521         Constant = APInt::getAllOnesValue(BitWidth);
2522         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2523           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2524       }
2525     }
2526
2527     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2528     // actually legal and isn't going to get expanded, else this is a false
2529     // optimisation.
2530     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2531                                                     Load->getMemoryVT());
2532
2533     // Resize the constant to the same size as the original memory access before
2534     // extension. If it is still the AllOnesValue then this AND is completely
2535     // unneeded.
2536     Constant =
2537       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2538
2539     bool B;
2540     switch (Load->getExtensionType()) {
2541     default: B = false; break;
2542     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2543     case ISD::ZEXTLOAD:
2544     case ISD::NON_EXTLOAD: B = true; break;
2545     }
2546
2547     if (B && Constant.isAllOnesValue()) {
2548       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2549       // preserve semantics once we get rid of the AND.
2550       SDValue NewLoad(Load, 0);
2551       if (Load->getExtensionType() == ISD::EXTLOAD) {
2552         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2553                               Load->getValueType(0), Load->getDebugLoc(),
2554                               Load->getChain(), Load->getBasePtr(),
2555                               Load->getOffset(), Load->getMemoryVT(),
2556                               Load->getMemOperand());
2557         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2558         if (Load->getNumValues() == 3) {
2559           // PRE/POST_INC loads have 3 values.
2560           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2561                            NewLoad.getValue(2) };
2562           CombineTo(Load, To, 3, true);
2563         } else {
2564           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2565         }
2566       }
2567
2568       // Fold the AND away, taking care not to fold to the old load node if we
2569       // replaced it.
2570       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2571
2572       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2573     }
2574   }
2575   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2576   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2577     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2578     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2579
2580     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2581         LL.getValueType().isInteger()) {
2582       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2583       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2584         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2585                                      LR.getValueType(), LL, RL);
2586         AddToWorkList(ORNode.getNode());
2587         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2588       }
2589       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2590       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2591         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2592                                       LR.getValueType(), LL, RL);
2593         AddToWorkList(ANDNode.getNode());
2594         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2595       }
2596       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2597       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2598         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2599                                      LR.getValueType(), LL, RL);
2600         AddToWorkList(ORNode.getNode());
2601         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2602       }
2603     }
2604     // canonicalize equivalent to ll == rl
2605     if (LL == RR && LR == RL) {
2606       Op1 = ISD::getSetCCSwappedOperands(Op1);
2607       std::swap(RL, RR);
2608     }
2609     if (LL == RL && LR == RR) {
2610       bool isInteger = LL.getValueType().isInteger();
2611       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2612       if (Result != ISD::SETCC_INVALID &&
2613           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2614         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2615                             LL, LR, Result);
2616     }
2617   }
2618
2619   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2620   if (N0.getOpcode() == N1.getOpcode()) {
2621     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2622     if (Tmp.getNode()) return Tmp;
2623   }
2624
2625   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2626   // fold (and (sra)) -> (and (srl)) when possible.
2627   if (!VT.isVector() &&
2628       SimplifyDemandedBits(SDValue(N, 0)))
2629     return SDValue(N, 0);
2630
2631   // fold (zext_inreg (extload x)) -> (zextload x)
2632   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2633     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2634     EVT MemVT = LN0->getMemoryVT();
2635     // If we zero all the possible extended bits, then we can turn this into
2636     // a zextload if we are running before legalize or the operation is legal.
2637     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2638     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2639                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2640         ((!LegalOperations && !LN0->isVolatile()) ||
2641          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2642       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2643                                        LN0->getChain(), LN0->getBasePtr(),
2644                                        LN0->getPointerInfo(), MemVT,
2645                                        LN0->isVolatile(), LN0->isNonTemporal(),
2646                                        LN0->getAlignment());
2647       AddToWorkList(N);
2648       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2649       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2650     }
2651   }
2652   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2653   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2654       N0.hasOneUse()) {
2655     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2656     EVT MemVT = LN0->getMemoryVT();
2657     // If we zero all the possible extended bits, then we can turn this into
2658     // a zextload if we are running before legalize or the operation is legal.
2659     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2660     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2661                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2662         ((!LegalOperations && !LN0->isVolatile()) ||
2663          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2664       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2665                                        LN0->getChain(),
2666                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2667                                        MemVT,
2668                                        LN0->isVolatile(), LN0->isNonTemporal(),
2669                                        LN0->getAlignment());
2670       AddToWorkList(N);
2671       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2672       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2673     }
2674   }
2675
2676   // fold (and (load x), 255) -> (zextload x, i8)
2677   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2678   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2679   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2680               (N0.getOpcode() == ISD::ANY_EXTEND &&
2681                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2682     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2683     LoadSDNode *LN0 = HasAnyExt
2684       ? cast<LoadSDNode>(N0.getOperand(0))
2685       : cast<LoadSDNode>(N0);
2686     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2687         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2688       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2689       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2690         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2691         EVT LoadedVT = LN0->getMemoryVT();
2692
2693         if (ExtVT == LoadedVT &&
2694             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2695           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2696
2697           SDValue NewLoad =
2698             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2699                            LN0->getChain(), LN0->getBasePtr(),
2700                            LN0->getPointerInfo(),
2701                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2702                            LN0->getAlignment());
2703           AddToWorkList(N);
2704           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2705           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2706         }
2707
2708         // Do not change the width of a volatile load.
2709         // Do not generate loads of non-round integer types since these can
2710         // be expensive (and would be wrong if the type is not byte sized).
2711         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2712             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2713           EVT PtrType = LN0->getOperand(1).getValueType();
2714
2715           unsigned Alignment = LN0->getAlignment();
2716           SDValue NewPtr = LN0->getBasePtr();
2717
2718           // For big endian targets, we need to add an offset to the pointer
2719           // to load the correct bytes.  For little endian systems, we merely
2720           // need to read fewer bytes from the same pointer.
2721           if (TLI.isBigEndian()) {
2722             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2723             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2724             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2725             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2726                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2727             Alignment = MinAlign(Alignment, PtrOff);
2728           }
2729
2730           AddToWorkList(NewPtr.getNode());
2731
2732           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2733           SDValue Load =
2734             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2735                            LN0->getChain(), NewPtr,
2736                            LN0->getPointerInfo(),
2737                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2738                            Alignment);
2739           AddToWorkList(N);
2740           CombineTo(LN0, Load, Load.getValue(1));
2741           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2742         }
2743       }
2744     }
2745   }
2746
2747   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2748       VT.getSizeInBits() <= 64) {
2749     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2750       APInt ADDC = ADDI->getAPIntValue();
2751       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2752         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2753         // immediate for an add, but it is legal if its top c2 bits are set,
2754         // transform the ADD so the immediate doesn't need to be materialized
2755         // in a register.
2756         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2757           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2758                                              SRLI->getZExtValue());
2759           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2760             ADDC |= Mask;
2761             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2762               SDValue NewAdd =
2763                 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2764                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2765               CombineTo(N0.getNode(), NewAdd);
2766               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2767             }
2768           }
2769         }
2770       }
2771     }
2772   }
2773       
2774
2775   return SDValue();
2776 }
2777
2778 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2779 ///
2780 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2781                                         bool DemandHighBits) {
2782   if (!LegalOperations)
2783     return SDValue();
2784
2785   EVT VT = N->getValueType(0);
2786   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2787     return SDValue();
2788   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2789     return SDValue();
2790
2791   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2792   bool LookPassAnd0 = false;
2793   bool LookPassAnd1 = false;
2794   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2795       std::swap(N0, N1);
2796   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2797       std::swap(N0, N1);
2798   if (N0.getOpcode() == ISD::AND) {
2799     if (!N0.getNode()->hasOneUse())
2800       return SDValue();
2801     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2802     if (!N01C || N01C->getZExtValue() != 0xFF00)
2803       return SDValue();
2804     N0 = N0.getOperand(0);
2805     LookPassAnd0 = true;
2806   }
2807
2808   if (N1.getOpcode() == ISD::AND) {
2809     if (!N1.getNode()->hasOneUse())
2810       return SDValue();
2811     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2812     if (!N11C || N11C->getZExtValue() != 0xFF)
2813       return SDValue();
2814     N1 = N1.getOperand(0);
2815     LookPassAnd1 = true;
2816   }
2817
2818   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2819     std::swap(N0, N1);
2820   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2821     return SDValue();
2822   if (!N0.getNode()->hasOneUse() ||
2823       !N1.getNode()->hasOneUse())
2824     return SDValue();
2825
2826   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2827   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2828   if (!N01C || !N11C)
2829     return SDValue();
2830   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2831     return SDValue();
2832
2833   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2834   SDValue N00 = N0->getOperand(0);
2835   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2836     if (!N00.getNode()->hasOneUse())
2837       return SDValue();
2838     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2839     if (!N001C || N001C->getZExtValue() != 0xFF)
2840       return SDValue();
2841     N00 = N00.getOperand(0);
2842     LookPassAnd0 = true;
2843   }
2844
2845   SDValue N10 = N1->getOperand(0);
2846   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2847     if (!N10.getNode()->hasOneUse())
2848       return SDValue();
2849     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2850     if (!N101C || N101C->getZExtValue() != 0xFF00)
2851       return SDValue();
2852     N10 = N10.getOperand(0);
2853     LookPassAnd1 = true;
2854   }
2855
2856   if (N00 != N10)
2857     return SDValue();
2858
2859   // Make sure everything beyond the low halfword is zero since the SRL 16
2860   // will clear the top bits.
2861   unsigned OpSizeInBits = VT.getSizeInBits();
2862   if (DemandHighBits && OpSizeInBits > 16 &&
2863       (!LookPassAnd0 || !LookPassAnd1) &&
2864       !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2865     return SDValue();
2866
2867   SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2868   if (OpSizeInBits > 16)
2869     Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2870                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2871   return Res;
2872 }
2873
2874 /// isBSwapHWordElement - Return true if the specified node is an element
2875 /// that makes up a 32-bit packed halfword byteswap. i.e.
2876 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2877 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2878   if (!N.getNode()->hasOneUse())
2879     return false;
2880
2881   unsigned Opc = N.getOpcode();
2882   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2883     return false;
2884
2885   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2886   if (!N1C)
2887     return false;
2888
2889   unsigned Num;
2890   switch (N1C->getZExtValue()) {
2891   default:
2892     return false;
2893   case 0xFF:       Num = 0; break;
2894   case 0xFF00:     Num = 1; break;
2895   case 0xFF0000:   Num = 2; break;
2896   case 0xFF000000: Num = 3; break;
2897   }
2898
2899   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2900   SDValue N0 = N.getOperand(0);
2901   if (Opc == ISD::AND) {
2902     if (Num == 0 || Num == 2) {
2903       // (x >> 8) & 0xff
2904       // (x >> 8) & 0xff0000
2905       if (N0.getOpcode() != ISD::SRL)
2906         return false;
2907       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2908       if (!C || C->getZExtValue() != 8)
2909         return false;
2910     } else {
2911       // (x << 8) & 0xff00
2912       // (x << 8) & 0xff000000
2913       if (N0.getOpcode() != ISD::SHL)
2914         return false;
2915       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2916       if (!C || C->getZExtValue() != 8)
2917         return false;
2918     }
2919   } else if (Opc == ISD::SHL) {
2920     // (x & 0xff) << 8
2921     // (x & 0xff0000) << 8
2922     if (Num != 0 && Num != 2)
2923       return false;
2924     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2925     if (!C || C->getZExtValue() != 8)
2926       return false;
2927   } else { // Opc == ISD::SRL
2928     // (x & 0xff00) >> 8
2929     // (x & 0xff000000) >> 8
2930     if (Num != 1 && Num != 3)
2931       return false;
2932     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2933     if (!C || C->getZExtValue() != 8)
2934       return false;
2935   }
2936
2937   if (Parts[Num])
2938     return false;
2939
2940   Parts[Num] = N0.getOperand(0).getNode();
2941   return true;
2942 }
2943
2944 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2945 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2946 /// => (rotl (bswap x), 16)
2947 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2948   if (!LegalOperations)
2949     return SDValue();
2950
2951   EVT VT = N->getValueType(0);
2952   if (VT != MVT::i32)
2953     return SDValue();
2954   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2955     return SDValue();
2956
2957   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2958   // Look for either
2959   // (or (or (and), (and)), (or (and), (and)))
2960   // (or (or (or (and), (and)), (and)), (and))
2961   if (N0.getOpcode() != ISD::OR)
2962     return SDValue();
2963   SDValue N00 = N0.getOperand(0);
2964   SDValue N01 = N0.getOperand(1);
2965
2966   if (N1.getOpcode() == ISD::OR) {
2967     // (or (or (and), (and)), (or (and), (and)))
2968     SDValue N000 = N00.getOperand(0);
2969     if (!isBSwapHWordElement(N000, Parts))
2970       return SDValue();
2971
2972     SDValue N001 = N00.getOperand(1);
2973     if (!isBSwapHWordElement(N001, Parts))
2974       return SDValue();
2975     SDValue N010 = N01.getOperand(0);
2976     if (!isBSwapHWordElement(N010, Parts))
2977       return SDValue();
2978     SDValue N011 = N01.getOperand(1);
2979     if (!isBSwapHWordElement(N011, Parts))
2980       return SDValue();
2981   } else {
2982     // (or (or (or (and), (and)), (and)), (and))
2983     if (!isBSwapHWordElement(N1, Parts))
2984       return SDValue();
2985     if (!isBSwapHWordElement(N01, Parts))
2986       return SDValue();
2987     if (N00.getOpcode() != ISD::OR)
2988       return SDValue();
2989     SDValue N000 = N00.getOperand(0);
2990     if (!isBSwapHWordElement(N000, Parts))
2991       return SDValue();
2992     SDValue N001 = N00.getOperand(1);
2993     if (!isBSwapHWordElement(N001, Parts))
2994       return SDValue();
2995   }
2996
2997   // Make sure the parts are all coming from the same node.
2998   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2999     return SDValue();
3000
3001   SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
3002                               SDValue(Parts[0],0));
3003
3004   // Result of the bswap should be rotated by 16. If it's not legal, than
3005   // do  (x << 16) | (x >> 16).
3006   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3007   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3008     return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
3009   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3010     return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
3011   return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
3012                      DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
3013                      DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
3014 }
3015
3016 SDValue DAGCombiner::visitOR(SDNode *N) {
3017   SDValue N0 = N->getOperand(0);
3018   SDValue N1 = N->getOperand(1);
3019   SDValue LL, LR, RL, RR, CC0, CC1;
3020   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3021   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3022   EVT VT = N1.getValueType();
3023
3024   // fold vector ops
3025   if (VT.isVector()) {
3026     SDValue FoldedVOp = SimplifyVBinOp(N);
3027     if (FoldedVOp.getNode()) return FoldedVOp;
3028   }
3029
3030   // fold (or x, undef) -> -1
3031   if (!LegalOperations &&
3032       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3033     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3034     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3035   }
3036   // fold (or c1, c2) -> c1|c2
3037   if (N0C && N1C)
3038     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3039   // canonicalize constant to RHS
3040   if (N0C && !N1C)
3041     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3042   // fold (or x, 0) -> x
3043   if (N1C && N1C->isNullValue())
3044     return N0;
3045   // fold (or x, -1) -> -1
3046   if (N1C && N1C->isAllOnesValue())
3047     return N1;
3048   // fold (or x, c) -> c iff (x & ~c) == 0
3049   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3050     return N1;
3051
3052   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3053   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3054   if (BSwap.getNode() != 0)
3055     return BSwap;
3056   BSwap = MatchBSwapHWordLow(N, N0, N1);
3057   if (BSwap.getNode() != 0)
3058     return BSwap;
3059
3060   // reassociate or
3061   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3062   if (ROR.getNode() != 0)
3063     return ROR;
3064   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3065   // iff (c1 & c2) == 0.
3066   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3067              isa<ConstantSDNode>(N0.getOperand(1))) {
3068     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3069     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3070       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3071                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3072                                      N0.getOperand(0), N1),
3073                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3074   }
3075   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3076   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3077     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3078     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3079
3080     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3081         LL.getValueType().isInteger()) {
3082       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3083       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3084       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3085           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3086         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3087                                      LR.getValueType(), LL, RL);
3088         AddToWorkList(ORNode.getNode());
3089         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3090       }
3091       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3092       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3093       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3094           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3095         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3096                                       LR.getValueType(), LL, RL);
3097         AddToWorkList(ANDNode.getNode());
3098         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3099       }
3100     }
3101     // canonicalize equivalent to ll == rl
3102     if (LL == RR && LR == RL) {
3103       Op1 = ISD::getSetCCSwappedOperands(Op1);
3104       std::swap(RL, RR);
3105     }
3106     if (LL == RL && LR == RR) {
3107       bool isInteger = LL.getValueType().isInteger();
3108       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3109       if (Result != ISD::SETCC_INVALID &&
3110           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
3111         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3112                             LL, LR, Result);
3113     }
3114   }
3115
3116   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3117   if (N0.getOpcode() == N1.getOpcode()) {
3118     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3119     if (Tmp.getNode()) return Tmp;
3120   }
3121
3122   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3123   if (N0.getOpcode() == ISD::AND &&
3124       N1.getOpcode() == ISD::AND &&
3125       N0.getOperand(1).getOpcode() == ISD::Constant &&
3126       N1.getOperand(1).getOpcode() == ISD::Constant &&
3127       // Don't increase # computations.
3128       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3129     // We can only do this xform if we know that bits from X that are set in C2
3130     // but not in C1 are already zero.  Likewise for Y.
3131     const APInt &LHSMask =
3132       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3133     const APInt &RHSMask =
3134       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3135
3136     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3137         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3138       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3139                               N0.getOperand(0), N1.getOperand(0));
3140       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3141                          DAG.getConstant(LHSMask | RHSMask, VT));
3142     }
3143   }
3144
3145   // See if this is some rotate idiom.
3146   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3147     return SDValue(Rot, 0);
3148
3149   // Simplify the operands using demanded-bits information.
3150   if (!VT.isVector() &&
3151       SimplifyDemandedBits(SDValue(N, 0)))
3152     return SDValue(N, 0);
3153
3154   return SDValue();
3155 }
3156
3157 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3158 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3159   if (Op.getOpcode() == ISD::AND) {
3160     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3161       Mask = Op.getOperand(1);
3162       Op = Op.getOperand(0);
3163     } else {
3164       return false;
3165     }
3166   }
3167
3168   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3169     Shift = Op;
3170     return true;
3171   }
3172
3173   return false;
3174 }
3175
3176 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3177 // idioms for rotate, and if the target supports rotation instructions, generate
3178 // a rot[lr].
3179 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3180   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3181   EVT VT = LHS.getValueType();
3182   if (!TLI.isTypeLegal(VT)) return 0;
3183
3184   // The target must have at least one rotate flavor.
3185   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3186   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3187   if (!HasROTL && !HasROTR) return 0;
3188
3189   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3190   SDValue LHSShift;   // The shift.
3191   SDValue LHSMask;    // AND value if any.
3192   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3193     return 0; // Not part of a rotate.
3194
3195   SDValue RHSShift;   // The shift.
3196   SDValue RHSMask;    // AND value if any.
3197   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3198     return 0; // Not part of a rotate.
3199
3200   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3201     return 0;   // Not shifting the same value.
3202
3203   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3204     return 0;   // Shifts must disagree.
3205
3206   // Canonicalize shl to left side in a shl/srl pair.
3207   if (RHSShift.getOpcode() == ISD::SHL) {
3208     std::swap(LHS, RHS);
3209     std::swap(LHSShift, RHSShift);
3210     std::swap(LHSMask , RHSMask );
3211   }
3212
3213   unsigned OpSizeInBits = VT.getSizeInBits();
3214   SDValue LHSShiftArg = LHSShift.getOperand(0);
3215   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3216   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3217
3218   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3219   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3220   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3221       RHSShiftAmt.getOpcode() == ISD::Constant) {
3222     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3223     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3224     if ((LShVal + RShVal) != OpSizeInBits)
3225       return 0;
3226
3227     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3228                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3229
3230     // If there is an AND of either shifted operand, apply it to the result.
3231     if (LHSMask.getNode() || RHSMask.getNode()) {
3232       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3233
3234       if (LHSMask.getNode()) {
3235         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3236         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3237       }
3238       if (RHSMask.getNode()) {
3239         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3240         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3241       }
3242
3243       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3244     }
3245
3246     return Rot.getNode();
3247   }
3248
3249   // If there is a mask here, and we have a variable shift, we can't be sure
3250   // that we're masking out the right stuff.
3251   if (LHSMask.getNode() || RHSMask.getNode())
3252     return 0;
3253
3254   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3255   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3256   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3257       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3258     if (ConstantSDNode *SUBC =
3259           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3260       if (SUBC->getAPIntValue() == OpSizeInBits) {
3261         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3262                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3263       }
3264     }
3265   }
3266
3267   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3268   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3269   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3270       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3271     if (ConstantSDNode *SUBC =
3272           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3273       if (SUBC->getAPIntValue() == OpSizeInBits) {
3274         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3275                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3276       }
3277     }
3278   }
3279
3280   // Look for sign/zext/any-extended or truncate cases:
3281   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3282        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3283        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3284        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3285       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3286        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3287        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3288        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3289     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3290     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3291     if (RExtOp0.getOpcode() == ISD::SUB &&
3292         RExtOp0.getOperand(1) == LExtOp0) {
3293       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3294       //   (rotl x, y)
3295       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3296       //   (rotr x, (sub 32, y))
3297       if (ConstantSDNode *SUBC =
3298             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3299         if (SUBC->getAPIntValue() == OpSizeInBits) {
3300           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3301                              LHSShiftArg,
3302                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3303         }
3304       }
3305     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3306                RExtOp0 == LExtOp0.getOperand(1)) {
3307       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3308       //   (rotr x, y)
3309       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3310       //   (rotl x, (sub 32, y))
3311       if (ConstantSDNode *SUBC =
3312             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3313         if (SUBC->getAPIntValue() == OpSizeInBits) {
3314           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3315                              LHSShiftArg,
3316                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3317         }
3318       }
3319     }
3320   }
3321
3322   return 0;
3323 }
3324
3325 SDValue DAGCombiner::visitXOR(SDNode *N) {
3326   SDValue N0 = N->getOperand(0);
3327   SDValue N1 = N->getOperand(1);
3328   SDValue LHS, RHS, CC;
3329   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3330   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3331   EVT VT = N0.getValueType();
3332
3333   // fold vector ops
3334   if (VT.isVector()) {
3335     SDValue FoldedVOp = SimplifyVBinOp(N);
3336     if (FoldedVOp.getNode()) return FoldedVOp;
3337   }
3338
3339   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3340   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3341     return DAG.getConstant(0, VT);
3342   // fold (xor x, undef) -> undef
3343   if (N0.getOpcode() == ISD::UNDEF)
3344     return N0;
3345   if (N1.getOpcode() == ISD::UNDEF)
3346     return N1;
3347   // fold (xor c1, c2) -> c1^c2
3348   if (N0C && N1C)
3349     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3350   // canonicalize constant to RHS
3351   if (N0C && !N1C)
3352     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3353   // fold (xor x, 0) -> x
3354   if (N1C && N1C->isNullValue())
3355     return N0;
3356   // reassociate xor
3357   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3358   if (RXOR.getNode() != 0)
3359     return RXOR;
3360
3361   // fold !(x cc y) -> (x !cc y)
3362   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3363     bool isInt = LHS.getValueType().isInteger();
3364     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3365                                                isInt);
3366
3367     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3368       switch (N0.getOpcode()) {
3369       default:
3370         llvm_unreachable("Unhandled SetCC Equivalent!");
3371       case ISD::SETCC:
3372         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3373       case ISD::SELECT_CC:
3374         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3375                                N0.getOperand(3), NotCC);
3376       }
3377     }
3378   }
3379
3380   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3381   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3382       N0.getNode()->hasOneUse() &&
3383       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3384     SDValue V = N0.getOperand(0);
3385     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3386                     DAG.getConstant(1, V.getValueType()));
3387     AddToWorkList(V.getNode());
3388     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3389   }
3390
3391   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3392   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3393       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3394     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3395     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3396       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3397       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3398       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3399       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3400       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3401     }
3402   }
3403   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3404   if (N1C && N1C->isAllOnesValue() &&
3405       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3406     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3407     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3408       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3409       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3410       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3411       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3412       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3413     }
3414   }
3415   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3416   if (N1C && N0.getOpcode() == ISD::XOR) {
3417     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3418     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3419     if (N00C)
3420       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3421                          DAG.getConstant(N1C->getAPIntValue() ^
3422                                          N00C->getAPIntValue(), VT));
3423     if (N01C)
3424       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3425                          DAG.getConstant(N1C->getAPIntValue() ^
3426                                          N01C->getAPIntValue(), VT));
3427   }
3428   // fold (xor x, x) -> 0
3429   if (N0 == N1)
3430     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3431
3432   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3433   if (N0.getOpcode() == N1.getOpcode()) {
3434     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3435     if (Tmp.getNode()) return Tmp;
3436   }
3437
3438   // Simplify the expression using non-local knowledge.
3439   if (!VT.isVector() &&
3440       SimplifyDemandedBits(SDValue(N, 0)))
3441     return SDValue(N, 0);
3442
3443   return SDValue();
3444 }
3445
3446 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3447 /// the shift amount is a constant.
3448 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3449   SDNode *LHS = N->getOperand(0).getNode();
3450   if (!LHS->hasOneUse()) return SDValue();
3451
3452   // We want to pull some binops through shifts, so that we have (and (shift))
3453   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3454   // thing happens with address calculations, so it's important to canonicalize
3455   // it.
3456   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3457
3458   switch (LHS->getOpcode()) {
3459   default: return SDValue();
3460   case ISD::OR:
3461   case ISD::XOR:
3462     HighBitSet = false; // We can only transform sra if the high bit is clear.
3463     break;
3464   case ISD::AND:
3465     HighBitSet = true;  // We can only transform sra if the high bit is set.
3466     break;
3467   case ISD::ADD:
3468     if (N->getOpcode() != ISD::SHL)
3469       return SDValue(); // only shl(add) not sr[al](add).
3470     HighBitSet = false; // We can only transform sra if the high bit is clear.
3471     break;
3472   }
3473
3474   // We require the RHS of the binop to be a constant as well.
3475   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3476   if (!BinOpCst) return SDValue();
3477
3478   // FIXME: disable this unless the input to the binop is a shift by a constant.
3479   // If it is not a shift, it pessimizes some common cases like:
3480   //
3481   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3482   //    int bar(int *X, int i) { return X[i & 255]; }
3483   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3484   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3485        BinOpLHSVal->getOpcode() != ISD::SRA &&
3486        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3487       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3488     return SDValue();
3489
3490   EVT VT = N->getValueType(0);
3491
3492   // If this is a signed shift right, and the high bit is modified by the
3493   // logical operation, do not perform the transformation. The highBitSet
3494   // boolean indicates the value of the high bit of the constant which would
3495   // cause it to be modified for this operation.
3496   if (N->getOpcode() == ISD::SRA) {
3497     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3498     if (BinOpRHSSignSet != HighBitSet)
3499       return SDValue();
3500   }
3501
3502   // Fold the constants, shifting the binop RHS by the shift amount.
3503   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3504                                N->getValueType(0),
3505                                LHS->getOperand(1), N->getOperand(1));
3506
3507   // Create the new shift.
3508   SDValue NewShift = DAG.getNode(N->getOpcode(),
3509                                  LHS->getOperand(0).getDebugLoc(),
3510                                  VT, LHS->getOperand(0), N->getOperand(1));
3511
3512   // Create the new binop.
3513   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3514 }
3515
3516 SDValue DAGCombiner::visitSHL(SDNode *N) {
3517   SDValue N0 = N->getOperand(0);
3518   SDValue N1 = N->getOperand(1);
3519   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3520   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3521   EVT VT = N0.getValueType();
3522   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3523
3524   // fold (shl c1, c2) -> c1<<c2
3525   if (N0C && N1C)
3526     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3527   // fold (shl 0, x) -> 0
3528   if (N0C && N0C->isNullValue())
3529     return N0;
3530   // fold (shl x, c >= size(x)) -> undef
3531   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3532     return DAG.getUNDEF(VT);
3533   // fold (shl x, 0) -> x
3534   if (N1C && N1C->isNullValue())
3535     return N0;
3536   // fold (shl undef, x) -> 0
3537   if (N0.getOpcode() == ISD::UNDEF)
3538     return DAG.getConstant(0, VT);
3539   // if (shl x, c) is known to be zero, return 0
3540   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3541                             APInt::getAllOnesValue(OpSizeInBits)))
3542     return DAG.getConstant(0, VT);
3543   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3544   if (N1.getOpcode() == ISD::TRUNCATE &&
3545       N1.getOperand(0).getOpcode() == ISD::AND &&
3546       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3547     SDValue N101 = N1.getOperand(0).getOperand(1);
3548     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3549       EVT TruncVT = N1.getValueType();
3550       SDValue N100 = N1.getOperand(0).getOperand(0);
3551       APInt TruncC = N101C->getAPIntValue();
3552       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3553       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3554                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3555                                      DAG.getNode(ISD::TRUNCATE,
3556                                                  N->getDebugLoc(),
3557                                                  TruncVT, N100),
3558                                      DAG.getConstant(TruncC, TruncVT)));
3559     }
3560   }
3561
3562   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3563     return SDValue(N, 0);
3564
3565   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3566   if (N1C && N0.getOpcode() == ISD::SHL &&
3567       N0.getOperand(1).getOpcode() == ISD::Constant) {
3568     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3569     uint64_t c2 = N1C->getZExtValue();
3570     if (c1 + c2 >= OpSizeInBits)
3571       return DAG.getConstant(0, VT);
3572     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3573                        DAG.getConstant(c1 + c2, N1.getValueType()));
3574   }
3575
3576   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3577   // For this to be valid, the second form must not preserve any of the bits
3578   // that are shifted out by the inner shift in the first form.  This means
3579   // the outer shift size must be >= the number of bits added by the ext.
3580   // As a corollary, we don't care what kind of ext it is.
3581   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3582               N0.getOpcode() == ISD::ANY_EXTEND ||
3583               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3584       N0.getOperand(0).getOpcode() == ISD::SHL &&
3585       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3586     uint64_t c1 =
3587       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3588     uint64_t c2 = N1C->getZExtValue();
3589     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3590     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3591     if (c2 >= OpSizeInBits - InnerShiftSize) {
3592       if (c1 + c2 >= OpSizeInBits)
3593         return DAG.getConstant(0, VT);
3594       return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3595                          DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3596                                      N0.getOperand(0)->getOperand(0)),
3597                          DAG.getConstant(c1 + c2, N1.getValueType()));
3598     }
3599   }
3600
3601   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3602   //                               (and (srl x, (sub c1, c2), MASK)
3603   // Only fold this if the inner shift has no other uses -- if it does, folding
3604   // this will increase the total number of instructions.
3605   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3606       N0.getOperand(1).getOpcode() == ISD::Constant) {
3607     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3608     if (c1 < VT.getSizeInBits()) {
3609       uint64_t c2 = N1C->getZExtValue();
3610       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3611                                          VT.getSizeInBits() - c1);
3612       SDValue Shift;
3613       if (c2 > c1) {
3614         Mask = Mask.shl(c2-c1);
3615         Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3616                             DAG.getConstant(c2-c1, N1.getValueType()));
3617       } else {
3618         Mask = Mask.lshr(c1-c2);
3619         Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3620                             DAG.getConstant(c1-c2, N1.getValueType()));
3621       }
3622       return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3623                          DAG.getConstant(Mask, VT));
3624     }
3625   }
3626   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3627   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3628     SDValue HiBitsMask =
3629       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3630                                             VT.getSizeInBits() -
3631                                               N1C->getZExtValue()),
3632                       VT);
3633     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3634                        HiBitsMask);
3635   }
3636
3637   if (N1C) {
3638     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3639     if (NewSHL.getNode())
3640       return NewSHL;
3641   }
3642
3643   return SDValue();
3644 }
3645
3646 SDValue DAGCombiner::visitSRA(SDNode *N) {
3647   SDValue N0 = N->getOperand(0);
3648   SDValue N1 = N->getOperand(1);
3649   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3650   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3651   EVT VT = N0.getValueType();
3652   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3653
3654   // fold (sra c1, c2) -> (sra c1, c2)
3655   if (N0C && N1C)
3656     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3657   // fold (sra 0, x) -> 0
3658   if (N0C && N0C->isNullValue())
3659     return N0;
3660   // fold (sra -1, x) -> -1
3661   if (N0C && N0C->isAllOnesValue())
3662     return N0;
3663   // fold (sra x, (setge c, size(x))) -> undef
3664   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3665     return DAG.getUNDEF(VT);
3666   // fold (sra x, 0) -> x
3667   if (N1C && N1C->isNullValue())
3668     return N0;
3669   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3670   // sext_inreg.
3671   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3672     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3673     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3674     if (VT.isVector())
3675       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3676                                ExtVT, VT.getVectorNumElements());
3677     if ((!LegalOperations ||
3678          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3679       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3680                          N0.getOperand(0), DAG.getValueType(ExtVT));
3681   }
3682
3683   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3684   if (N1C && N0.getOpcode() == ISD::SRA) {
3685     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3686       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3687       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3688       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3689                          DAG.getConstant(Sum, N1C->getValueType(0)));
3690     }
3691   }
3692
3693   // fold (sra (shl X, m), (sub result_size, n))
3694   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3695   // result_size - n != m.
3696   // If truncate is free for the target sext(shl) is likely to result in better
3697   // code.
3698   if (N0.getOpcode() == ISD::SHL) {
3699     // Get the two constanst of the shifts, CN0 = m, CN = n.
3700     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3701     if (N01C && N1C) {
3702       // Determine what the truncate's result bitsize and type would be.
3703       EVT TruncVT =
3704         EVT::getIntegerVT(*DAG.getContext(),
3705                           OpSizeInBits - N1C->getZExtValue());
3706       // Determine the residual right-shift amount.
3707       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3708
3709       // If the shift is not a no-op (in which case this should be just a sign
3710       // extend already), the truncated to type is legal, sign_extend is legal
3711       // on that type, and the truncate to that type is both legal and free,
3712       // perform the transform.
3713       if ((ShiftAmt > 0) &&
3714           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3715           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3716           TLI.isTruncateFree(VT, TruncVT)) {
3717
3718           SDValue Amt = DAG.getConstant(ShiftAmt,
3719               getShiftAmountTy(N0.getOperand(0).getValueType()));
3720           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3721                                       N0.getOperand(0), Amt);
3722           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3723                                       Shift);
3724           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3725                              N->getValueType(0), Trunc);
3726       }
3727     }
3728   }
3729
3730   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3731   if (N1.getOpcode() == ISD::TRUNCATE &&
3732       N1.getOperand(0).getOpcode() == ISD::AND &&
3733       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3734     SDValue N101 = N1.getOperand(0).getOperand(1);
3735     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3736       EVT TruncVT = N1.getValueType();
3737       SDValue N100 = N1.getOperand(0).getOperand(0);
3738       APInt TruncC = N101C->getAPIntValue();
3739       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3740       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3741                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3742                                      TruncVT,
3743                                      DAG.getNode(ISD::TRUNCATE,
3744                                                  N->getDebugLoc(),
3745                                                  TruncVT, N100),
3746                                      DAG.getConstant(TruncC, TruncVT)));
3747     }
3748   }
3749
3750   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3751   //      if c1 is equal to the number of bits the trunc removes
3752   if (N0.getOpcode() == ISD::TRUNCATE &&
3753       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3754        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3755       N0.getOperand(0).hasOneUse() &&
3756       N0.getOperand(0).getOperand(1).hasOneUse() &&
3757       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3758     EVT LargeVT = N0.getOperand(0).getValueType();
3759     ConstantSDNode *LargeShiftAmt =
3760       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3761
3762     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3763         LargeShiftAmt->getZExtValue()) {
3764       SDValue Amt =
3765         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3766               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3767       SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3768                                 N0.getOperand(0).getOperand(0), Amt);
3769       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3770     }
3771   }
3772
3773   // Simplify, based on bits shifted out of the LHS.
3774   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3775     return SDValue(N, 0);
3776
3777
3778   // If the sign bit is known to be zero, switch this to a SRL.
3779   if (DAG.SignBitIsZero(N0))
3780     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3781
3782   if (N1C) {
3783     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3784     if (NewSRA.getNode())
3785       return NewSRA;
3786   }
3787
3788   return SDValue();
3789 }
3790
3791 SDValue DAGCombiner::visitSRL(SDNode *N) {
3792   SDValue N0 = N->getOperand(0);
3793   SDValue N1 = N->getOperand(1);
3794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3796   EVT VT = N0.getValueType();
3797   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3798
3799   // fold (srl c1, c2) -> c1 >>u c2
3800   if (N0C && N1C)
3801     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3802   // fold (srl 0, x) -> 0
3803   if (N0C && N0C->isNullValue())
3804     return N0;
3805   // fold (srl x, c >= size(x)) -> undef
3806   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3807     return DAG.getUNDEF(VT);
3808   // fold (srl x, 0) -> x
3809   if (N1C && N1C->isNullValue())
3810     return N0;
3811   // if (srl x, c) is known to be zero, return 0
3812   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3813                                    APInt::getAllOnesValue(OpSizeInBits)))
3814     return DAG.getConstant(0, VT);
3815
3816   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3817   if (N1C && N0.getOpcode() == ISD::SRL &&
3818       N0.getOperand(1).getOpcode() == ISD::Constant) {
3819     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3820     uint64_t c2 = N1C->getZExtValue();
3821     if (c1 + c2 >= OpSizeInBits)
3822       return DAG.getConstant(0, VT);
3823     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3824                        DAG.getConstant(c1 + c2, N1.getValueType()));
3825   }
3826
3827   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3828   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3829       N0.getOperand(0).getOpcode() == ISD::SRL &&
3830       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3831     uint64_t c1 =
3832       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3833     uint64_t c2 = N1C->getZExtValue();
3834     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3835     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3836     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3837     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3838     if (c1 + OpSizeInBits == InnerShiftSize) {
3839       if (c1 + c2 >= InnerShiftSize)
3840         return DAG.getConstant(0, VT);
3841       return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3842                          DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3843                                      N0.getOperand(0)->getOperand(0),
3844                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3845     }
3846   }
3847
3848   // fold (srl (shl x, c), c) -> (and x, cst2)
3849   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3850       N0.getValueSizeInBits() <= 64) {
3851     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3852     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3853                        DAG.getConstant(~0ULL >> ShAmt, VT));
3854   }
3855
3856
3857   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3858   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3859     // Shifting in all undef bits?
3860     EVT SmallVT = N0.getOperand(0).getValueType();
3861     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3862       return DAG.getUNDEF(VT);
3863
3864     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3865       uint64_t ShiftAmt = N1C->getZExtValue();
3866       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3867                                        N0.getOperand(0),
3868                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3869       AddToWorkList(SmallShift.getNode());
3870       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3871     }
3872   }
3873
3874   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3875   // bit, which is unmodified by sra.
3876   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3877     if (N0.getOpcode() == ISD::SRA)
3878       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3879   }
3880
3881   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3882   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3883       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3884     APInt KnownZero, KnownOne;
3885     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3886
3887     // If any of the input bits are KnownOne, then the input couldn't be all
3888     // zeros, thus the result of the srl will always be zero.
3889     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3890
3891     // If all of the bits input the to ctlz node are known to be zero, then
3892     // the result of the ctlz is "32" and the result of the shift is one.
3893     APInt UnknownBits = ~KnownZero;
3894     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3895
3896     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3897     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3898       // Okay, we know that only that the single bit specified by UnknownBits
3899       // could be set on input to the CTLZ node. If this bit is set, the SRL
3900       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3901       // to an SRL/XOR pair, which is likely to simplify more.
3902       unsigned ShAmt = UnknownBits.countTrailingZeros();
3903       SDValue Op = N0.getOperand(0);
3904
3905       if (ShAmt) {
3906         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3907                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3908         AddToWorkList(Op.getNode());
3909       }
3910
3911       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3912                          Op, DAG.getConstant(1, VT));
3913     }
3914   }
3915
3916   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3917   if (N1.getOpcode() == ISD::TRUNCATE &&
3918       N1.getOperand(0).getOpcode() == ISD::AND &&
3919       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3920     SDValue N101 = N1.getOperand(0).getOperand(1);
3921     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3922       EVT TruncVT = N1.getValueType();
3923       SDValue N100 = N1.getOperand(0).getOperand(0);
3924       APInt TruncC = N101C->getAPIntValue();
3925       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3926       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3927                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3928                                      TruncVT,
3929                                      DAG.getNode(ISD::TRUNCATE,
3930                                                  N->getDebugLoc(),
3931                                                  TruncVT, N100),
3932                                      DAG.getConstant(TruncC, TruncVT)));
3933     }
3934   }
3935
3936   // fold operands of srl based on knowledge that the low bits are not
3937   // demanded.
3938   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3939     return SDValue(N, 0);
3940
3941   if (N1C) {
3942     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3943     if (NewSRL.getNode())
3944       return NewSRL;
3945   }
3946
3947   // Attempt to convert a srl of a load into a narrower zero-extending load.
3948   SDValue NarrowLoad = ReduceLoadWidth(N);
3949   if (NarrowLoad.getNode())
3950     return NarrowLoad;
3951
3952   // Here is a common situation. We want to optimize:
3953   //
3954   //   %a = ...
3955   //   %b = and i32 %a, 2
3956   //   %c = srl i32 %b, 1
3957   //   brcond i32 %c ...
3958   //
3959   // into
3960   //
3961   //   %a = ...
3962   //   %b = and %a, 2
3963   //   %c = setcc eq %b, 0
3964   //   brcond %c ...
3965   //
3966   // However when after the source operand of SRL is optimized into AND, the SRL
3967   // itself may not be optimized further. Look for it and add the BRCOND into
3968   // the worklist.
3969   if (N->hasOneUse()) {
3970     SDNode *Use = *N->use_begin();
3971     if (Use->getOpcode() == ISD::BRCOND)
3972       AddToWorkList(Use);
3973     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3974       // Also look pass the truncate.
3975       Use = *Use->use_begin();
3976       if (Use->getOpcode() == ISD::BRCOND)
3977         AddToWorkList(Use);
3978     }
3979   }
3980
3981   return SDValue();
3982 }
3983
3984 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3985   SDValue N0 = N->getOperand(0);
3986   EVT VT = N->getValueType(0);
3987
3988   // fold (ctlz c1) -> c2
3989   if (isa<ConstantSDNode>(N0))
3990     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3991   return SDValue();
3992 }
3993
3994 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
3995   SDValue N0 = N->getOperand(0);
3996   EVT VT = N->getValueType(0);
3997
3998   // fold (ctlz_zero_undef c1) -> c2
3999   if (isa<ConstantSDNode>(N0))
4000     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4001   return SDValue();
4002 }
4003
4004 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4005   SDValue N0 = N->getOperand(0);
4006   EVT VT = N->getValueType(0);
4007
4008   // fold (cttz c1) -> c2
4009   if (isa<ConstantSDNode>(N0))
4010     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
4011   return SDValue();
4012 }
4013
4014 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4015   SDValue N0 = N->getOperand(0);
4016   EVT VT = N->getValueType(0);
4017
4018   // fold (cttz_zero_undef c1) -> c2
4019   if (isa<ConstantSDNode>(N0))
4020     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4021   return SDValue();
4022 }
4023
4024 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4025   SDValue N0 = N->getOperand(0);
4026   EVT VT = N->getValueType(0);
4027
4028   // fold (ctpop c1) -> c2
4029   if (isa<ConstantSDNode>(N0))
4030     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4031   return SDValue();
4032 }
4033
4034 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4035   SDValue N0 = N->getOperand(0);
4036   SDValue N1 = N->getOperand(1);
4037   SDValue N2 = N->getOperand(2);
4038   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4039   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4040   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4041   EVT VT = N->getValueType(0);
4042   EVT VT0 = N0.getValueType();
4043
4044   // fold (select C, X, X) -> X
4045   if (N1 == N2)
4046     return N1;
4047   // fold (select true, X, Y) -> X
4048   if (N0C && !N0C->isNullValue())
4049     return N1;
4050   // fold (select false, X, Y) -> Y
4051   if (N0C && N0C->isNullValue())
4052     return N2;
4053   // fold (select C, 1, X) -> (or C, X)
4054   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4055     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4056   // fold (select C, 0, 1) -> (xor C, 1)
4057   if (VT.isInteger() &&
4058       (VT0 == MVT::i1 ||
4059        (VT0.isInteger() &&
4060         TLI.getBooleanContents(false) ==
4061         TargetLowering::ZeroOrOneBooleanContent)) &&
4062       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4063     SDValue XORNode;
4064     if (VT == VT0)
4065       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4066                          N0, DAG.getConstant(1, VT0));
4067     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4068                           N0, DAG.getConstant(1, VT0));
4069     AddToWorkList(XORNode.getNode());
4070     if (VT.bitsGT(VT0))
4071       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4072     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4073   }
4074   // fold (select C, 0, X) -> (and (not C), X)
4075   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4076     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4077     AddToWorkList(NOTNode.getNode());
4078     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4079   }
4080   // fold (select C, X, 1) -> (or (not C), X)
4081   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4082     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4083     AddToWorkList(NOTNode.getNode());
4084     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4085   }
4086   // fold (select C, X, 0) -> (and C, X)
4087   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4088     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4089   // fold (select X, X, Y) -> (or X, Y)
4090   // fold (select X, 1, Y) -> (or X, Y)
4091   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4092     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4093   // fold (select X, Y, X) -> (and X, Y)
4094   // fold (select X, Y, 0) -> (and X, Y)
4095   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4096     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4097
4098   // If we can fold this based on the true/false value, do so.
4099   if (SimplifySelectOps(N, N1, N2))
4100     return SDValue(N, 0);  // Don't revisit N.
4101
4102   // fold selects based on a setcc into other things, such as min/max/abs
4103   if (N0.getOpcode() == ISD::SETCC) {
4104     // FIXME:
4105     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4106     // having to say they don't support SELECT_CC on every type the DAG knows
4107     // about, since there is no way to mark an opcode illegal at all value types
4108     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4109         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4110       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4111                          N0.getOperand(0), N0.getOperand(1),
4112                          N1, N2, N0.getOperand(2));
4113     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4114   }
4115
4116   return SDValue();
4117 }
4118
4119 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4120   SDValue N0 = N->getOperand(0);
4121   SDValue N1 = N->getOperand(1);
4122   SDValue N2 = N->getOperand(2);
4123   SDValue N3 = N->getOperand(3);
4124   SDValue N4 = N->getOperand(4);
4125   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4126
4127   // fold select_cc lhs, rhs, x, x, cc -> x
4128   if (N2 == N3)
4129     return N2;
4130
4131   // Determine if the condition we're dealing with is constant
4132   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4133                               N0, N1, CC, N->getDebugLoc(), false);
4134   if (SCC.getNode()) AddToWorkList(SCC.getNode());
4135
4136   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4137     if (!SCCC->isNullValue())
4138       return N2;    // cond always true -> true val
4139     else
4140       return N3;    // cond always false -> false val
4141   }
4142
4143   // Fold to a simpler select_cc
4144   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4145     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4146                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4147                        SCC.getOperand(2));
4148
4149   // If we can fold this based on the true/false value, do so.
4150   if (SimplifySelectOps(N, N2, N3))
4151     return SDValue(N, 0);  // Don't revisit N.
4152
4153   // fold select_cc into other things, such as min/max/abs
4154   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4155 }
4156
4157 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4158   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4159                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4160                        N->getDebugLoc());
4161 }
4162
4163 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4164 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4165 // transformation. Returns true if extension are possible and the above
4166 // mentioned transformation is profitable.
4167 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4168                                     unsigned ExtOpc,
4169                                     SmallVector<SDNode*, 4> &ExtendNodes,
4170                                     const TargetLowering &TLI) {
4171   bool HasCopyToRegUses = false;
4172   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4173   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4174                             UE = N0.getNode()->use_end();
4175        UI != UE; ++UI) {
4176     SDNode *User = *UI;
4177     if (User == N)
4178       continue;
4179     if (UI.getUse().getResNo() != N0.getResNo())
4180       continue;
4181     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4182     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4183       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4184       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4185         // Sign bits will be lost after a zext.
4186         return false;
4187       bool Add = false;
4188       for (unsigned i = 0; i != 2; ++i) {
4189         SDValue UseOp = User->getOperand(i);
4190         if (UseOp == N0)
4191           continue;
4192         if (!isa<ConstantSDNode>(UseOp))
4193           return false;
4194         Add = true;
4195       }
4196       if (Add)
4197         ExtendNodes.push_back(User);
4198       continue;
4199     }
4200     // If truncates aren't free and there are users we can't
4201     // extend, it isn't worthwhile.
4202     if (!isTruncFree)
4203       return false;
4204     // Remember if this value is live-out.
4205     if (User->getOpcode() == ISD::CopyToReg)
4206       HasCopyToRegUses = true;
4207   }
4208
4209   if (HasCopyToRegUses) {
4210     bool BothLiveOut = false;
4211     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4212          UI != UE; ++UI) {
4213       SDUse &Use = UI.getUse();
4214       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4215         BothLiveOut = true;
4216         break;
4217       }
4218     }
4219     if (BothLiveOut)
4220       // Both unextended and extended values are live out. There had better be
4221       // a good reason for the transformation.
4222       return ExtendNodes.size();
4223   }
4224   return true;
4225 }
4226
4227 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4228                                   SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4229                                   ISD::NodeType ExtType) {
4230   // Extend SetCC uses if necessary.
4231   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4232     SDNode *SetCC = SetCCs[i];
4233     SmallVector<SDValue, 4> Ops;
4234
4235     for (unsigned j = 0; j != 2; ++j) {
4236       SDValue SOp = SetCC->getOperand(j);
4237       if (SOp == Trunc)
4238         Ops.push_back(ExtLoad);
4239       else
4240         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4241     }
4242
4243     Ops.push_back(SetCC->getOperand(2));
4244     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4245                                  &Ops[0], Ops.size()));
4246   }
4247 }
4248
4249 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4250   SDValue N0 = N->getOperand(0);
4251   EVT VT = N->getValueType(0);
4252
4253   // fold (sext c1) -> c1
4254   if (isa<ConstantSDNode>(N0))
4255     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4256
4257   // fold (sext (sext x)) -> (sext x)
4258   // fold (sext (aext x)) -> (sext x)
4259   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4260     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4261                        N0.getOperand(0));
4262
4263   if (N0.getOpcode() == ISD::TRUNCATE) {
4264     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4265     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4266     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4267     if (NarrowLoad.getNode()) {
4268       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4269       if (NarrowLoad.getNode() != N0.getNode()) {
4270         CombineTo(N0.getNode(), NarrowLoad);
4271         // CombineTo deleted the truncate, if needed, but not what's under it.
4272         AddToWorkList(oye);
4273       }
4274       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4275     }
4276
4277     // See if the value being truncated is already sign extended.  If so, just
4278     // eliminate the trunc/sext pair.
4279     SDValue Op = N0.getOperand(0);
4280     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4281     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4282     unsigned DestBits = VT.getScalarType().getSizeInBits();
4283     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4284
4285     if (OpBits == DestBits) {
4286       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4287       // bits, it is already ready.
4288       if (NumSignBits > DestBits-MidBits)
4289         return Op;
4290     } else if (OpBits < DestBits) {
4291       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4292       // bits, just sext from i32.
4293       if (NumSignBits > OpBits-MidBits)
4294         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4295     } else {
4296       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4297       // bits, just truncate to i32.
4298       if (NumSignBits > OpBits-MidBits)
4299         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4300     }
4301
4302     // fold (sext (truncate x)) -> (sextinreg x).
4303     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4304                                                  N0.getValueType())) {
4305       if (OpBits < DestBits)
4306         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4307       else if (OpBits > DestBits)
4308         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4309       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4310                          DAG.getValueType(N0.getValueType()));
4311     }
4312   }
4313
4314   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4315   // None of the supported targets knows how to perform load and sign extend
4316   // on vectors in one instruction.  We only perform this transformation on
4317   // scalars.
4318   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4319       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4320        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4321     bool DoXform = true;
4322     SmallVector<SDNode*, 4> SetCCs;
4323     if (!N0.hasOneUse())
4324       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4325     if (DoXform) {
4326       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4327       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4328                                        LN0->getChain(),
4329                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4330                                        N0.getValueType(),
4331                                        LN0->isVolatile(), LN0->isNonTemporal(),
4332                                        LN0->getAlignment());
4333       CombineTo(N, ExtLoad);
4334       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4335                                   N0.getValueType(), ExtLoad);
4336       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4337       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4338                       ISD::SIGN_EXTEND);
4339       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4340     }
4341   }
4342
4343   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4344   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4345   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4346       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4347     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4348     EVT MemVT = LN0->getMemoryVT();
4349     if ((!LegalOperations && !LN0->isVolatile()) ||
4350         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4351       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4352                                        LN0->getChain(),
4353                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4354                                        MemVT,
4355                                        LN0->isVolatile(), LN0->isNonTemporal(),
4356                                        LN0->getAlignment());
4357       CombineTo(N, ExtLoad);
4358       CombineTo(N0.getNode(),
4359                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4360                             N0.getValueType(), ExtLoad),
4361                 ExtLoad.getValue(1));
4362       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4363     }
4364   }
4365
4366   // fold (sext (and/or/xor (load x), cst)) ->
4367   //      (and/or/xor (sextload x), (sext cst))
4368   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4369        N0.getOpcode() == ISD::XOR) &&
4370       isa<LoadSDNode>(N0.getOperand(0)) &&
4371       N0.getOperand(1).getOpcode() == ISD::Constant &&
4372       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4373       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4374     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4375     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4376       bool DoXform = true;
4377       SmallVector<SDNode*, 4> SetCCs;
4378       if (!N0.hasOneUse())
4379         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4380                                           SetCCs, TLI);
4381       if (DoXform) {
4382         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4383                                          LN0->getChain(), LN0->getBasePtr(),
4384                                          LN0->getPointerInfo(),
4385                                          LN0->getMemoryVT(),
4386                                          LN0->isVolatile(),
4387                                          LN0->isNonTemporal(),
4388                                          LN0->getAlignment());
4389         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4390         Mask = Mask.sext(VT.getSizeInBits());
4391         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4392                                   ExtLoad, DAG.getConstant(Mask, VT));
4393         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4394                                     N0.getOperand(0).getDebugLoc(),
4395                                     N0.getOperand(0).getValueType(), ExtLoad);
4396         CombineTo(N, And);
4397         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4398         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4399                         ISD::SIGN_EXTEND);
4400         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4401       }
4402     }
4403   }
4404
4405   if (N0.getOpcode() == ISD::SETCC) {
4406     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4407     // Only do this before legalize for now.
4408     if (VT.isVector() && !LegalOperations) {
4409       EVT N0VT = N0.getOperand(0).getValueType();
4410       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4411       // of the same size as the compared operands. Only optimize sext(setcc())
4412       // if this is the case.
4413       EVT SVT = TLI.getSetCCResultType(N0VT);
4414
4415       // We know that the # elements of the results is the same as the
4416       // # elements of the compare (and the # elements of the compare result
4417       // for that matter).  Check to see that they are the same size.  If so,
4418       // we know that the element size of the sext'd result matches the
4419       // element size of the compare operands.
4420       if (VT.getSizeInBits() == SVT.getSizeInBits())
4421         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4422                              N0.getOperand(1),
4423                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4424       // If the desired elements are smaller or larger than the source
4425       // elements we can use a matching integer vector type and then
4426       // truncate/sign extend
4427       EVT MatchingElementType =
4428         EVT::getIntegerVT(*DAG.getContext(),
4429                           N0VT.getScalarType().getSizeInBits());
4430       EVT MatchingVectorType =
4431         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4432                          N0VT.getVectorNumElements());
4433
4434       if (SVT == MatchingVectorType) {
4435         SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4436                                N0.getOperand(0), N0.getOperand(1),
4437                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4438         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4439       }
4440     }
4441
4442     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4443     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4444     SDValue NegOne =
4445       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4446     SDValue SCC =
4447       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4448                        NegOne, DAG.getConstant(0, VT),
4449                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4450     if (SCC.getNode()) return SCC;
4451     if (!LegalOperations ||
4452         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4453       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4454                          DAG.getSetCC(N->getDebugLoc(),
4455                                       TLI.getSetCCResultType(VT),
4456                                       N0.getOperand(0), N0.getOperand(1),
4457                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4458                          NegOne, DAG.getConstant(0, VT));
4459   }
4460
4461   // fold (sext x) -> (zext x) if the sign bit is known zero.
4462   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4463       DAG.SignBitIsZero(N0))
4464     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4465
4466   return SDValue();
4467 }
4468
4469 // isTruncateOf - If N is a truncate of some other value, return true, record
4470 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4471 // This function computes KnownZero to avoid a duplicated call to
4472 // ComputeMaskedBits in the caller.
4473 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4474                          APInt &KnownZero) {
4475   APInt KnownOne;
4476   if (N->getOpcode() == ISD::TRUNCATE) {
4477     Op = N->getOperand(0);
4478     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4479     return true;
4480   }
4481
4482   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4483       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4484     return false;
4485
4486   SDValue Op0 = N->getOperand(0);
4487   SDValue Op1 = N->getOperand(1);
4488   assert(Op0.getValueType() == Op1.getValueType());
4489
4490   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4491   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4492   if (COp0 && COp0->isNullValue())
4493     Op = Op1;
4494   else if (COp1 && COp1->isNullValue())
4495     Op = Op0;
4496   else
4497     return false;
4498
4499   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4500
4501   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4502     return false;
4503
4504   return true;
4505 }
4506
4507 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4508   SDValue N0 = N->getOperand(0);
4509   EVT VT = N->getValueType(0);
4510
4511   // fold (zext c1) -> c1
4512   if (isa<ConstantSDNode>(N0))
4513     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4514   // fold (zext (zext x)) -> (zext x)
4515   // fold (zext (aext x)) -> (zext x)
4516   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4517     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4518                        N0.getOperand(0));
4519
4520   // fold (zext (truncate x)) -> (zext x) or
4521   //      (zext (truncate x)) -> (truncate x)
4522   // This is valid when the truncated bits of x are already zero.
4523   // FIXME: We should extend this to work for vectors too.
4524   SDValue Op;
4525   APInt KnownZero;
4526   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4527     APInt TruncatedBits =
4528       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4529       APInt(Op.getValueSizeInBits(), 0) :
4530       APInt::getBitsSet(Op.getValueSizeInBits(),
4531                         N0.getValueSizeInBits(),
4532                         std::min(Op.getValueSizeInBits(),
4533                                  VT.getSizeInBits()));
4534     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4535       if (VT.bitsGT(Op.getValueType()))
4536         return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4537       if (VT.bitsLT(Op.getValueType()))
4538         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4539
4540       return Op;
4541     }
4542   }
4543
4544   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4545   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4546   if (N0.getOpcode() == ISD::TRUNCATE) {
4547     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4548     if (NarrowLoad.getNode()) {
4549       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4550       if (NarrowLoad.getNode() != N0.getNode()) {
4551         CombineTo(N0.getNode(), NarrowLoad);
4552         // CombineTo deleted the truncate, if needed, but not what's under it.
4553         AddToWorkList(oye);
4554       }
4555       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4556     }
4557   }
4558
4559   // fold (zext (truncate x)) -> (and x, mask)
4560   if (N0.getOpcode() == ISD::TRUNCATE &&
4561       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4562
4563     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4564     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4565     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4566     if (NarrowLoad.getNode()) {
4567       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4568       if (NarrowLoad.getNode() != N0.getNode()) {
4569         CombineTo(N0.getNode(), NarrowLoad);
4570         // CombineTo deleted the truncate, if needed, but not what's under it.
4571         AddToWorkList(oye);
4572       }
4573       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4574     }
4575
4576     SDValue Op = N0.getOperand(0);
4577     if (Op.getValueType().bitsLT(VT)) {
4578       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4579       AddToWorkList(Op.getNode());
4580     } else if (Op.getValueType().bitsGT(VT)) {
4581       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4582       AddToWorkList(Op.getNode());
4583     }
4584     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4585                                   N0.getValueType().getScalarType());
4586   }
4587
4588   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4589   // if either of the casts is not free.
4590   if (N0.getOpcode() == ISD::AND &&
4591       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4592       N0.getOperand(1).getOpcode() == ISD::Constant &&
4593       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4594                            N0.getValueType()) ||
4595        !TLI.isZExtFree(N0.getValueType(), VT))) {
4596     SDValue X = N0.getOperand(0).getOperand(0);
4597     if (X.getValueType().bitsLT(VT)) {
4598       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4599     } else if (X.getValueType().bitsGT(VT)) {
4600       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4601     }
4602     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4603     Mask = Mask.zext(VT.getSizeInBits());
4604     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4605                        X, DAG.getConstant(Mask, VT));
4606   }
4607
4608   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4609   // None of the supported targets knows how to perform load and vector_zext
4610   // on vectors in one instruction.  We only perform this transformation on
4611   // scalars.
4612   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4613       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4614        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4615     bool DoXform = true;
4616     SmallVector<SDNode*, 4> SetCCs;
4617     if (!N0.hasOneUse())
4618       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4619     if (DoXform) {
4620       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4621       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4622                                        LN0->getChain(),
4623                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4624                                        N0.getValueType(),
4625                                        LN0->isVolatile(), LN0->isNonTemporal(),
4626                                        LN0->getAlignment());
4627       CombineTo(N, ExtLoad);
4628       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4629                                   N0.getValueType(), ExtLoad);
4630       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4631
4632       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4633                       ISD::ZERO_EXTEND);
4634       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4635     }
4636   }
4637
4638   // fold (zext (and/or/xor (load x), cst)) ->
4639   //      (and/or/xor (zextload x), (zext cst))
4640   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4641        N0.getOpcode() == ISD::XOR) &&
4642       isa<LoadSDNode>(N0.getOperand(0)) &&
4643       N0.getOperand(1).getOpcode() == ISD::Constant &&
4644       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4645       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4646     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4647     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4648       bool DoXform = true;
4649       SmallVector<SDNode*, 4> SetCCs;
4650       if (!N0.hasOneUse())
4651         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4652                                           SetCCs, TLI);
4653       if (DoXform) {
4654         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4655                                          LN0->getChain(), LN0->getBasePtr(),
4656                                          LN0->getPointerInfo(),
4657                                          LN0->getMemoryVT(),
4658                                          LN0->isVolatile(),
4659                                          LN0->isNonTemporal(),
4660                                          LN0->getAlignment());
4661         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4662         Mask = Mask.zext(VT.getSizeInBits());
4663         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4664                                   ExtLoad, DAG.getConstant(Mask, VT));
4665         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4666                                     N0.getOperand(0).getDebugLoc(),
4667                                     N0.getOperand(0).getValueType(), ExtLoad);
4668         CombineTo(N, And);
4669         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4670         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4671                         ISD::ZERO_EXTEND);
4672         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4673       }
4674     }
4675   }
4676
4677   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4678   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4679   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4680       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4681     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4682     EVT MemVT = LN0->getMemoryVT();
4683     if ((!LegalOperations && !LN0->isVolatile()) ||
4684         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4685       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4686                                        LN0->getChain(),
4687                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4688                                        MemVT,
4689                                        LN0->isVolatile(), LN0->isNonTemporal(),
4690                                        LN0->getAlignment());
4691       CombineTo(N, ExtLoad);
4692       CombineTo(N0.getNode(),
4693                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4694                             ExtLoad),
4695                 ExtLoad.getValue(1));
4696       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4697     }
4698   }
4699
4700   if (N0.getOpcode() == ISD::SETCC) {
4701     if (!LegalOperations && VT.isVector()) {
4702       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4703       // Only do this before legalize for now.
4704       EVT N0VT = N0.getOperand(0).getValueType();
4705       EVT EltVT = VT.getVectorElementType();
4706       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4707                                     DAG.getConstant(1, EltVT));
4708       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4709         // We know that the # elements of the results is the same as the
4710         // # elements of the compare (and the # elements of the compare result
4711         // for that matter).  Check to see that they are the same size.  If so,
4712         // we know that the element size of the sext'd result matches the
4713         // element size of the compare operands.
4714         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4715                            DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4716                                          N0.getOperand(1),
4717                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4718                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4719                                        &OneOps[0], OneOps.size()));
4720
4721       // If the desired elements are smaller or larger than the source
4722       // elements we can use a matching integer vector type and then
4723       // truncate/sign extend
4724       EVT MatchingElementType =
4725         EVT::getIntegerVT(*DAG.getContext(),
4726                           N0VT.getScalarType().getSizeInBits());
4727       EVT MatchingVectorType =
4728         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4729                          N0VT.getVectorNumElements());
4730       SDValue VsetCC =
4731         DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4732                       N0.getOperand(1),
4733                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4734       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4735                          DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4736                          DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4737                                      &OneOps[0], OneOps.size()));
4738     }
4739
4740     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4741     SDValue SCC =
4742       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4743                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4744                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4745     if (SCC.getNode()) return SCC;
4746   }
4747
4748   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4749   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4750       isa<ConstantSDNode>(N0.getOperand(1)) &&
4751       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4752       N0.hasOneUse()) {
4753     SDValue ShAmt = N0.getOperand(1);
4754     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4755     if (N0.getOpcode() == ISD::SHL) {
4756       SDValue InnerZExt = N0.getOperand(0);
4757       // If the original shl may be shifting out bits, do not perform this
4758       // transformation.
4759       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4760         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4761       if (ShAmtVal > KnownZeroBits)
4762         return SDValue();
4763     }
4764
4765     DebugLoc DL = N->getDebugLoc();
4766
4767     // Ensure that the shift amount is wide enough for the shifted value.
4768     if (VT.getSizeInBits() >= 256)
4769       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4770
4771     return DAG.getNode(N0.getOpcode(), DL, VT,
4772                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4773                        ShAmt);
4774   }
4775
4776   return SDValue();
4777 }
4778
4779 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4780   SDValue N0 = N->getOperand(0);
4781   EVT VT = N->getValueType(0);
4782
4783   // fold (aext c1) -> c1
4784   if (isa<ConstantSDNode>(N0))
4785     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4786   // fold (aext (aext x)) -> (aext x)
4787   // fold (aext (zext x)) -> (zext x)
4788   // fold (aext (sext x)) -> (sext x)
4789   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4790       N0.getOpcode() == ISD::ZERO_EXTEND ||
4791       N0.getOpcode() == ISD::SIGN_EXTEND)
4792     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4793
4794   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4795   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4796   if (N0.getOpcode() == ISD::TRUNCATE) {
4797     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4798     if (NarrowLoad.getNode()) {
4799       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4800       if (NarrowLoad.getNode() != N0.getNode()) {
4801         CombineTo(N0.getNode(), NarrowLoad);
4802         // CombineTo deleted the truncate, if needed, but not what's under it.
4803         AddToWorkList(oye);
4804       }
4805       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4806     }
4807   }
4808
4809   // fold (aext (truncate x))
4810   if (N0.getOpcode() == ISD::TRUNCATE) {
4811     SDValue TruncOp = N0.getOperand(0);
4812     if (TruncOp.getValueType() == VT)
4813       return TruncOp; // x iff x size == zext size.
4814     if (TruncOp.getValueType().bitsGT(VT))
4815       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4816     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4817   }
4818
4819   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4820   // if the trunc is not free.
4821   if (N0.getOpcode() == ISD::AND &&
4822       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4823       N0.getOperand(1).getOpcode() == ISD::Constant &&
4824       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4825                           N0.getValueType())) {
4826     SDValue X = N0.getOperand(0).getOperand(0);
4827     if (X.getValueType().bitsLT(VT)) {
4828       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4829     } else if (X.getValueType().bitsGT(VT)) {
4830       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4831     }
4832     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4833     Mask = Mask.zext(VT.getSizeInBits());
4834     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4835                        X, DAG.getConstant(Mask, VT));
4836   }
4837
4838   // fold (aext (load x)) -> (aext (truncate (extload x)))
4839   // None of the supported targets knows how to perform load and any_ext
4840   // on vectors in one instruction.  We only perform this transformation on
4841   // scalars.
4842   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4843       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4844        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4845     bool DoXform = true;
4846     SmallVector<SDNode*, 4> SetCCs;
4847     if (!N0.hasOneUse())
4848       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4849     if (DoXform) {
4850       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4851       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4852                                        LN0->getChain(),
4853                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4854                                        N0.getValueType(),
4855                                        LN0->isVolatile(), LN0->isNonTemporal(),
4856                                        LN0->getAlignment());
4857       CombineTo(N, ExtLoad);
4858       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4859                                   N0.getValueType(), ExtLoad);
4860       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4861       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4862                       ISD::ANY_EXTEND);
4863       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4864     }
4865   }
4866
4867   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4868   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4869   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4870   if (N0.getOpcode() == ISD::LOAD &&
4871       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4872       N0.hasOneUse()) {
4873     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4874     EVT MemVT = LN0->getMemoryVT();
4875     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4876                                      VT, LN0->getChain(), LN0->getBasePtr(),
4877                                      LN0->getPointerInfo(), MemVT,
4878                                      LN0->isVolatile(), LN0->isNonTemporal(),
4879                                      LN0->getAlignment());
4880     CombineTo(N, ExtLoad);
4881     CombineTo(N0.getNode(),
4882               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4883                           N0.getValueType(), ExtLoad),
4884               ExtLoad.getValue(1));
4885     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4886   }
4887
4888   if (N0.getOpcode() == ISD::SETCC) {
4889     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4890     // Only do this before legalize for now.
4891     if (VT.isVector() && !LegalOperations) {
4892       EVT N0VT = N0.getOperand(0).getValueType();
4893         // We know that the # elements of the results is the same as the
4894         // # elements of the compare (and the # elements of the compare result
4895         // for that matter).  Check to see that they are the same size.  If so,
4896         // we know that the element size of the sext'd result matches the
4897         // element size of the compare operands.
4898       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4899         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4900                              N0.getOperand(1),
4901                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4902       // If the desired elements are smaller or larger than the source
4903       // elements we can use a matching integer vector type and then
4904       // truncate/sign extend
4905       else {
4906         EVT MatchingElementType =
4907           EVT::getIntegerVT(*DAG.getContext(),
4908                             N0VT.getScalarType().getSizeInBits());
4909         EVT MatchingVectorType =
4910           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4911                            N0VT.getVectorNumElements());
4912         SDValue VsetCC =
4913           DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4914                         N0.getOperand(1),
4915                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
4916         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4917       }
4918     }
4919
4920     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4921     SDValue SCC =
4922       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4923                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4924                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4925     if (SCC.getNode())
4926       return SCC;
4927   }
4928
4929   return SDValue();
4930 }
4931
4932 /// GetDemandedBits - See if the specified operand can be simplified with the
4933 /// knowledge that only the bits specified by Mask are used.  If so, return the
4934 /// simpler operand, otherwise return a null SDValue.
4935 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4936   switch (V.getOpcode()) {
4937   default: break;
4938   case ISD::Constant: {
4939     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4940     assert(CV != 0 && "Const value should be ConstSDNode.");
4941     const APInt &CVal = CV->getAPIntValue();
4942     APInt NewVal = CVal & Mask;
4943     if (NewVal != CVal) {
4944       return DAG.getConstant(NewVal, V.getValueType());
4945     }
4946     break;
4947   }
4948   case ISD::OR:
4949   case ISD::XOR:
4950     // If the LHS or RHS don't contribute bits to the or, drop them.
4951     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4952       return V.getOperand(1);
4953     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4954       return V.getOperand(0);
4955     break;
4956   case ISD::SRL:
4957     // Only look at single-use SRLs.
4958     if (!V.getNode()->hasOneUse())
4959       break;
4960     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4961       // See if we can recursively simplify the LHS.
4962       unsigned Amt = RHSC->getZExtValue();
4963
4964       // Watch out for shift count overflow though.
4965       if (Amt >= Mask.getBitWidth()) break;
4966       APInt NewMask = Mask << Amt;
4967       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4968       if (SimplifyLHS.getNode())
4969         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4970                            SimplifyLHS, V.getOperand(1));
4971     }
4972   }
4973   return SDValue();
4974 }
4975
4976 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4977 /// bits and then truncated to a narrower type and where N is a multiple
4978 /// of number of bits of the narrower type, transform it to a narrower load
4979 /// from address + N / num of bits of new type. If the result is to be
4980 /// extended, also fold the extension to form a extending load.
4981 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4982   unsigned Opc = N->getOpcode();
4983
4984   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4985   SDValue N0 = N->getOperand(0);
4986   EVT VT = N->getValueType(0);
4987   EVT ExtVT = VT;
4988
4989   // This transformation isn't valid for vector loads.
4990   if (VT.isVector())
4991     return SDValue();
4992
4993   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4994   // extended to VT.
4995   if (Opc == ISD::SIGN_EXTEND_INREG) {
4996     ExtType = ISD::SEXTLOAD;
4997     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4998   } else if (Opc == ISD::SRL) {
4999     // Another special-case: SRL is basically zero-extending a narrower value.
5000     ExtType = ISD::ZEXTLOAD;
5001     N0 = SDValue(N, 0);
5002     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5003     if (!N01) return SDValue();
5004     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5005                               VT.getSizeInBits() - N01->getZExtValue());
5006   }
5007   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5008     return SDValue();
5009
5010   unsigned EVTBits = ExtVT.getSizeInBits();
5011
5012   // Do not generate loads of non-round integer types since these can
5013   // be expensive (and would be wrong if the type is not byte sized).
5014   if (!ExtVT.isRound())
5015     return SDValue();
5016
5017   unsigned ShAmt = 0;
5018   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5019     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5020       ShAmt = N01->getZExtValue();
5021       // Is the shift amount a multiple of size of VT?
5022       if ((ShAmt & (EVTBits-1)) == 0) {
5023         N0 = N0.getOperand(0);
5024         // Is the load width a multiple of size of VT?
5025         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5026           return SDValue();
5027       }
5028
5029       // At this point, we must have a load or else we can't do the transform.
5030       if (!isa<LoadSDNode>(N0)) return SDValue();
5031
5032       // If the shift amount is larger than the input type then we're not
5033       // accessing any of the loaded bytes.  If the load was a zextload/extload
5034       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5035       // If the load was a sextload then the result is a splat of the sign bit
5036       // of the extended byte.  This is not worth optimizing for.
5037       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5038         return SDValue();
5039     }
5040   }
5041
5042   // If the load is shifted left (and the result isn't shifted back right),
5043   // we can fold the truncate through the shift.
5044   unsigned ShLeftAmt = 0;
5045   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5046       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5047     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5048       ShLeftAmt = N01->getZExtValue();
5049       N0 = N0.getOperand(0);
5050     }
5051   }
5052
5053   // If we haven't found a load, we can't narrow it.  Don't transform one with
5054   // multiple uses, this would require adding a new load.
5055   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
5056       // Don't change the width of a volatile load.
5057       cast<LoadSDNode>(N0)->isVolatile())
5058     return SDValue();
5059
5060   // Verify that we are actually reducing a load width here.
5061   if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
5062     return SDValue();
5063
5064   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5065   EVT PtrType = N0.getOperand(1).getValueType();
5066
5067   if (PtrType == MVT::Untyped || PtrType.isExtended())
5068     // It's not possible to generate a constant of extended or untyped type.
5069     return SDValue();
5070
5071   // For big endian targets, we need to adjust the offset to the pointer to
5072   // load the correct bytes.
5073   if (TLI.isBigEndian()) {
5074     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5075     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5076     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5077   }
5078
5079   uint64_t PtrOff = ShAmt / 8;
5080   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5081   SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5082                                PtrType, LN0->getBasePtr(),
5083                                DAG.getConstant(PtrOff, PtrType));
5084   AddToWorkList(NewPtr.getNode());
5085
5086   SDValue Load;
5087   if (ExtType == ISD::NON_EXTLOAD)
5088     Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5089                         LN0->getPointerInfo().getWithOffset(PtrOff),
5090                         LN0->isVolatile(), LN0->isNonTemporal(),
5091                         LN0->isInvariant(), NewAlign);
5092   else
5093     Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5094                           LN0->getPointerInfo().getWithOffset(PtrOff),
5095                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5096                           NewAlign);
5097
5098   // Replace the old load's chain with the new load's chain.
5099   WorkListRemover DeadNodes(*this);
5100   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5101
5102   // Shift the result left, if we've swallowed a left shift.
5103   SDValue Result = Load;
5104   if (ShLeftAmt != 0) {
5105     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5106     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5107       ShImmTy = VT;
5108     Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5109                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5110   }
5111
5112   // Return the new loaded value.
5113   return Result;
5114 }
5115
5116 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5117   SDValue N0 = N->getOperand(0);
5118   SDValue N1 = N->getOperand(1);
5119   EVT VT = N->getValueType(0);
5120   EVT EVT = cast<VTSDNode>(N1)->getVT();
5121   unsigned VTBits = VT.getScalarType().getSizeInBits();
5122   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5123
5124   // fold (sext_in_reg c1) -> c1
5125   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5126     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5127
5128   // If the input is already sign extended, just drop the extension.
5129   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5130     return N0;
5131
5132   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5133   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5134       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5135     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5136                        N0.getOperand(0), N1);
5137   }
5138
5139   // fold (sext_in_reg (sext x)) -> (sext x)
5140   // fold (sext_in_reg (aext x)) -> (sext x)
5141   // if x is small enough.
5142   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5143     SDValue N00 = N0.getOperand(0);
5144     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5145         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5146       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5147   }
5148
5149   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5150   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5151     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5152
5153   // fold operands of sext_in_reg based on knowledge that the top bits are not
5154   // demanded.
5155   if (SimplifyDemandedBits(SDValue(N, 0)))
5156     return SDValue(N, 0);
5157
5158   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5159   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5160   SDValue NarrowLoad = ReduceLoadWidth(N);
5161   if (NarrowLoad.getNode())
5162     return NarrowLoad;
5163
5164   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5165   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5166   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5167   if (N0.getOpcode() == ISD::SRL) {
5168     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5169       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5170         // We can turn this into an SRA iff the input to the SRL is already sign
5171         // extended enough.
5172         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5173         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5174           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5175                              N0.getOperand(0), N0.getOperand(1));
5176       }
5177   }
5178
5179   // fold (sext_inreg (extload x)) -> (sextload x)
5180   if (ISD::isEXTLoad(N0.getNode()) &&
5181       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5182       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5183       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5184        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5185     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5186     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5187                                      LN0->getChain(),
5188                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5189                                      EVT,
5190                                      LN0->isVolatile(), LN0->isNonTemporal(),
5191                                      LN0->getAlignment());
5192     CombineTo(N, ExtLoad);
5193     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5194     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5195   }
5196   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5197   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5198       N0.hasOneUse() &&
5199       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5200       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5201        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5202     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5203     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5204                                      LN0->getChain(),
5205                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5206                                      EVT,
5207                                      LN0->isVolatile(), LN0->isNonTemporal(),
5208                                      LN0->getAlignment());
5209     CombineTo(N, ExtLoad);
5210     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5211     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5212   }
5213
5214   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5215   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5216     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5217                                        N0.getOperand(1), false);
5218     if (BSwap.getNode() != 0)
5219       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5220                          BSwap, N1);
5221   }
5222
5223   return SDValue();
5224 }
5225
5226 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5227   SDValue N0 = N->getOperand(0);
5228   EVT VT = N->getValueType(0);
5229   bool isLE = TLI.isLittleEndian();
5230
5231   // noop truncate
5232   if (N0.getValueType() == N->getValueType(0))
5233     return N0;
5234   // fold (truncate c1) -> c1
5235   if (isa<ConstantSDNode>(N0))
5236     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5237   // fold (truncate (truncate x)) -> (truncate x)
5238   if (N0.getOpcode() == ISD::TRUNCATE)
5239     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5240   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5241   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5242       N0.getOpcode() == ISD::SIGN_EXTEND ||
5243       N0.getOpcode() == ISD::ANY_EXTEND) {
5244     if (N0.getOperand(0).getValueType().bitsLT(VT))
5245       // if the source is smaller than the dest, we still need an extend
5246       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5247                          N0.getOperand(0));
5248     if (N0.getOperand(0).getValueType().bitsGT(VT))
5249       // if the source is larger than the dest, than we just need the truncate
5250       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5251     // if the source and dest are the same type, we can drop both the extend
5252     // and the truncate.
5253     return N0.getOperand(0);
5254   }
5255
5256   // Fold extract-and-trunc into a narrow extract. For example:
5257   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5258   //   i32 y = TRUNCATE(i64 x)
5259   //        -- becomes --
5260   //   v16i8 b = BITCAST (v2i64 val)
5261   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5262   //
5263   // Note: We only run this optimization after type legalization (which often
5264   // creates this pattern) and before operation legalization after which
5265   // we need to be more careful about the vector instructions that we generate.
5266   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5267       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5268
5269     EVT VecTy = N0.getOperand(0).getValueType();
5270     EVT ExTy = N0.getValueType();
5271     EVT TrTy = N->getValueType(0);
5272
5273     unsigned NumElem = VecTy.getVectorNumElements();
5274     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5275
5276     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5277     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5278
5279     SDValue EltNo = N0->getOperand(1);
5280     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5281       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5282       EVT IndexTy = N0->getOperand(1).getValueType();
5283       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5284
5285       SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5286                               NVT, N0.getOperand(0));
5287
5288       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5289                          N->getDebugLoc(), TrTy, V,
5290                          DAG.getConstant(Index, IndexTy));
5291     }
5292   }
5293
5294   // See if we can simplify the input to this truncate through knowledge that
5295   // only the low bits are being used.
5296   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5297   // Currently we only perform this optimization on scalars because vectors
5298   // may have different active low bits.
5299   if (!VT.isVector()) {
5300     SDValue Shorter =
5301       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5302                                                VT.getSizeInBits()));
5303     if (Shorter.getNode())
5304       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5305   }
5306   // fold (truncate (load x)) -> (smaller load x)
5307   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5308   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5309     SDValue Reduced = ReduceLoadWidth(N);
5310     if (Reduced.getNode())
5311       return Reduced;
5312   }
5313   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5314   // where ... are all 'undef'.
5315   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5316     SmallVector<EVT, 8> VTs;
5317     SDValue V;
5318     unsigned Idx = 0;
5319     unsigned NumDefs = 0;
5320
5321     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5322       SDValue X = N0.getOperand(i);
5323       if (X.getOpcode() != ISD::UNDEF) {
5324         V = X;
5325         Idx = i;
5326         NumDefs++;
5327       }
5328       // Stop if more than one members are non-undef.
5329       if (NumDefs > 1)
5330         break;
5331       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5332                                      VT.getVectorElementType(),
5333                                      X.getValueType().getVectorNumElements()));
5334     }
5335
5336     if (NumDefs == 0)
5337       return DAG.getUNDEF(VT);
5338
5339     if (NumDefs == 1) {
5340       assert(V.getNode() && "The single defined operand is empty!");
5341       SmallVector<SDValue, 8> Opnds;
5342       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5343         if (i != Idx) {
5344           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5345           continue;
5346         }
5347         SDValue NV = DAG.getNode(ISD::TRUNCATE, V.getDebugLoc(), VTs[i], V);
5348         AddToWorkList(NV.getNode());
5349         Opnds.push_back(NV);
5350       }
5351       return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
5352                          &Opnds[0], Opnds.size());
5353     }
5354   }
5355
5356   // Simplify the operands using demanded-bits information.
5357   if (!VT.isVector() &&
5358       SimplifyDemandedBits(SDValue(N, 0)))
5359     return SDValue(N, 0);
5360
5361   return SDValue();
5362 }
5363
5364 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5365   SDValue Elt = N->getOperand(i);
5366   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5367     return Elt.getNode();
5368   return Elt.getOperand(Elt.getResNo()).getNode();
5369 }
5370
5371 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5372 /// if load locations are consecutive.
5373 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5374   assert(N->getOpcode() == ISD::BUILD_PAIR);
5375
5376   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5377   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5378   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5379       LD1->getPointerInfo().getAddrSpace() !=
5380          LD2->getPointerInfo().getAddrSpace())
5381     return SDValue();
5382   EVT LD1VT = LD1->getValueType(0);
5383
5384   if (ISD::isNON_EXTLoad(LD2) &&
5385       LD2->hasOneUse() &&
5386       // If both are volatile this would reduce the number of volatile loads.
5387       // If one is volatile it might be ok, but play conservative and bail out.
5388       !LD1->isVolatile() &&
5389       !LD2->isVolatile() &&
5390       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5391     unsigned Align = LD1->getAlignment();
5392     unsigned NewAlign = TLI.getDataLayout()->
5393       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5394
5395     if (NewAlign <= Align &&
5396         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5397       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5398                          LD1->getBasePtr(), LD1->getPointerInfo(),
5399                          false, false, false, Align);
5400   }
5401
5402   return SDValue();
5403 }
5404
5405 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5406   SDValue N0 = N->getOperand(0);
5407   EVT VT = N->getValueType(0);
5408
5409   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5410   // Only do this before legalize, since afterward the target may be depending
5411   // on the bitconvert.
5412   // First check to see if this is all constant.
5413   if (!LegalTypes &&
5414       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5415       VT.isVector()) {
5416     bool isSimple = true;
5417     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5418       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5419           N0.getOperand(i).getOpcode() != ISD::Constant &&
5420           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5421         isSimple = false;
5422         break;
5423       }
5424
5425     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5426     assert(!DestEltVT.isVector() &&
5427            "Element type of vector ValueType must not be vector!");
5428     if (isSimple)
5429       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5430   }
5431
5432   // If the input is a constant, let getNode fold it.
5433   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5434     SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5435     if (Res.getNode() != N) {
5436       if (!LegalOperations ||
5437           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5438         return Res;
5439
5440       // Folding it resulted in an illegal node, and it's too late to
5441       // do that. Clean up the old node and forego the transformation.
5442       // Ideally this won't happen very often, because instcombine
5443       // and the earlier dagcombine runs (where illegal nodes are
5444       // permitted) should have folded most of them already.
5445       DAG.DeleteNode(Res.getNode());
5446     }
5447   }
5448
5449   // (conv (conv x, t1), t2) -> (conv x, t2)
5450   if (N0.getOpcode() == ISD::BITCAST)
5451     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5452                        N0.getOperand(0));
5453
5454   // fold (conv (load x)) -> (load (conv*)x)
5455   // If the resultant load doesn't need a higher alignment than the original!
5456   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5457       // Do not change the width of a volatile load.
5458       !cast<LoadSDNode>(N0)->isVolatile() &&
5459       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5460     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5461     unsigned Align = TLI.getDataLayout()->
5462       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5463     unsigned OrigAlign = LN0->getAlignment();
5464
5465     if (Align <= OrigAlign) {
5466       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5467                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5468                                  LN0->isVolatile(), LN0->isNonTemporal(),
5469                                  LN0->isInvariant(), OrigAlign);
5470       AddToWorkList(N);
5471       CombineTo(N0.getNode(),
5472                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5473                             N0.getValueType(), Load),
5474                 Load.getValue(1));
5475       return Load;
5476     }
5477   }
5478
5479   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5480   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5481   // This often reduces constant pool loads.
5482   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5483        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5484       N0.getNode()->hasOneUse() && VT.isInteger() &&
5485       !VT.isVector() && !N0.getValueType().isVector()) {
5486     SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5487                                   N0.getOperand(0));
5488     AddToWorkList(NewConv.getNode());
5489
5490     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5491     if (N0.getOpcode() == ISD::FNEG)
5492       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5493                          NewConv, DAG.getConstant(SignBit, VT));
5494     assert(N0.getOpcode() == ISD::FABS);
5495     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5496                        NewConv, DAG.getConstant(~SignBit, VT));
5497   }
5498
5499   // fold (bitconvert (fcopysign cst, x)) ->
5500   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5501   // Note that we don't handle (copysign x, cst) because this can always be
5502   // folded to an fneg or fabs.
5503   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5504       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5505       VT.isInteger() && !VT.isVector()) {
5506     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5507     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5508     if (isTypeLegal(IntXVT)) {
5509       SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5510                               IntXVT, N0.getOperand(1));
5511       AddToWorkList(X.getNode());
5512
5513       // If X has a different width than the result/lhs, sext it or truncate it.
5514       unsigned VTWidth = VT.getSizeInBits();
5515       if (OrigXWidth < VTWidth) {
5516         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5517         AddToWorkList(X.getNode());
5518       } else if (OrigXWidth > VTWidth) {
5519         // To get the sign bit in the right place, we have to shift it right
5520         // before truncating.
5521         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5522                         X.getValueType(), X,
5523                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5524         AddToWorkList(X.getNode());
5525         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5526         AddToWorkList(X.getNode());
5527       }
5528
5529       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5530       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5531                       X, DAG.getConstant(SignBit, VT));
5532       AddToWorkList(X.getNode());
5533
5534       SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5535                                 VT, N0.getOperand(0));
5536       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5537                         Cst, DAG.getConstant(~SignBit, VT));
5538       AddToWorkList(Cst.getNode());
5539
5540       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5541     }
5542   }
5543
5544   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5545   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5546     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5547     if (CombineLD.getNode())
5548       return CombineLD;
5549   }
5550
5551   return SDValue();
5552 }
5553
5554 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5555   EVT VT = N->getValueType(0);
5556   return CombineConsecutiveLoads(N, VT);
5557 }
5558
5559 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5560 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5561 /// destination element value type.
5562 SDValue DAGCombiner::
5563 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5564   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5565
5566   // If this is already the right type, we're done.
5567   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5568
5569   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5570   unsigned DstBitSize = DstEltVT.getSizeInBits();
5571
5572   // If this is a conversion of N elements of one type to N elements of another
5573   // type, convert each element.  This handles FP<->INT cases.
5574   if (SrcBitSize == DstBitSize) {
5575     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5576                               BV->getValueType(0).getVectorNumElements());
5577
5578     // Due to the FP element handling below calling this routine recursively,
5579     // we can end up with a scalar-to-vector node here.
5580     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5581       return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5582                          DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5583                                      DstEltVT, BV->getOperand(0)));
5584
5585     SmallVector<SDValue, 8> Ops;
5586     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5587       SDValue Op = BV->getOperand(i);
5588       // If the vector element type is not legal, the BUILD_VECTOR operands
5589       // are promoted and implicitly truncated.  Make that explicit here.
5590       if (Op.getValueType() != SrcEltVT)
5591         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5592       Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5593                                 DstEltVT, Op));
5594       AddToWorkList(Ops.back().getNode());
5595     }
5596     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5597                        &Ops[0], Ops.size());
5598   }
5599
5600   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5601   // handle annoying details of growing/shrinking FP values, we convert them to
5602   // int first.
5603   if (SrcEltVT.isFloatingPoint()) {
5604     // Convert the input float vector to a int vector where the elements are the
5605     // same sizes.
5606     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5607     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5608     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5609     SrcEltVT = IntVT;
5610   }
5611
5612   // Now we know the input is an integer vector.  If the output is a FP type,
5613   // convert to integer first, then to FP of the right size.
5614   if (DstEltVT.isFloatingPoint()) {
5615     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5616     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5617     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5618
5619     // Next, convert to FP elements of the same size.
5620     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5621   }
5622
5623   // Okay, we know the src/dst types are both integers of differing types.
5624   // Handling growing first.
5625   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5626   if (SrcBitSize < DstBitSize) {
5627     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5628
5629     SmallVector<SDValue, 8> Ops;
5630     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5631          i += NumInputsPerOutput) {
5632       bool isLE = TLI.isLittleEndian();
5633       APInt NewBits = APInt(DstBitSize, 0);
5634       bool EltIsUndef = true;
5635       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5636         // Shift the previously computed bits over.
5637         NewBits <<= SrcBitSize;
5638         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5639         if (Op.getOpcode() == ISD::UNDEF) continue;
5640         EltIsUndef = false;
5641
5642         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5643                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5644       }
5645
5646       if (EltIsUndef)
5647         Ops.push_back(DAG.getUNDEF(DstEltVT));
5648       else
5649         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5650     }
5651
5652     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5653     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5654                        &Ops[0], Ops.size());
5655   }
5656
5657   // Finally, this must be the case where we are shrinking elements: each input
5658   // turns into multiple outputs.
5659   bool isS2V = ISD::isScalarToVector(BV);
5660   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5661   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5662                             NumOutputsPerInput*BV->getNumOperands());
5663   SmallVector<SDValue, 8> Ops;
5664
5665   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5666     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5667       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5668         Ops.push_back(DAG.getUNDEF(DstEltVT));
5669       continue;
5670     }
5671
5672     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5673                   getAPIntValue().zextOrTrunc(SrcBitSize);
5674
5675     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5676       APInt ThisVal = OpVal.trunc(DstBitSize);
5677       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5678       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5679         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5680         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5681                            Ops[0]);
5682       OpVal = OpVal.lshr(DstBitSize);
5683     }
5684
5685     // For big endian targets, swap the order of the pieces of each element.
5686     if (TLI.isBigEndian())
5687       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5688   }
5689
5690   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5691                      &Ops[0], Ops.size());
5692 }
5693
5694 SDValue DAGCombiner::visitFADD(SDNode *N) {
5695   SDValue N0 = N->getOperand(0);
5696   SDValue N1 = N->getOperand(1);
5697   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5698   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5699   EVT VT = N->getValueType(0);
5700
5701   // fold vector ops
5702   if (VT.isVector()) {
5703     SDValue FoldedVOp = SimplifyVBinOp(N);
5704     if (FoldedVOp.getNode()) return FoldedVOp;
5705   }
5706
5707   // fold (fadd c1, c2) -> c1 + c2
5708   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5709     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5710   // canonicalize constant to RHS
5711   if (N0CFP && !N1CFP)
5712     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5713   // fold (fadd A, 0) -> A
5714   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5715       N1CFP->getValueAPF().isZero())
5716     return N0;
5717   // fold (fadd A, (fneg B)) -> (fsub A, B)
5718   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5719     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5720     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5721                        GetNegatedExpression(N1, DAG, LegalOperations));
5722   // fold (fadd (fneg A), B) -> (fsub B, A)
5723   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5724     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5725     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5726                        GetNegatedExpression(N0, DAG, LegalOperations));
5727
5728   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5729   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5730       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5731       isa<ConstantFPSDNode>(N0.getOperand(1)))
5732     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5733                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5734                                    N0.getOperand(1), N1));
5735
5736   // In unsafe math mode, we can fold chains of FADD's of the same value
5737   // into multiplications.  This transform is not safe in general because
5738   // we are reducing the number of rounding steps.
5739   if (DAG.getTarget().Options.UnsafeFPMath &&
5740       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5741       !N0CFP && !N1CFP) {
5742     if (N0.getOpcode() == ISD::FMUL) {
5743       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5744       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5745
5746       // (fadd (fmul c, x), x) -> (fmul c+1, x)
5747       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5748         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5749                                      SDValue(CFP00, 0),
5750                                      DAG.getConstantFP(1.0, VT));
5751         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5752                            N1, NewCFP);
5753       }
5754
5755       // (fadd (fmul x, c), x) -> (fmul c+1, x)
5756       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5757         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5758                                      SDValue(CFP01, 0),
5759                                      DAG.getConstantFP(1.0, VT));
5760         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5761                            N1, NewCFP);
5762       }
5763
5764       // (fadd (fadd x, x), x) -> (fmul 3.0, x)
5765       if (!CFP00 && !CFP01 && N0.getOperand(0) == N0.getOperand(1) &&
5766           N0.getOperand(0) == N1) {
5767         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5768                            N1, DAG.getConstantFP(3.0, VT));
5769       }
5770
5771       // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x)
5772       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5773           N1.getOperand(0) == N1.getOperand(1) &&
5774           N0.getOperand(1) == N1.getOperand(0)) {
5775         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5776                                      SDValue(CFP00, 0),
5777                                      DAG.getConstantFP(2.0, VT));
5778         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5779                            N0.getOperand(1), NewCFP);
5780       }
5781
5782       // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x)
5783       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5784           N1.getOperand(0) == N1.getOperand(1) &&
5785           N0.getOperand(0) == N1.getOperand(0)) {
5786         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5787                                      SDValue(CFP01, 0),
5788                                      DAG.getConstantFP(2.0, VT));
5789         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5790                            N0.getOperand(0), NewCFP);
5791       }
5792     }
5793
5794     if (N1.getOpcode() == ISD::FMUL) {
5795       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5796       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
5797
5798       // (fadd x, (fmul c, x)) -> (fmul c+1, x)
5799       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
5800         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5801                                      SDValue(CFP10, 0),
5802                                      DAG.getConstantFP(1.0, VT));
5803         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5804                            N0, NewCFP);
5805       }
5806
5807       // (fadd x, (fmul x, c)) -> (fmul c+1, x)
5808       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
5809         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5810                                      SDValue(CFP11, 0),
5811                                      DAG.getConstantFP(1.0, VT));
5812         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5813                            N0, NewCFP);
5814       }
5815
5816       // (fadd x, (fadd x, x)) -> (fmul 3.0, x)
5817       if (!CFP10 && !CFP11 && N1.getOperand(0) == N1.getOperand(1) &&
5818           N1.getOperand(0) == N0) {
5819         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5820                            N0, DAG.getConstantFP(3.0, VT));
5821       }
5822
5823       // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x)
5824       if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD &&
5825           N1.getOperand(0) == N1.getOperand(1) &&
5826           N0.getOperand(1) == N1.getOperand(0)) {
5827         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5828                                      SDValue(CFP10, 0),
5829                                      DAG.getConstantFP(2.0, VT));
5830         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5831                            N0.getOperand(1), NewCFP);
5832       }
5833
5834       // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x)
5835       if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD &&
5836           N1.getOperand(0) == N1.getOperand(1) &&
5837           N0.getOperand(0) == N1.getOperand(0)) {
5838         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5839                                      SDValue(CFP11, 0),
5840                                      DAG.getConstantFP(2.0, VT));
5841         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5842                            N0.getOperand(0), NewCFP);
5843       }
5844     }
5845
5846     // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x)
5847     if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
5848         N0.getOperand(0) == N0.getOperand(1) &&
5849         N1.getOperand(0) == N1.getOperand(1) &&
5850         N0.getOperand(0) == N1.getOperand(0)) {
5851       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5852                          N0.getOperand(0),
5853                          DAG.getConstantFP(4.0, VT));
5854     }
5855   }
5856
5857   // FADD -> FMA combines:
5858   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5859        DAG.getTarget().Options.UnsafeFPMath) &&
5860       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5861       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5862
5863     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5864     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5865       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5866                          N0.getOperand(0), N0.getOperand(1), N1);
5867     }
5868
5869     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
5870     // Note: Commutes FADD operands.
5871     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5872       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5873                          N1.getOperand(0), N1.getOperand(1), N0);
5874     }
5875   }
5876
5877   return SDValue();
5878 }
5879
5880 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5881   SDValue N0 = N->getOperand(0);
5882   SDValue N1 = N->getOperand(1);
5883   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5884   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5885   EVT VT = N->getValueType(0);
5886   DebugLoc dl = N->getDebugLoc();
5887
5888   // fold vector ops
5889   if (VT.isVector()) {
5890     SDValue FoldedVOp = SimplifyVBinOp(N);
5891     if (FoldedVOp.getNode()) return FoldedVOp;
5892   }
5893
5894   // fold (fsub c1, c2) -> c1-c2
5895   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5896     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5897   // fold (fsub A, 0) -> A
5898   if (DAG.getTarget().Options.UnsafeFPMath &&
5899       N1CFP && N1CFP->getValueAPF().isZero())
5900     return N0;
5901   // fold (fsub 0, B) -> -B
5902   if (DAG.getTarget().Options.UnsafeFPMath &&
5903       N0CFP && N0CFP->getValueAPF().isZero()) {
5904     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5905       return GetNegatedExpression(N1, DAG, LegalOperations);
5906     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5907       return DAG.getNode(ISD::FNEG, dl, VT, N1);
5908   }
5909   // fold (fsub A, (fneg B)) -> (fadd A, B)
5910   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5911     return DAG.getNode(ISD::FADD, dl, VT, N0,
5912                        GetNegatedExpression(N1, DAG, LegalOperations));
5913
5914   // If 'unsafe math' is enabled, fold
5915   //    (fsub x, x) -> 0.0 &
5916   //    (fsub x, (fadd x, y)) -> (fneg y) &
5917   //    (fsub x, (fadd y, x)) -> (fneg y)
5918   if (DAG.getTarget().Options.UnsafeFPMath) {
5919     if (N0 == N1)
5920       return DAG.getConstantFP(0.0f, VT);
5921
5922     if (N1.getOpcode() == ISD::FADD) {
5923       SDValue N10 = N1->getOperand(0);
5924       SDValue N11 = N1->getOperand(1);
5925
5926       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
5927                                           &DAG.getTarget().Options))
5928         return GetNegatedExpression(N11, DAG, LegalOperations);
5929       else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
5930                                                &DAG.getTarget().Options))
5931         return GetNegatedExpression(N10, DAG, LegalOperations);
5932     }
5933   }
5934
5935   // FSUB -> FMA combines:
5936   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5937        DAG.getTarget().Options.UnsafeFPMath) &&
5938       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5939       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5940
5941     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
5942     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5943       return DAG.getNode(ISD::FMA, dl, VT,
5944                          N0.getOperand(0), N0.getOperand(1),
5945                          DAG.getNode(ISD::FNEG, dl, VT, N1));
5946     }
5947
5948     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
5949     // Note: Commutes FSUB operands.
5950     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5951       return DAG.getNode(ISD::FMA, dl, VT,
5952                          DAG.getNode(ISD::FNEG, dl, VT,
5953                          N1.getOperand(0)),
5954                          N1.getOperand(1), N0);
5955     }
5956
5957     // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
5958     if (N0.getOpcode() == ISD::FNEG && 
5959         N0.getOperand(0).getOpcode() == ISD::FMUL &&
5960         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
5961       SDValue N00 = N0.getOperand(0).getOperand(0);
5962       SDValue N01 = N0.getOperand(0).getOperand(1);
5963       return DAG.getNode(ISD::FMA, dl, VT,
5964                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
5965                          DAG.getNode(ISD::FNEG, dl, VT, N1));
5966     }
5967   }
5968
5969   return SDValue();
5970 }
5971
5972 SDValue DAGCombiner::visitFMUL(SDNode *N) {
5973   SDValue N0 = N->getOperand(0);
5974   SDValue N1 = N->getOperand(1);
5975   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5976   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5977   EVT VT = N->getValueType(0);
5978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5979
5980   // fold vector ops
5981   if (VT.isVector()) {
5982     SDValue FoldedVOp = SimplifyVBinOp(N);
5983     if (FoldedVOp.getNode()) return FoldedVOp;
5984   }
5985
5986   // fold (fmul c1, c2) -> c1*c2
5987   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5988     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5989   // canonicalize constant to RHS
5990   if (N0CFP && !N1CFP)
5991     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5992   // fold (fmul A, 0) -> 0
5993   if (DAG.getTarget().Options.UnsafeFPMath &&
5994       N1CFP && N1CFP->getValueAPF().isZero())
5995     return N1;
5996   // fold (fmul A, 0) -> 0, vector edition.
5997   if (DAG.getTarget().Options.UnsafeFPMath &&
5998       ISD::isBuildVectorAllZeros(N1.getNode()))
5999     return N1;
6000   // fold (fmul A, 1.0) -> A
6001   if (N1CFP && N1CFP->isExactlyValue(1.0))
6002     return N0;
6003   // fold (fmul X, 2.0) -> (fadd X, X)
6004   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6005     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
6006   // fold (fmul X, -1.0) -> (fneg X)
6007   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6008     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6009       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
6010
6011   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6012   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6013                                        &DAG.getTarget().Options)) {
6014     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 
6015                                          &DAG.getTarget().Options)) {
6016       // Both can be negated for free, check to see if at least one is cheaper
6017       // negated.
6018       if (LHSNeg == 2 || RHSNeg == 2)
6019         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6020                            GetNegatedExpression(N0, DAG, LegalOperations),
6021                            GetNegatedExpression(N1, DAG, LegalOperations));
6022     }
6023   }
6024
6025   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6026   if (DAG.getTarget().Options.UnsafeFPMath &&
6027       N1CFP && N0.getOpcode() == ISD::FMUL &&
6028       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6029     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
6030                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6031                                    N0.getOperand(1), N1));
6032
6033   return SDValue();
6034 }
6035
6036 SDValue DAGCombiner::visitFMA(SDNode *N) {
6037   SDValue N0 = N->getOperand(0);
6038   SDValue N1 = N->getOperand(1);
6039   SDValue N2 = N->getOperand(2);
6040   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6041   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6042   EVT VT = N->getValueType(0);
6043   DebugLoc dl = N->getDebugLoc();
6044
6045   if (N0CFP && N0CFP->isExactlyValue(1.0))
6046     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
6047   if (N1CFP && N1CFP->isExactlyValue(1.0))
6048     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
6049
6050   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6051   if (N0CFP && !N1CFP)
6052     return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
6053
6054   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6055   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6056       N2.getOpcode() == ISD::FMUL &&
6057       N0 == N2.getOperand(0) &&
6058       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6059     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6060                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6061   }
6062
6063
6064   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6065   if (DAG.getTarget().Options.UnsafeFPMath &&
6066       N0.getOpcode() == ISD::FMUL && N1CFP &&
6067       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6068     return DAG.getNode(ISD::FMA, dl, VT,
6069                        N0.getOperand(0),
6070                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6071                        N2);
6072   }
6073
6074   // (fma x, 1, y) -> (fadd x, y)
6075   // (fma x, -1, y) -> (fadd (fneg x), y)
6076   if (N1CFP) {
6077     if (N1CFP->isExactlyValue(1.0))
6078       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6079
6080     if (N1CFP->isExactlyValue(-1.0) &&
6081         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6082       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6083       AddToWorkList(RHSNeg.getNode());
6084       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6085     }
6086   }
6087
6088   // (fma x, c, x) -> (fmul x, (c+1))
6089   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6090     return DAG.getNode(ISD::FMUL, dl, VT,
6091                        N0,
6092                        DAG.getNode(ISD::FADD, dl, VT,
6093                                    N1, DAG.getConstantFP(1.0, VT)));
6094   }
6095
6096   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6097   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6098       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6099     return DAG.getNode(ISD::FMUL, dl, VT,
6100                        N0,
6101                        DAG.getNode(ISD::FADD, dl, VT,
6102                                    N1, DAG.getConstantFP(-1.0, VT)));
6103   }
6104
6105
6106   return SDValue();
6107 }
6108
6109 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6110   SDValue N0 = N->getOperand(0);
6111   SDValue N1 = N->getOperand(1);
6112   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6113   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6114   EVT VT = N->getValueType(0);
6115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6116
6117   // fold vector ops
6118   if (VT.isVector()) {
6119     SDValue FoldedVOp = SimplifyVBinOp(N);
6120     if (FoldedVOp.getNode()) return FoldedVOp;
6121   }
6122
6123   // fold (fdiv c1, c2) -> c1/c2
6124   if (N0CFP && N1CFP && VT != MVT::ppcf128)
6125     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
6126
6127   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6128   if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) {
6129     // Compute the reciprocal 1.0 / c2.
6130     APFloat N1APF = N1CFP->getValueAPF();
6131     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6132     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6133     // Only do the transform if the reciprocal is a legal fp immediate that
6134     // isn't too nasty (eg NaN, denormal, ...).
6135     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6136         (!LegalOperations ||
6137          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6138          // backend)... we should handle this gracefully after Legalize.
6139          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6140          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6141          TLI.isFPImmLegal(Recip, VT)))
6142       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
6143                          DAG.getConstantFP(Recip, VT));
6144   }
6145
6146   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6147   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6148                                        &DAG.getTarget().Options)) {
6149     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6150                                          &DAG.getTarget().Options)) {
6151       // Both can be negated for free, check to see if at least one is cheaper
6152       // negated.
6153       if (LHSNeg == 2 || RHSNeg == 2)
6154         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
6155                            GetNegatedExpression(N0, DAG, LegalOperations),
6156                            GetNegatedExpression(N1, DAG, LegalOperations));
6157     }
6158   }
6159
6160   return SDValue();
6161 }
6162
6163 SDValue DAGCombiner::visitFREM(SDNode *N) {
6164   SDValue N0 = N->getOperand(0);
6165   SDValue N1 = N->getOperand(1);
6166   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6167   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6168   EVT VT = N->getValueType(0);
6169
6170   // fold (frem c1, c2) -> fmod(c1,c2)
6171   if (N0CFP && N1CFP && VT != MVT::ppcf128)
6172     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
6173
6174   return SDValue();
6175 }
6176
6177 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6178   SDValue N0 = N->getOperand(0);
6179   SDValue N1 = N->getOperand(1);
6180   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6181   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6182   EVT VT = N->getValueType(0);
6183
6184   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
6185     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
6186
6187   if (N1CFP) {
6188     const APFloat& V = N1CFP->getValueAPF();
6189     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6190     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6191     if (!V.isNegative()) {
6192       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6193         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6194     } else {
6195       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6196         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6197                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
6198     }
6199   }
6200
6201   // copysign(fabs(x), y) -> copysign(x, y)
6202   // copysign(fneg(x), y) -> copysign(x, y)
6203   // copysign(copysign(x,z), y) -> copysign(x, y)
6204   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6205       N0.getOpcode() == ISD::FCOPYSIGN)
6206     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6207                        N0.getOperand(0), N1);
6208
6209   // copysign(x, abs(y)) -> abs(x)
6210   if (N1.getOpcode() == ISD::FABS)
6211     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6212
6213   // copysign(x, copysign(y,z)) -> copysign(x, z)
6214   if (N1.getOpcode() == ISD::FCOPYSIGN)
6215     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6216                        N0, N1.getOperand(1));
6217
6218   // copysign(x, fp_extend(y)) -> copysign(x, y)
6219   // copysign(x, fp_round(y)) -> copysign(x, y)
6220   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6221     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6222                        N0, N1.getOperand(0));
6223
6224   return SDValue();
6225 }
6226
6227 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6228   SDValue N0 = N->getOperand(0);
6229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6230   EVT VT = N->getValueType(0);
6231   EVT OpVT = N0.getValueType();
6232
6233   // fold (sint_to_fp c1) -> c1fp
6234   if (N0C && OpVT != MVT::ppcf128 &&
6235       // ...but only if the target supports immediate floating-point values
6236       (!LegalOperations ||
6237        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6238     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6239
6240   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6241   // but UINT_TO_FP is legal on this target, try to convert.
6242   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6243       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6244     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6245     if (DAG.SignBitIsZero(N0))
6246       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6247   }
6248
6249   // The next optimizations are desireable only if SELECT_CC can be lowered.
6250   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6251   // having to say they don't support SELECT_CC on every type the DAG knows
6252   // about, since there is no way to mark an opcode illegal at all value types
6253   // (See also visitSELECT)
6254   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6255     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6256     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6257         !VT.isVector() &&
6258         (!LegalOperations ||
6259          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6260       SDValue Ops[] =
6261         { N0.getOperand(0), N0.getOperand(1),
6262           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6263           N0.getOperand(2) };
6264       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6265     }
6266
6267     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6268     //      (select_cc x, y, 1.0, 0.0,, cc)
6269     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6270         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6271         (!LegalOperations ||
6272          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6273       SDValue Ops[] =
6274         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6275           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6276           N0.getOperand(0).getOperand(2) };
6277       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6278     }
6279   }
6280
6281   return SDValue();
6282 }
6283
6284 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6285   SDValue N0 = N->getOperand(0);
6286   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6287   EVT VT = N->getValueType(0);
6288   EVT OpVT = N0.getValueType();
6289
6290   // fold (uint_to_fp c1) -> c1fp
6291   if (N0C && OpVT != MVT::ppcf128 &&
6292       // ...but only if the target supports immediate floating-point values
6293       (!LegalOperations ||
6294        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6295     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6296
6297   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6298   // but SINT_TO_FP is legal on this target, try to convert.
6299   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6300       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6301     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6302     if (DAG.SignBitIsZero(N0))
6303       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6304   }
6305
6306   // The next optimizations are desireable only if SELECT_CC can be lowered.
6307   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6308   // having to say they don't support SELECT_CC on every type the DAG knows
6309   // about, since there is no way to mark an opcode illegal at all value types
6310   // (See also visitSELECT)
6311   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6312     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6313
6314     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6315         (!LegalOperations ||
6316          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6317       SDValue Ops[] =
6318         { N0.getOperand(0), N0.getOperand(1),
6319           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6320           N0.getOperand(2) };
6321       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6322     }
6323   }
6324
6325   return SDValue();
6326 }
6327
6328 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6329   SDValue N0 = N->getOperand(0);
6330   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6331   EVT VT = N->getValueType(0);
6332
6333   // fold (fp_to_sint c1fp) -> c1
6334   if (N0CFP)
6335     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6336
6337   return SDValue();
6338 }
6339
6340 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6341   SDValue N0 = N->getOperand(0);
6342   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6343   EVT VT = N->getValueType(0);
6344
6345   // fold (fp_to_uint c1fp) -> c1
6346   if (N0CFP && VT != MVT::ppcf128)
6347     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6348
6349   return SDValue();
6350 }
6351
6352 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6353   SDValue N0 = N->getOperand(0);
6354   SDValue N1 = N->getOperand(1);
6355   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6356   EVT VT = N->getValueType(0);
6357
6358   // fold (fp_round c1fp) -> c1fp
6359   if (N0CFP && N0.getValueType() != MVT::ppcf128)
6360     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6361
6362   // fold (fp_round (fp_extend x)) -> x
6363   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6364     return N0.getOperand(0);
6365
6366   // fold (fp_round (fp_round x)) -> (fp_round x)
6367   if (N0.getOpcode() == ISD::FP_ROUND) {
6368     // This is a value preserving truncation if both round's are.
6369     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6370                    N0.getNode()->getConstantOperandVal(1) == 1;
6371     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6372                        DAG.getIntPtrConstant(IsTrunc));
6373   }
6374
6375   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6376   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6377     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6378                               N0.getOperand(0), N1);
6379     AddToWorkList(Tmp.getNode());
6380     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6381                        Tmp, N0.getOperand(1));
6382   }
6383
6384   return SDValue();
6385 }
6386
6387 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6388   SDValue N0 = N->getOperand(0);
6389   EVT VT = N->getValueType(0);
6390   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6391   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6392
6393   // fold (fp_round_inreg c1fp) -> c1fp
6394   if (N0CFP && isTypeLegal(EVT)) {
6395     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6396     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6397   }
6398
6399   return SDValue();
6400 }
6401
6402 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6403   SDValue N0 = N->getOperand(0);
6404   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6405   EVT VT = N->getValueType(0);
6406
6407   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6408   if (N->hasOneUse() &&
6409       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6410     return SDValue();
6411
6412   // fold (fp_extend c1fp) -> c1fp
6413   if (N0CFP && VT != MVT::ppcf128)
6414     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6415
6416   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6417   // value of X.
6418   if (N0.getOpcode() == ISD::FP_ROUND
6419       && N0.getNode()->getConstantOperandVal(1) == 1) {
6420     SDValue In = N0.getOperand(0);
6421     if (In.getValueType() == VT) return In;
6422     if (VT.bitsLT(In.getValueType()))
6423       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6424                          In, N0.getOperand(1));
6425     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6426   }
6427
6428   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6429   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6430       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6431        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6432     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6433     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6434                                      LN0->getChain(),
6435                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6436                                      N0.getValueType(),
6437                                      LN0->isVolatile(), LN0->isNonTemporal(),
6438                                      LN0->getAlignment());
6439     CombineTo(N, ExtLoad);
6440     CombineTo(N0.getNode(),
6441               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6442                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6443               ExtLoad.getValue(1));
6444     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6445   }
6446
6447   return SDValue();
6448 }
6449
6450 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6451   SDValue N0 = N->getOperand(0);
6452   EVT VT = N->getValueType(0);
6453
6454   if (VT.isVector()) {
6455     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6456     if (FoldedVOp.getNode()) return FoldedVOp;
6457   }
6458
6459   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6460                          &DAG.getTarget().Options))
6461     return GetNegatedExpression(N0, DAG, LegalOperations);
6462
6463   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6464   // constant pool values.
6465   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6466       !VT.isVector() &&
6467       N0.getNode()->hasOneUse() &&
6468       N0.getOperand(0).getValueType().isInteger()) {
6469     SDValue Int = N0.getOperand(0);
6470     EVT IntVT = Int.getValueType();
6471     if (IntVT.isInteger() && !IntVT.isVector()) {
6472       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6473               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6474       AddToWorkList(Int.getNode());
6475       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6476                          VT, Int);
6477     }
6478   }
6479
6480   // (fneg (fmul c, x)) -> (fmul -c, x)
6481   if (N0.getOpcode() == ISD::FMUL) {
6482     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6483     if (CFP1) {
6484       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6485                          N0.getOperand(0),
6486                          DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6487                                      N0.getOperand(1)));
6488     }
6489   }
6490
6491   return SDValue();
6492 }
6493
6494 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6495   SDValue N0 = N->getOperand(0);
6496   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6497   EVT VT = N->getValueType(0);
6498
6499   // fold (fceil c1) -> fceil(c1)
6500   if (N0CFP && VT != MVT::ppcf128)
6501     return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
6502
6503   return SDValue();
6504 }
6505
6506 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6507   SDValue N0 = N->getOperand(0);
6508   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6509   EVT VT = N->getValueType(0);
6510
6511   // fold (ftrunc c1) -> ftrunc(c1)
6512   if (N0CFP && VT != MVT::ppcf128)
6513     return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
6514
6515   return SDValue();
6516 }
6517
6518 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6519   SDValue N0 = N->getOperand(0);
6520   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6521   EVT VT = N->getValueType(0);
6522
6523   // fold (ffloor c1) -> ffloor(c1)
6524   if (N0CFP && VT != MVT::ppcf128)
6525     return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
6526
6527   return SDValue();
6528 }
6529
6530 SDValue DAGCombiner::visitFABS(SDNode *N) {
6531   SDValue N0 = N->getOperand(0);
6532   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6533   EVT VT = N->getValueType(0);
6534
6535   if (VT.isVector()) {
6536     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6537     if (FoldedVOp.getNode()) return FoldedVOp;
6538   }
6539
6540   // fold (fabs c1) -> fabs(c1)
6541   if (N0CFP && VT != MVT::ppcf128)
6542     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6543   // fold (fabs (fabs x)) -> (fabs x)
6544   if (N0.getOpcode() == ISD::FABS)
6545     return N->getOperand(0);
6546   // fold (fabs (fneg x)) -> (fabs x)
6547   // fold (fabs (fcopysign x, y)) -> (fabs x)
6548   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6549     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6550
6551   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6552   // constant pool values.
6553   if (!TLI.isFAbsFree(VT) && 
6554       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6555       N0.getOperand(0).getValueType().isInteger() &&
6556       !N0.getOperand(0).getValueType().isVector()) {
6557     SDValue Int = N0.getOperand(0);
6558     EVT IntVT = Int.getValueType();
6559     if (IntVT.isInteger() && !IntVT.isVector()) {
6560       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6561              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6562       AddToWorkList(Int.getNode());
6563       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6564                          N->getValueType(0), Int);
6565     }
6566   }
6567
6568   return SDValue();
6569 }
6570
6571 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6572   SDValue Chain = N->getOperand(0);
6573   SDValue N1 = N->getOperand(1);
6574   SDValue N2 = N->getOperand(2);
6575
6576   // If N is a constant we could fold this into a fallthrough or unconditional
6577   // branch. However that doesn't happen very often in normal code, because
6578   // Instcombine/SimplifyCFG should have handled the available opportunities.
6579   // If we did this folding here, it would be necessary to update the
6580   // MachineBasicBlock CFG, which is awkward.
6581
6582   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6583   // on the target.
6584   if (N1.getOpcode() == ISD::SETCC &&
6585       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
6586     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6587                        Chain, N1.getOperand(2),
6588                        N1.getOperand(0), N1.getOperand(1), N2);
6589   }
6590
6591   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6592       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6593        (N1.getOperand(0).hasOneUse() &&
6594         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6595     SDNode *Trunc = 0;
6596     if (N1.getOpcode() == ISD::TRUNCATE) {
6597       // Look pass the truncate.
6598       Trunc = N1.getNode();
6599       N1 = N1.getOperand(0);
6600     }
6601
6602     // Match this pattern so that we can generate simpler code:
6603     //
6604     //   %a = ...
6605     //   %b = and i32 %a, 2
6606     //   %c = srl i32 %b, 1
6607     //   brcond i32 %c ...
6608     //
6609     // into
6610     //
6611     //   %a = ...
6612     //   %b = and i32 %a, 2
6613     //   %c = setcc eq %b, 0
6614     //   brcond %c ...
6615     //
6616     // This applies only when the AND constant value has one bit set and the
6617     // SRL constant is equal to the log2 of the AND constant. The back-end is
6618     // smart enough to convert the result into a TEST/JMP sequence.
6619     SDValue Op0 = N1.getOperand(0);
6620     SDValue Op1 = N1.getOperand(1);
6621
6622     if (Op0.getOpcode() == ISD::AND &&
6623         Op1.getOpcode() == ISD::Constant) {
6624       SDValue AndOp1 = Op0.getOperand(1);
6625
6626       if (AndOp1.getOpcode() == ISD::Constant) {
6627         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6628
6629         if (AndConst.isPowerOf2() &&
6630             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6631           SDValue SetCC =
6632             DAG.getSetCC(N->getDebugLoc(),
6633                          TLI.getSetCCResultType(Op0.getValueType()),
6634                          Op0, DAG.getConstant(0, Op0.getValueType()),
6635                          ISD::SETNE);
6636
6637           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6638                                           MVT::Other, Chain, SetCC, N2);
6639           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6640           // will convert it back to (X & C1) >> C2.
6641           CombineTo(N, NewBRCond, false);
6642           // Truncate is dead.
6643           if (Trunc) {
6644             removeFromWorkList(Trunc);
6645             DAG.DeleteNode(Trunc);
6646           }
6647           // Replace the uses of SRL with SETCC
6648           WorkListRemover DeadNodes(*this);
6649           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6650           removeFromWorkList(N1.getNode());
6651           DAG.DeleteNode(N1.getNode());
6652           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6653         }
6654       }
6655     }
6656
6657     if (Trunc)
6658       // Restore N1 if the above transformation doesn't match.
6659       N1 = N->getOperand(1);
6660   }
6661
6662   // Transform br(xor(x, y)) -> br(x != y)
6663   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6664   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6665     SDNode *TheXor = N1.getNode();
6666     SDValue Op0 = TheXor->getOperand(0);
6667     SDValue Op1 = TheXor->getOperand(1);
6668     if (Op0.getOpcode() == Op1.getOpcode()) {
6669       // Avoid missing important xor optimizations.
6670       SDValue Tmp = visitXOR(TheXor);
6671       if (Tmp.getNode() && Tmp.getNode() != TheXor) {
6672         DEBUG(dbgs() << "\nReplacing.8 ";
6673               TheXor->dump(&DAG);
6674               dbgs() << "\nWith: ";
6675               Tmp.getNode()->dump(&DAG);
6676               dbgs() << '\n');
6677         WorkListRemover DeadNodes(*this);
6678         DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6679         removeFromWorkList(TheXor);
6680         DAG.DeleteNode(TheXor);
6681         return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6682                            MVT::Other, Chain, Tmp, N2);
6683       }
6684     }
6685
6686     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6687       bool Equal = false;
6688       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6689         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6690             Op0.getOpcode() == ISD::XOR) {
6691           TheXor = Op0.getNode();
6692           Equal = true;
6693         }
6694
6695       EVT SetCCVT = N1.getValueType();
6696       if (LegalTypes)
6697         SetCCVT = TLI.getSetCCResultType(SetCCVT);
6698       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6699                                    SetCCVT,
6700                                    Op0, Op1,
6701                                    Equal ? ISD::SETEQ : ISD::SETNE);
6702       // Replace the uses of XOR with SETCC
6703       WorkListRemover DeadNodes(*this);
6704       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6705       removeFromWorkList(N1.getNode());
6706       DAG.DeleteNode(N1.getNode());
6707       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6708                          MVT::Other, Chain, SetCC, N2);
6709     }
6710   }
6711
6712   return SDValue();
6713 }
6714
6715 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6716 //
6717 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6718   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6719   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6720
6721   // If N is a constant we could fold this into a fallthrough or unconditional
6722   // branch. However that doesn't happen very often in normal code, because
6723   // Instcombine/SimplifyCFG should have handled the available opportunities.
6724   // If we did this folding here, it would be necessary to update the
6725   // MachineBasicBlock CFG, which is awkward.
6726
6727   // Use SimplifySetCC to simplify SETCC's.
6728   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6729                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6730                                false);
6731   if (Simp.getNode()) AddToWorkList(Simp.getNode());
6732
6733   // fold to a simpler setcc
6734   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6735     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6736                        N->getOperand(0), Simp.getOperand(2),
6737                        Simp.getOperand(0), Simp.getOperand(1),
6738                        N->getOperand(4));
6739
6740   return SDValue();
6741 }
6742
6743 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6744 /// uses N as its base pointer and that N may be folded in the load / store
6745 /// addressing mode.
6746 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6747                                     SelectionDAG &DAG,
6748                                     const TargetLowering &TLI) {
6749   EVT VT;
6750   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6751     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6752       return false;
6753     VT = Use->getValueType(0);
6754   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6755     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6756       return false;
6757     VT = ST->getValue().getValueType();
6758   } else
6759     return false;
6760
6761   AddrMode AM;
6762   if (N->getOpcode() == ISD::ADD) {
6763     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6764     if (Offset)
6765       // [reg +/- imm]
6766       AM.BaseOffs = Offset->getSExtValue();
6767     else
6768       // [reg +/- reg]
6769       AM.Scale = 1;
6770   } else if (N->getOpcode() == ISD::SUB) {
6771     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6772     if (Offset)
6773       // [reg +/- imm]
6774       AM.BaseOffs = -Offset->getSExtValue();
6775     else
6776       // [reg +/- reg]
6777       AM.Scale = 1;
6778   } else
6779     return false;
6780
6781   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6782 }
6783
6784 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6785 /// pre-indexed load / store when the base pointer is an add or subtract
6786 /// and it has other uses besides the load / store. After the
6787 /// transformation, the new indexed load / store has effectively folded
6788 /// the add / subtract in and all of its other uses are redirected to the
6789 /// new load / store.
6790 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6791   if (Level < AfterLegalizeDAG)
6792     return false;
6793
6794   bool isLoad = true;
6795   SDValue Ptr;
6796   EVT VT;
6797   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6798     if (LD->isIndexed())
6799       return false;
6800     VT = LD->getMemoryVT();
6801     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6802         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6803       return false;
6804     Ptr = LD->getBasePtr();
6805   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6806     if (ST->isIndexed())
6807       return false;
6808     VT = ST->getMemoryVT();
6809     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6810         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6811       return false;
6812     Ptr = ST->getBasePtr();
6813     isLoad = false;
6814   } else {
6815     return false;
6816   }
6817
6818   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6819   // out.  There is no reason to make this a preinc/predec.
6820   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6821       Ptr.getNode()->hasOneUse())
6822     return false;
6823
6824   // Ask the target to do addressing mode selection.
6825   SDValue BasePtr;
6826   SDValue Offset;
6827   ISD::MemIndexedMode AM = ISD::UNINDEXED;
6828   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6829     return false;
6830   // Don't create a indexed load / store with zero offset.
6831   if (isa<ConstantSDNode>(Offset) &&
6832       cast<ConstantSDNode>(Offset)->isNullValue())
6833     return false;
6834
6835   // Try turning it into a pre-indexed load / store except when:
6836   // 1) The new base ptr is a frame index.
6837   // 2) If N is a store and the new base ptr is either the same as or is a
6838   //    predecessor of the value being stored.
6839   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6840   //    that would create a cycle.
6841   // 4) All uses are load / store ops that use it as old base ptr.
6842
6843   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
6844   // (plus the implicit offset) to a register to preinc anyway.
6845   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6846     return false;
6847
6848   // Check #2.
6849   if (!isLoad) {
6850     SDValue Val = cast<StoreSDNode>(N)->getValue();
6851     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
6852       return false;
6853   }
6854
6855   // Now check for #3 and #4.
6856   bool RealUse = false;
6857
6858   // Caches for hasPredecessorHelper
6859   SmallPtrSet<const SDNode *, 32> Visited;
6860   SmallVector<const SDNode *, 16> Worklist;
6861
6862   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6863          E = Ptr.getNode()->use_end(); I != E; ++I) {
6864     SDNode *Use = *I;
6865     if (Use == N)
6866       continue;
6867     if (N->hasPredecessorHelper(Use, Visited, Worklist))
6868       return false;
6869
6870     // If Ptr may be folded in addressing mode of other use, then it's
6871     // not profitable to do this transformation.
6872     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
6873       RealUse = true;
6874   }
6875
6876   if (!RealUse)
6877     return false;
6878
6879   SDValue Result;
6880   if (isLoad)
6881     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6882                                 BasePtr, Offset, AM);
6883   else
6884     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6885                                  BasePtr, Offset, AM);
6886   ++PreIndexedNodes;
6887   ++NodesCombined;
6888   DEBUG(dbgs() << "\nReplacing.4 ";
6889         N->dump(&DAG);
6890         dbgs() << "\nWith: ";
6891         Result.getNode()->dump(&DAG);
6892         dbgs() << '\n');
6893   WorkListRemover DeadNodes(*this);
6894   if (isLoad) {
6895     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6896     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6897   } else {
6898     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6899   }
6900
6901   // Finally, since the node is now dead, remove it from the graph.
6902   DAG.DeleteNode(N);
6903
6904   // Replace the uses of Ptr with uses of the updated base value.
6905   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
6906   removeFromWorkList(Ptr.getNode());
6907   DAG.DeleteNode(Ptr.getNode());
6908
6909   return true;
6910 }
6911
6912 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6913 /// add / sub of the base pointer node into a post-indexed load / store.
6914 /// The transformation folded the add / subtract into the new indexed
6915 /// load / store effectively and all of its uses are redirected to the
6916 /// new load / store.
6917 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6918   if (Level < AfterLegalizeDAG)
6919     return false;
6920
6921   bool isLoad = true;
6922   SDValue Ptr;
6923   EVT VT;
6924   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6925     if (LD->isIndexed())
6926       return false;
6927     VT = LD->getMemoryVT();
6928     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6929         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6930       return false;
6931     Ptr = LD->getBasePtr();
6932   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6933     if (ST->isIndexed())
6934       return false;
6935     VT = ST->getMemoryVT();
6936     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6937         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6938       return false;
6939     Ptr = ST->getBasePtr();
6940     isLoad = false;
6941   } else {
6942     return false;
6943   }
6944
6945   if (Ptr.getNode()->hasOneUse())
6946     return false;
6947
6948   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6949          E = Ptr.getNode()->use_end(); I != E; ++I) {
6950     SDNode *Op = *I;
6951     if (Op == N ||
6952         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6953       continue;
6954
6955     SDValue BasePtr;
6956     SDValue Offset;
6957     ISD::MemIndexedMode AM = ISD::UNINDEXED;
6958     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6959       // Don't create a indexed load / store with zero offset.
6960       if (isa<ConstantSDNode>(Offset) &&
6961           cast<ConstantSDNode>(Offset)->isNullValue())
6962         continue;
6963
6964       // Try turning it into a post-indexed load / store except when
6965       // 1) All uses are load / store ops that use it as base ptr (and
6966       //    it may be folded as addressing mmode).
6967       // 2) Op must be independent of N, i.e. Op is neither a predecessor
6968       //    nor a successor of N. Otherwise, if Op is folded that would
6969       //    create a cycle.
6970
6971       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6972         continue;
6973
6974       // Check for #1.
6975       bool TryNext = false;
6976       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6977              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6978         SDNode *Use = *II;
6979         if (Use == Ptr.getNode())
6980           continue;
6981
6982         // If all the uses are load / store addresses, then don't do the
6983         // transformation.
6984         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6985           bool RealUse = false;
6986           for (SDNode::use_iterator III = Use->use_begin(),
6987                  EEE = Use->use_end(); III != EEE; ++III) {
6988             SDNode *UseUse = *III;
6989             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 
6990               RealUse = true;
6991           }
6992
6993           if (!RealUse) {
6994             TryNext = true;
6995             break;
6996           }
6997         }
6998       }
6999
7000       if (TryNext)
7001         continue;
7002
7003       // Check for #2
7004       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7005         SDValue Result = isLoad
7006           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7007                                BasePtr, Offset, AM)
7008           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7009                                 BasePtr, Offset, AM);
7010         ++PostIndexedNodes;
7011         ++NodesCombined;
7012         DEBUG(dbgs() << "\nReplacing.5 ";
7013               N->dump(&DAG);
7014               dbgs() << "\nWith: ";
7015               Result.getNode()->dump(&DAG);
7016               dbgs() << '\n');
7017         WorkListRemover DeadNodes(*this);
7018         if (isLoad) {
7019           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7020           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7021         } else {
7022           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7023         }
7024
7025         // Finally, since the node is now dead, remove it from the graph.
7026         DAG.DeleteNode(N);
7027
7028         // Replace the uses of Use with uses of the updated base value.
7029         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7030                                       Result.getValue(isLoad ? 1 : 0));
7031         removeFromWorkList(Op);
7032         DAG.DeleteNode(Op);
7033         return true;
7034       }
7035     }
7036   }
7037
7038   return false;
7039 }
7040
7041 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7042   LoadSDNode *LD  = cast<LoadSDNode>(N);
7043   SDValue Chain = LD->getChain();
7044   SDValue Ptr   = LD->getBasePtr();
7045
7046   // If load is not volatile and there are no uses of the loaded value (and
7047   // the updated indexed value in case of indexed loads), change uses of the
7048   // chain value into uses of the chain input (i.e. delete the dead load).
7049   if (!LD->isVolatile()) {
7050     if (N->getValueType(1) == MVT::Other) {
7051       // Unindexed loads.
7052       if (!N->hasAnyUseOfValue(0)) {
7053         // It's not safe to use the two value CombineTo variant here. e.g.
7054         // v1, chain2 = load chain1, loc
7055         // v2, chain3 = load chain2, loc
7056         // v3         = add v2, c
7057         // Now we replace use of chain2 with chain1.  This makes the second load
7058         // isomorphic to the one we are deleting, and thus makes this load live.
7059         DEBUG(dbgs() << "\nReplacing.6 ";
7060               N->dump(&DAG);
7061               dbgs() << "\nWith chain: ";
7062               Chain.getNode()->dump(&DAG);
7063               dbgs() << "\n");
7064         WorkListRemover DeadNodes(*this);
7065         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7066
7067         if (N->use_empty()) {
7068           removeFromWorkList(N);
7069           DAG.DeleteNode(N);
7070         }
7071
7072         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7073       }
7074     } else {
7075       // Indexed loads.
7076       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7077       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7078         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7079         DEBUG(dbgs() << "\nReplacing.7 ";
7080               N->dump(&DAG);
7081               dbgs() << "\nWith: ";
7082               Undef.getNode()->dump(&DAG);
7083               dbgs() << " and 2 other values\n");
7084         WorkListRemover DeadNodes(*this);
7085         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7086         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7087                                       DAG.getUNDEF(N->getValueType(1)));
7088         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7089         removeFromWorkList(N);
7090         DAG.DeleteNode(N);
7091         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7092       }
7093     }
7094   }
7095
7096   // If this load is directly stored, replace the load value with the stored
7097   // value.
7098   // TODO: Handle store large -> read small portion.
7099   // TODO: Handle TRUNCSTORE/LOADEXT
7100   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7101     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7102       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7103       if (PrevST->getBasePtr() == Ptr &&
7104           PrevST->getValue().getValueType() == N->getValueType(0))
7105       return CombineTo(N, Chain.getOperand(1), Chain);
7106     }
7107   }
7108
7109   // Try to infer better alignment information than the load already has.
7110   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7111     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7112       if (Align > LD->getAlignment())
7113         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
7114                               LD->getValueType(0),
7115                               Chain, Ptr, LD->getPointerInfo(),
7116                               LD->getMemoryVT(),
7117                               LD->isVolatile(), LD->isNonTemporal(), Align);
7118     }
7119   }
7120
7121   if (CombinerAA) {
7122     // Walk up chain skipping non-aliasing memory nodes.
7123     SDValue BetterChain = FindBetterChain(N, Chain);
7124
7125     // If there is a better chain.
7126     if (Chain != BetterChain) {
7127       SDValue ReplLoad;
7128
7129       // Replace the chain to void dependency.
7130       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7131         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
7132                                BetterChain, Ptr, LD->getPointerInfo(),
7133                                LD->isVolatile(), LD->isNonTemporal(),
7134                                LD->isInvariant(), LD->getAlignment());
7135       } else {
7136         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
7137                                   LD->getValueType(0),
7138                                   BetterChain, Ptr, LD->getPointerInfo(),
7139                                   LD->getMemoryVT(),
7140                                   LD->isVolatile(),
7141                                   LD->isNonTemporal(),
7142                                   LD->getAlignment());
7143       }
7144
7145       // Create token factor to keep old chain connected.
7146       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7147                                   MVT::Other, Chain, ReplLoad.getValue(1));
7148
7149       // Make sure the new and old chains are cleaned up.
7150       AddToWorkList(Token.getNode());
7151
7152       // Replace uses with load result and token factor. Don't add users
7153       // to work list.
7154       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7155     }
7156   }
7157
7158   // Try transforming N to an indexed load.
7159   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7160     return SDValue(N, 0);
7161
7162   return SDValue();
7163 }
7164
7165 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7166 /// load is having specific bytes cleared out.  If so, return the byte size
7167 /// being masked out and the shift amount.
7168 static std::pair<unsigned, unsigned>
7169 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7170   std::pair<unsigned, unsigned> Result(0, 0);
7171
7172   // Check for the structure we're looking for.
7173   if (V->getOpcode() != ISD::AND ||
7174       !isa<ConstantSDNode>(V->getOperand(1)) ||
7175       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7176     return Result;
7177
7178   // Check the chain and pointer.
7179   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7180   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7181
7182   // The store should be chained directly to the load or be an operand of a
7183   // tokenfactor.
7184   if (LD == Chain.getNode())
7185     ; // ok.
7186   else if (Chain->getOpcode() != ISD::TokenFactor)
7187     return Result; // Fail.
7188   else {
7189     bool isOk = false;
7190     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7191       if (Chain->getOperand(i).getNode() == LD) {
7192         isOk = true;
7193         break;
7194       }
7195     if (!isOk) return Result;
7196   }
7197
7198   // This only handles simple types.
7199   if (V.getValueType() != MVT::i16 &&
7200       V.getValueType() != MVT::i32 &&
7201       V.getValueType() != MVT::i64)
7202     return Result;
7203
7204   // Check the constant mask.  Invert it so that the bits being masked out are
7205   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7206   // follow the sign bit for uniformity.
7207   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7208   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
7209   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7210   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
7211   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7212   if (NotMaskLZ == 64) return Result;  // All zero mask.
7213
7214   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7215   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7216     return Result;
7217
7218   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7219   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7220     NotMaskLZ -= 64-V.getValueSizeInBits();
7221
7222   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7223   switch (MaskedBytes) {
7224   case 1:
7225   case 2:
7226   case 4: break;
7227   default: return Result; // All one mask, or 5-byte mask.
7228   }
7229
7230   // Verify that the first bit starts at a multiple of mask so that the access
7231   // is aligned the same as the access width.
7232   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7233
7234   Result.first = MaskedBytes;
7235   Result.second = NotMaskTZ/8;
7236   return Result;
7237 }
7238
7239
7240 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7241 /// provides a value as specified by MaskInfo.  If so, replace the specified
7242 /// store with a narrower store of truncated IVal.
7243 static SDNode *
7244 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7245                                 SDValue IVal, StoreSDNode *St,
7246                                 DAGCombiner *DC) {
7247   unsigned NumBytes = MaskInfo.first;
7248   unsigned ByteShift = MaskInfo.second;
7249   SelectionDAG &DAG = DC->getDAG();
7250
7251   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7252   // that uses this.  If not, this is not a replacement.
7253   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7254                                   ByteShift*8, (ByteShift+NumBytes)*8);
7255   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7256
7257   // Check that it is legal on the target to do this.  It is legal if the new
7258   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7259   // legalization.
7260   MVT VT = MVT::getIntegerVT(NumBytes*8);
7261   if (!DC->isTypeLegal(VT))
7262     return 0;
7263
7264   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7265   // shifted by ByteShift and truncated down to NumBytes.
7266   if (ByteShift)
7267     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
7268                        DAG.getConstant(ByteShift*8,
7269                                     DC->getShiftAmountTy(IVal.getValueType())));
7270
7271   // Figure out the offset for the store and the alignment of the access.
7272   unsigned StOffset;
7273   unsigned NewAlign = St->getAlignment();
7274
7275   if (DAG.getTargetLoweringInfo().isLittleEndian())
7276     StOffset = ByteShift;
7277   else
7278     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7279
7280   SDValue Ptr = St->getBasePtr();
7281   if (StOffset) {
7282     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
7283                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7284     NewAlign = MinAlign(NewAlign, StOffset);
7285   }
7286
7287   // Truncate down to the new size.
7288   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7289
7290   ++OpsNarrowed;
7291   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7292                       St->getPointerInfo().getWithOffset(StOffset),
7293                       false, false, NewAlign).getNode();
7294 }
7295
7296
7297 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7298 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7299 /// of the loaded bits, try narrowing the load and store if it would end up
7300 /// being a win for performance or code size.
7301 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7302   StoreSDNode *ST  = cast<StoreSDNode>(N);
7303   if (ST->isVolatile())
7304     return SDValue();
7305
7306   SDValue Chain = ST->getChain();
7307   SDValue Value = ST->getValue();
7308   SDValue Ptr   = ST->getBasePtr();
7309   EVT VT = Value.getValueType();
7310
7311   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7312     return SDValue();
7313
7314   unsigned Opc = Value.getOpcode();
7315
7316   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7317   // is a byte mask indicating a consecutive number of bytes, check to see if
7318   // Y is known to provide just those bytes.  If so, we try to replace the
7319   // load + replace + store sequence with a single (narrower) store, which makes
7320   // the load dead.
7321   if (Opc == ISD::OR) {
7322     std::pair<unsigned, unsigned> MaskedLoad;
7323     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7324     if (MaskedLoad.first)
7325       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7326                                                   Value.getOperand(1), ST,this))
7327         return SDValue(NewST, 0);
7328
7329     // Or is commutative, so try swapping X and Y.
7330     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7331     if (MaskedLoad.first)
7332       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7333                                                   Value.getOperand(0), ST,this))
7334         return SDValue(NewST, 0);
7335   }
7336
7337   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7338       Value.getOperand(1).getOpcode() != ISD::Constant)
7339     return SDValue();
7340
7341   SDValue N0 = Value.getOperand(0);
7342   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7343       Chain == SDValue(N0.getNode(), 1)) {
7344     LoadSDNode *LD = cast<LoadSDNode>(N0);
7345     if (LD->getBasePtr() != Ptr ||
7346         LD->getPointerInfo().getAddrSpace() !=
7347         ST->getPointerInfo().getAddrSpace())
7348       return SDValue();
7349
7350     // Find the type to narrow it the load / op / store to.
7351     SDValue N1 = Value.getOperand(1);
7352     unsigned BitWidth = N1.getValueSizeInBits();
7353     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7354     if (Opc == ISD::AND)
7355       Imm ^= APInt::getAllOnesValue(BitWidth);
7356     if (Imm == 0 || Imm.isAllOnesValue())
7357       return SDValue();
7358     unsigned ShAmt = Imm.countTrailingZeros();
7359     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7360     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7361     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7362     while (NewBW < BitWidth &&
7363            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7364              TLI.isNarrowingProfitable(VT, NewVT))) {
7365       NewBW = NextPowerOf2(NewBW);
7366       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7367     }
7368     if (NewBW >= BitWidth)
7369       return SDValue();
7370
7371     // If the lsb changed does not start at the type bitwidth boundary,
7372     // start at the previous one.
7373     if (ShAmt % NewBW)
7374       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7375     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
7376     if ((Imm & Mask) == Imm) {
7377       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7378       if (Opc == ISD::AND)
7379         NewImm ^= APInt::getAllOnesValue(NewBW);
7380       uint64_t PtrOff = ShAmt / 8;
7381       // For big endian targets, we need to adjust the offset to the pointer to
7382       // load the correct bytes.
7383       if (TLI.isBigEndian())
7384         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7385
7386       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7387       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7388       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7389         return SDValue();
7390
7391       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7392                                    Ptr.getValueType(), Ptr,
7393                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7394       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7395                                   LD->getChain(), NewPtr,
7396                                   LD->getPointerInfo().getWithOffset(PtrOff),
7397                                   LD->isVolatile(), LD->isNonTemporal(),
7398                                   LD->isInvariant(), NewAlign);
7399       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7400                                    DAG.getConstant(NewImm, NewVT));
7401       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7402                                    NewVal, NewPtr,
7403                                    ST->getPointerInfo().getWithOffset(PtrOff),
7404                                    false, false, NewAlign);
7405
7406       AddToWorkList(NewPtr.getNode());
7407       AddToWorkList(NewLD.getNode());
7408       AddToWorkList(NewVal.getNode());
7409       WorkListRemover DeadNodes(*this);
7410       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7411       ++OpsNarrowed;
7412       return NewST;
7413     }
7414   }
7415
7416   return SDValue();
7417 }
7418
7419 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7420 /// if the load value isn't used by any other operations, then consider
7421 /// transforming the pair to integer load / store operations if the target
7422 /// deems the transformation profitable.
7423 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7424   StoreSDNode *ST  = cast<StoreSDNode>(N);
7425   SDValue Chain = ST->getChain();
7426   SDValue Value = ST->getValue();
7427   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7428       Value.hasOneUse() &&
7429       Chain == SDValue(Value.getNode(), 1)) {
7430     LoadSDNode *LD = cast<LoadSDNode>(Value);
7431     EVT VT = LD->getMemoryVT();
7432     if (!VT.isFloatingPoint() ||
7433         VT != ST->getMemoryVT() ||
7434         LD->isNonTemporal() ||
7435         ST->isNonTemporal() ||
7436         LD->getPointerInfo().getAddrSpace() != 0 ||
7437         ST->getPointerInfo().getAddrSpace() != 0)
7438       return SDValue();
7439
7440     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7441     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7442         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7443         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7444         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7445       return SDValue();
7446
7447     unsigned LDAlign = LD->getAlignment();
7448     unsigned STAlign = ST->getAlignment();
7449     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7450     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7451     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7452       return SDValue();
7453
7454     SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7455                                 LD->getChain(), LD->getBasePtr(),
7456                                 LD->getPointerInfo(),
7457                                 false, false, false, LDAlign);
7458
7459     SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7460                                  NewLD, ST->getBasePtr(),
7461                                  ST->getPointerInfo(),
7462                                  false, false, STAlign);
7463
7464     AddToWorkList(NewLD.getNode());
7465     AddToWorkList(NewST.getNode());
7466     WorkListRemover DeadNodes(*this);
7467     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7468     ++LdStFP2Int;
7469     return NewST;
7470   }
7471
7472   return SDValue();
7473 }
7474
7475 /// Returns the base pointer and an integer offset from that object.
7476 static std::pair<SDValue, int64_t> GetPointerBaseAndOffset(SDValue Ptr) {
7477   if (Ptr->getOpcode() == ISD::ADD && isa<ConstantSDNode>(Ptr->getOperand(1))) {
7478     int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7479     SDValue Base = Ptr->getOperand(0);
7480     return std::make_pair(Base, Offset);
7481   }
7482
7483   return std::make_pair(Ptr, 0);
7484 }
7485
7486 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7487 /// is located in a sequence of memory operations connected by a chain.
7488 struct MemOpLink {
7489   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7490     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7491   // Ptr to the mem node.
7492   LSBaseSDNode *MemNode;
7493   // Offset from the base ptr.
7494   int64_t OffsetFromBase;
7495   // What is the sequence number of this mem node.
7496   // Lowest mem operand in the DAG starts at zero.
7497   unsigned SequenceNum;
7498 };
7499
7500 /// Sorts store nodes in a link according to their offset from a shared
7501 // base ptr.
7502 struct ConsecutiveMemoryChainSorter {
7503   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7504     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7505   }
7506 };
7507
7508 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7509   EVT MemVT = St->getMemoryVT();
7510   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7511
7512   // Don't merge vectors into wider inputs.
7513   if (MemVT.isVector() || !MemVT.isSimple())
7514     return false;
7515
7516   // Perform an early exit check. Do not bother looking at stored values that
7517   // are not constants or loads.
7518   SDValue StoredVal = St->getValue();
7519   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7520   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7521       !IsLoadSrc)
7522     return false;
7523
7524   // Only look at ends of store sequences.
7525   SDValue Chain = SDValue(St, 1);
7526   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7527     return false;
7528
7529   // This holds the base pointer and the offset in bytes from the base pointer.
7530   std::pair<SDValue, int64_t> BasePtr =
7531       GetPointerBaseAndOffset(St->getBasePtr());
7532
7533   // We must have a base and an offset.
7534   if (!BasePtr.first.getNode())
7535     return false;
7536
7537   // Do not handle stores to undef base pointers.
7538   if (BasePtr.first.getOpcode() == ISD::UNDEF)
7539     return false;
7540
7541   SmallVector<MemOpLink, 8> StoreNodes;
7542   // Walk up the chain and look for nodes with offsets from the same
7543   // base pointer. Stop when reaching an instruction with a different kind
7544   // or instruction which has a different base pointer.
7545   unsigned Seq = 0;
7546   StoreSDNode *Index = St;
7547   while (Index) {
7548     // If the chain has more than one use, then we can't reorder the mem ops.
7549     if (Index != St && !SDValue(Index, 1)->hasOneUse())
7550       break;
7551
7552     // Find the base pointer and offset for this memory node.
7553     std::pair<SDValue, int64_t> Ptr =
7554       GetPointerBaseAndOffset(Index->getBasePtr());
7555
7556     // Check that the base pointer is the same as the original one.
7557     if (Ptr.first.getNode() != BasePtr.first.getNode())
7558       break;
7559
7560     // Check that the alignment is the same.
7561     if (Index->getAlignment() != St->getAlignment())
7562       break;
7563
7564     // The memory operands must not be volatile.
7565     if (Index->isVolatile() || Index->isIndexed())
7566       break;
7567
7568     // No truncation.
7569     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7570       if (St->isTruncatingStore())
7571         break;
7572
7573     // The stored memory type must be the same.
7574     if (Index->getMemoryVT() != MemVT)
7575       break;
7576
7577     // We do not allow unaligned stores because we want to prevent overriding
7578     // stores.
7579     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
7580       break;
7581
7582     // We found a potential memory operand to merge.
7583     StoreNodes.push_back(MemOpLink(Index, Ptr.second, Seq++));
7584
7585     // Move up the chain to the next memory operation.
7586     Index = dyn_cast<StoreSDNode>(Index->getChain().getNode());
7587   }
7588
7589   // Check if there is anything to merge.
7590   if (StoreNodes.size() < 2)
7591     return false;
7592
7593   // Sort the memory operands according to their distance from the base pointer.
7594   std::sort(StoreNodes.begin(), StoreNodes.end(),
7595             ConsecutiveMemoryChainSorter());
7596
7597   // Scan the memory operations on the chain and find the first non-consecutive
7598   // store memory address.
7599   unsigned LastConsecutiveStore = 0;
7600   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
7601   for (unsigned i=1; i<StoreNodes.size(); ++i) {
7602     int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
7603     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7604       break;
7605
7606     // Mark this node as useful.
7607     LastConsecutiveStore = i;
7608   }
7609
7610   // The node with the lowest store address.
7611   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
7612
7613   // Store the constants into memory as one consecutive store.
7614   if (!IsLoadSrc) {
7615     unsigned LastLegalType = 0;
7616     unsigned LastLegalVectorType = 0;
7617     bool NonZero = false;
7618     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
7619       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
7620       SDValue StoredVal = St->getValue();
7621
7622       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
7623         NonZero |= !C->isNullValue();
7624       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
7625         NonZero |= !C->getConstantFPValue()->isNullValue();
7626       } else {
7627         // Non constant.
7628         break;
7629       }
7630
7631       // Find a legal type for the constant store.
7632       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
7633       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7634       if (TLI.isTypeLegal(StoreTy))
7635         LastLegalType = i+1;
7636
7637       // Find a legal type for the vector store.
7638       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
7639       if (TLI.isTypeLegal(Ty))
7640         LastLegalVectorType = i + 1;
7641     }
7642
7643     // We only use vectors if the constant is known to be zero.
7644     if (NonZero)
7645       LastLegalVectorType = 0;
7646
7647     // Check if we found a legal integer type to store.
7648     if (LastLegalType == 0 && LastLegalVectorType == 0)
7649       return false;
7650
7651     bool UseVector = LastLegalVectorType > LastLegalType;
7652     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
7653
7654     // Make sure we have something to merge.
7655     if (NumElem < 2)
7656       return false;
7657
7658     unsigned EarliestNodeUsed = 0;
7659     for (unsigned i=0; i < NumElem; ++i) {
7660       // Find a chain for the new wide-store operand. Notice that some
7661       // of the store nodes that we found may not be selected for inclusion
7662       // in the wide store. The chain we use needs to be the chain of the
7663       // earliest store node which is *used* and replaced by the wide store.
7664       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
7665         EarliestNodeUsed = i;
7666     }
7667
7668     // The earliest Node in the DAG.
7669     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
7670     DebugLoc DL = StoreNodes[0].MemNode->getDebugLoc();
7671
7672     SDValue StoredVal;
7673     if (UseVector) {
7674       // Find a legal type for the vector store.
7675       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
7676       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
7677       StoredVal = DAG.getConstant(0, Ty);
7678     } else {
7679       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
7680       APInt StoreInt(StoreBW, 0);
7681
7682       // Construct a single integer constant which is made of the smaller
7683       // constant inputs.
7684       bool IsLE = TLI.isLittleEndian();
7685       for (unsigned i = 0; i < NumElem ; ++i) {
7686         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
7687         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
7688         SDValue Val = St->getValue();
7689         StoreInt<<=ElementSizeBytes*8;
7690         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
7691           StoreInt|=C->getAPIntValue().zext(StoreBW);
7692         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
7693           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
7694         } else {
7695           assert(false && "Invalid constant element type");
7696         }
7697       }
7698
7699       // Create the new Load and Store operations.
7700       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7701       StoredVal = DAG.getConstant(StoreInt, StoreTy);
7702     }
7703
7704     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
7705                                     FirstInChain->getBasePtr(),
7706                                     FirstInChain->getPointerInfo(),
7707                                     false, false,
7708                                     FirstInChain->getAlignment());
7709
7710     // Replace the first store with the new store
7711     CombineTo(EarliestOp, NewStore);
7712     // Erase all other stores.
7713     for (unsigned i = 0; i < NumElem ; ++i) {
7714       if (StoreNodes[i].MemNode == EarliestOp)
7715         continue;
7716       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
7717       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
7718       removeFromWorkList(St);
7719       DAG.DeleteNode(St);
7720     }
7721
7722     return true;
7723   }
7724
7725   // Below we handle the case of multiple consecutive stores that
7726   // come from multiple consecutive loads. We merge them into a single
7727   // wide load and a single wide store.
7728
7729   // Look for load nodes which are used by the stored values.
7730   SmallVector<MemOpLink, 8> LoadNodes;
7731
7732   // Find acceptable loads. Loads need to have the same chain (token factor),
7733   // must not be zext, volatile, indexed, and they must be consecutive.
7734   SDValue LdBasePtr;
7735   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
7736     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
7737     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
7738     if (!Ld) break;
7739
7740     // Loads must only have one use.
7741     if (!Ld->hasNUsesOfValue(1, 0))
7742       break;
7743
7744     // Check that the alignment is the same as the stores.
7745     if (Ld->getAlignment() != St->getAlignment())
7746       break;
7747
7748     // The memory operands must not be volatile.
7749     if (Ld->isVolatile() || Ld->isIndexed())
7750       break;
7751
7752     // We do not accept ext loads.
7753     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
7754       break;
7755
7756     // The stored memory type must be the same.
7757     if (Ld->getMemoryVT() != MemVT)
7758       break;
7759
7760     std::pair<SDValue, int64_t> LdPtr =
7761     GetPointerBaseAndOffset(Ld->getBasePtr());
7762
7763     // If this is not the first ptr that we check.
7764     if (LdBasePtr.getNode()) {
7765       // The base ptr must be the same.
7766       if (LdPtr.first != LdBasePtr)
7767         break;
7768     } else {
7769       // Check that all other base pointers are the same as this one.
7770       LdBasePtr = LdPtr.first;
7771     }
7772
7773     // We found a potential memory operand to merge.
7774     LoadNodes.push_back(MemOpLink(Ld, LdPtr.second, 0));
7775   }
7776
7777   if (LoadNodes.size() < 2)
7778     return false;
7779
7780   // Scan the memory operations on the chain and find the first non-consecutive
7781   // load memory address. These variables hold the index in the store node
7782   // array.
7783   unsigned LastConsecutiveLoad = 0;
7784   // This variable refers to the size and not index in the array.
7785   unsigned LastLegalVectorType = 0;
7786   unsigned LastLegalIntegerType = 0;
7787   StartAddress = LoadNodes[0].OffsetFromBase;
7788   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
7789   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
7790     // All loads much share the same chain.
7791     if (LoadNodes[i].MemNode->getChain() != FirstChain)
7792       break;
7793     
7794     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
7795     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7796       break;
7797     LastConsecutiveLoad = i;
7798
7799     // Find a legal type for the vector store.
7800     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
7801     if (TLI.isTypeLegal(StoreTy))
7802       LastLegalVectorType = i + 1;
7803
7804     // Find a legal type for the integer store.
7805     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
7806     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7807     if (TLI.isTypeLegal(StoreTy))
7808       LastLegalIntegerType = i + 1;
7809   }
7810
7811   // Only use vector types if the vector type is larger than the integer type.
7812   // If they are the same, use integers.
7813   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType;
7814   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
7815
7816   // We add +1 here because the LastXXX variables refer to location while
7817   // the NumElem refers to array/index size.
7818   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
7819   NumElem = std::min(LastLegalType, NumElem);
7820
7821   if (NumElem < 2)
7822     return false;
7823
7824   // The earliest Node in the DAG.
7825   unsigned EarliestNodeUsed = 0;
7826   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
7827   for (unsigned i=1; i<NumElem; ++i) {
7828     // Find a chain for the new wide-store operand. Notice that some
7829     // of the store nodes that we found may not be selected for inclusion
7830     // in the wide store. The chain we use needs to be the chain of the
7831     // earliest store node which is *used* and replaced by the wide store.
7832     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
7833       EarliestNodeUsed = i;
7834   }
7835
7836   // Find if it is better to use vectors or integers to load and store
7837   // to memory.
7838   EVT JointMemOpVT;
7839   if (UseVectorTy) {
7840     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
7841   } else {
7842     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
7843     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7844   }
7845
7846   DebugLoc LoadDL = LoadNodes[0].MemNode->getDebugLoc();
7847   DebugLoc StoreDL = StoreNodes[0].MemNode->getDebugLoc();
7848
7849   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
7850   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
7851                                 FirstLoad->getChain(),
7852                                 FirstLoad->getBasePtr(),
7853                                 FirstLoad->getPointerInfo(),
7854                                 false, false, false,
7855                                 FirstLoad->getAlignment());
7856
7857   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
7858                                   FirstInChain->getBasePtr(),
7859                                   FirstInChain->getPointerInfo(), false, false,
7860                                   FirstInChain->getAlignment());
7861
7862   // Replace one of the loads with the new load.
7863   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
7864   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
7865                                 SDValue(NewLoad.getNode(), 1));
7866
7867   // Remove the rest of the load chains.
7868   for (unsigned i = 1; i < NumElem ; ++i) {
7869     // Replace all chain users of the old load nodes with the chain of the new
7870     // load node.
7871     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
7872     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
7873   }
7874
7875   // Replace the first store with the new store.
7876   CombineTo(EarliestOp, NewStore);
7877   // Erase all other stores.
7878   for (unsigned i = 0; i < NumElem ; ++i) {
7879     // Remove all Store nodes.
7880     if (StoreNodes[i].MemNode == EarliestOp)
7881       continue;
7882     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
7883     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
7884     removeFromWorkList(St);
7885     DAG.DeleteNode(St);
7886   }
7887
7888   return true;
7889 }
7890
7891 SDValue DAGCombiner::visitSTORE(SDNode *N) {
7892   StoreSDNode *ST  = cast<StoreSDNode>(N);
7893   SDValue Chain = ST->getChain();
7894   SDValue Value = ST->getValue();
7895   SDValue Ptr   = ST->getBasePtr();
7896
7897   // If this is a store of a bit convert, store the input value if the
7898   // resultant store does not need a higher alignment than the original.
7899   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
7900       ST->isUnindexed()) {
7901     unsigned OrigAlign = ST->getAlignment();
7902     EVT SVT = Value.getOperand(0).getValueType();
7903     unsigned Align = TLI.getDataLayout()->
7904       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
7905     if (Align <= OrigAlign &&
7906         ((!LegalOperations && !ST->isVolatile()) ||
7907          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
7908       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7909                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
7910                           ST->isNonTemporal(), OrigAlign);
7911   }
7912
7913   // Turn 'store undef, Ptr' -> nothing.
7914   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
7915     return Chain;
7916
7917   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
7918   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
7919     // NOTE: If the original store is volatile, this transform must not increase
7920     // the number of stores.  For example, on x86-32 an f64 can be stored in one
7921     // processor operation but an i64 (which is not legal) requires two.  So the
7922     // transform should not be done in this case.
7923     if (Value.getOpcode() != ISD::TargetConstantFP) {
7924       SDValue Tmp;
7925       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
7926       default: llvm_unreachable("Unknown FP type");
7927       case MVT::f16:    // We don't do this for these yet.
7928       case MVT::f80:
7929       case MVT::f128:
7930       case MVT::ppcf128:
7931         break;
7932       case MVT::f32:
7933         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
7934             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7935           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
7936                               bitcastToAPInt().getZExtValue(), MVT::i32);
7937           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7938                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
7939                               ST->isNonTemporal(), ST->getAlignment());
7940         }
7941         break;
7942       case MVT::f64:
7943         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
7944              !ST->isVolatile()) ||
7945             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
7946           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
7947                                 getZExtValue(), MVT::i64);
7948           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7949                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
7950                               ST->isNonTemporal(), ST->getAlignment());
7951         }
7952
7953         if (!ST->isVolatile() &&
7954             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7955           // Many FP stores are not made apparent until after legalize, e.g. for
7956           // argument passing.  Since this is so common, custom legalize the
7957           // 64-bit integer store into two 32-bit stores.
7958           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
7959           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
7960           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
7961           if (TLI.isBigEndian()) std::swap(Lo, Hi);
7962
7963           unsigned Alignment = ST->getAlignment();
7964           bool isVolatile = ST->isVolatile();
7965           bool isNonTemporal = ST->isNonTemporal();
7966
7967           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
7968                                      Ptr, ST->getPointerInfo(),
7969                                      isVolatile, isNonTemporal,
7970                                      ST->getAlignment());
7971           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
7972                             DAG.getConstant(4, Ptr.getValueType()));
7973           Alignment = MinAlign(Alignment, 4U);
7974           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
7975                                      Ptr, ST->getPointerInfo().getWithOffset(4),
7976                                      isVolatile, isNonTemporal,
7977                                      Alignment);
7978           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7979                              St0, St1);
7980         }
7981
7982         break;
7983       }
7984     }
7985   }
7986
7987   // Try to infer better alignment information than the store already has.
7988   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
7989     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7990       if (Align > ST->getAlignment())
7991         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
7992                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7993                                  ST->isVolatile(), ST->isNonTemporal(), Align);
7994     }
7995   }
7996
7997   // Try transforming a pair floating point load / store ops to integer
7998   // load / store ops.
7999   SDValue NewST = TransformFPLoadStorePair(N);
8000   if (NewST.getNode())
8001     return NewST;
8002
8003   if (CombinerAA) {
8004     // Walk up chain skipping non-aliasing memory nodes.
8005     SDValue BetterChain = FindBetterChain(N, Chain);
8006
8007     // If there is a better chain.
8008     if (Chain != BetterChain) {
8009       SDValue ReplStore;
8010
8011       // Replace the chain to avoid dependency.
8012       if (ST->isTruncatingStore()) {
8013         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8014                                       ST->getPointerInfo(),
8015                                       ST->getMemoryVT(), ST->isVolatile(),
8016                                       ST->isNonTemporal(), ST->getAlignment());
8017       } else {
8018         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8019                                  ST->getPointerInfo(),
8020                                  ST->isVolatile(), ST->isNonTemporal(),
8021                                  ST->getAlignment());
8022       }
8023
8024       // Create token to keep both nodes around.
8025       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
8026                                   MVT::Other, Chain, ReplStore);
8027
8028       // Make sure the new and old chains are cleaned up.
8029       AddToWorkList(Token.getNode());
8030
8031       // Don't add users to work list.
8032       return CombineTo(N, Token, false);
8033     }
8034   }
8035
8036   // Try transforming N to an indexed store.
8037   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8038     return SDValue(N, 0);
8039
8040   // FIXME: is there such a thing as a truncating indexed store?
8041   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8042       Value.getValueType().isInteger()) {
8043     // See if we can simplify the input to this truncstore with knowledge that
8044     // only the low bits are being used.  For example:
8045     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8046     SDValue Shorter =
8047       GetDemandedBits(Value,
8048                       APInt::getLowBitsSet(
8049                         Value.getValueType().getScalarType().getSizeInBits(),
8050                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8051     AddToWorkList(Value.getNode());
8052     if (Shorter.getNode())
8053       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
8054                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8055                                ST->isVolatile(), ST->isNonTemporal(),
8056                                ST->getAlignment());
8057
8058     // Otherwise, see if we can simplify the operation with
8059     // SimplifyDemandedBits, which only works if the value has a single use.
8060     if (SimplifyDemandedBits(Value,
8061                         APInt::getLowBitsSet(
8062                           Value.getValueType().getScalarType().getSizeInBits(),
8063                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8064       return SDValue(N, 0);
8065   }
8066
8067   // If this is a load followed by a store to the same location, then the store
8068   // is dead/noop.
8069   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8070     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8071         ST->isUnindexed() && !ST->isVolatile() &&
8072         // There can't be any side effects between the load and store, such as
8073         // a call or store.
8074         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8075       // The store is dead, remove it.
8076       return Chain;
8077     }
8078   }
8079
8080   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8081   // truncating store.  We can do this even if this is already a truncstore.
8082   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8083       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8084       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8085                             ST->getMemoryVT())) {
8086     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8087                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8088                              ST->isVolatile(), ST->isNonTemporal(),
8089                              ST->getAlignment());
8090   }
8091
8092   // Only perform this optimization before the types are legal, because we
8093   // don't want to perform this optimization on every DAGCombine invocation.
8094   if (!LegalTypes && MergeConsecutiveStores(ST))
8095     return SDValue(N, 0);
8096
8097   return ReduceLoadOpStoreWidth(N);
8098 }
8099
8100 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8101   SDValue InVec = N->getOperand(0);
8102   SDValue InVal = N->getOperand(1);
8103   SDValue EltNo = N->getOperand(2);
8104   DebugLoc dl = N->getDebugLoc();
8105
8106   // If the inserted element is an UNDEF, just use the input vector.
8107   if (InVal.getOpcode() == ISD::UNDEF)
8108     return InVec;
8109
8110   EVT VT = InVec.getValueType();
8111
8112   // If we can't generate a legal BUILD_VECTOR, exit
8113   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8114     return SDValue();
8115
8116   // Check that we know which element is being inserted
8117   if (!isa<ConstantSDNode>(EltNo))
8118     return SDValue();
8119   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8120
8121   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8122   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8123   // vector elements.
8124   SmallVector<SDValue, 8> Ops;
8125   if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8126     Ops.append(InVec.getNode()->op_begin(),
8127                InVec.getNode()->op_end());
8128   } else if (InVec.getOpcode() == ISD::UNDEF) {
8129     unsigned NElts = VT.getVectorNumElements();
8130     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8131   } else {
8132     return SDValue();
8133   }
8134
8135   // Insert the element
8136   if (Elt < Ops.size()) {
8137     // All the operands of BUILD_VECTOR must have the same type;
8138     // we enforce that here.
8139     EVT OpVT = Ops[0].getValueType();
8140     if (InVal.getValueType() != OpVT)
8141       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8142                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8143                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8144     Ops[Elt] = InVal;
8145   }
8146
8147   // Return the new vector
8148   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8149                      VT, &Ops[0], Ops.size());
8150 }
8151
8152 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8153   // (vextract (scalar_to_vector val, 0) -> val
8154   SDValue InVec = N->getOperand(0);
8155   EVT VT = InVec.getValueType();
8156   EVT NVT = N->getValueType(0);
8157
8158   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8159     // Check if the result type doesn't match the inserted element type. A
8160     // SCALAR_TO_VECTOR may truncate the inserted element and the
8161     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8162     SDValue InOp = InVec.getOperand(0);
8163     if (InOp.getValueType() != NVT) {
8164       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8165       return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
8166     }
8167     return InOp;
8168   }
8169
8170   SDValue EltNo = N->getOperand(1);
8171   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8172
8173   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8174   // We only perform this optimization before the op legalization phase because
8175   // we may introduce new vector instructions which are not backed by TD
8176   // patterns. For example on AVX, extracting elements from a wide vector
8177   // without using extract_subvector.
8178   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8179       && ConstEltNo && !LegalOperations) {
8180     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8181     int NumElem = VT.getVectorNumElements();
8182     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8183     // Find the new index to extract from.
8184     int OrigElt = SVOp->getMaskElt(Elt);
8185
8186     // Extracting an undef index is undef.
8187     if (OrigElt == -1)
8188       return DAG.getUNDEF(NVT);
8189
8190     // Select the right vector half to extract from.
8191     if (OrigElt < NumElem) {
8192       InVec = InVec->getOperand(0);
8193     } else {
8194       InVec = InVec->getOperand(1);
8195       OrigElt -= NumElem;
8196     }
8197
8198     EVT IndexTy = N->getOperand(1).getValueType();
8199     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
8200                        InVec, DAG.getConstant(OrigElt, IndexTy));
8201   }
8202
8203   // Perform only after legalization to ensure build_vector / vector_shuffle
8204   // optimizations have already been done.
8205   if (!LegalOperations) return SDValue();
8206
8207   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8208   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8209   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8210
8211   if (ConstEltNo) {
8212     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8213     bool NewLoad = false;
8214     bool BCNumEltsChanged = false;
8215     EVT ExtVT = VT.getVectorElementType();
8216     EVT LVT = ExtVT;
8217
8218     // If the result of load has to be truncated, then it's not necessarily
8219     // profitable.
8220     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8221       return SDValue();
8222
8223     if (InVec.getOpcode() == ISD::BITCAST) {
8224       // Don't duplicate a load with other uses.
8225       if (!InVec.hasOneUse())
8226         return SDValue();
8227
8228       EVT BCVT = InVec.getOperand(0).getValueType();
8229       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8230         return SDValue();
8231       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8232         BCNumEltsChanged = true;
8233       InVec = InVec.getOperand(0);
8234       ExtVT = BCVT.getVectorElementType();
8235       NewLoad = true;
8236     }
8237
8238     LoadSDNode *LN0 = NULL;
8239     const ShuffleVectorSDNode *SVN = NULL;
8240     if (ISD::isNormalLoad(InVec.getNode())) {
8241       LN0 = cast<LoadSDNode>(InVec);
8242     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8243                InVec.getOperand(0).getValueType() == ExtVT &&
8244                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8245       // Don't duplicate a load with other uses.
8246       if (!InVec.hasOneUse())
8247         return SDValue();
8248
8249       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8250     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8251       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8252       // =>
8253       // (load $addr+1*size)
8254
8255       // Don't duplicate a load with other uses.
8256       if (!InVec.hasOneUse())
8257         return SDValue();
8258
8259       // If the bit convert changed the number of elements, it is unsafe
8260       // to examine the mask.
8261       if (BCNumEltsChanged)
8262         return SDValue();
8263
8264       // Select the input vector, guarding against out of range extract vector.
8265       unsigned NumElems = VT.getVectorNumElements();
8266       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8267       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8268
8269       if (InVec.getOpcode() == ISD::BITCAST) {
8270         // Don't duplicate a load with other uses.
8271         if (!InVec.hasOneUse())
8272           return SDValue();
8273
8274         InVec = InVec.getOperand(0);
8275       }
8276       if (ISD::isNormalLoad(InVec.getNode())) {
8277         LN0 = cast<LoadSDNode>(InVec);
8278         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8279       }
8280     }
8281
8282     // Make sure we found a non-volatile load and the extractelement is
8283     // the only use.
8284     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8285       return SDValue();
8286
8287     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8288     if (Elt == -1)
8289       return DAG.getUNDEF(LVT);
8290
8291     unsigned Align = LN0->getAlignment();
8292     if (NewLoad) {
8293       // Check the resultant load doesn't need a higher alignment than the
8294       // original load.
8295       unsigned NewAlign =
8296         TLI.getDataLayout()
8297             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8298
8299       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8300         return SDValue();
8301
8302       Align = NewAlign;
8303     }
8304
8305     SDValue NewPtr = LN0->getBasePtr();
8306     unsigned PtrOff = 0;
8307
8308     if (Elt) {
8309       PtrOff = LVT.getSizeInBits() * Elt / 8;
8310       EVT PtrType = NewPtr.getValueType();
8311       if (TLI.isBigEndian())
8312         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8313       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
8314                            DAG.getConstant(PtrOff, PtrType));
8315     }
8316
8317     // The replacement we need to do here is a little tricky: we need to
8318     // replace an extractelement of a load with a load.
8319     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8320     // Note that this replacement assumes that the extractvalue is the only
8321     // use of the load; that's okay because we don't want to perform this
8322     // transformation in other cases anyway.
8323     SDValue Load;
8324     SDValue Chain;
8325     if (NVT.bitsGT(LVT)) {
8326       // If the result type of vextract is wider than the load, then issue an
8327       // extending load instead.
8328       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8329         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8330       Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
8331                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8332                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8333       Chain = Load.getValue(1);
8334     } else {
8335       Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
8336                          LN0->getPointerInfo().getWithOffset(PtrOff),
8337                          LN0->isVolatile(), LN0->isNonTemporal(), 
8338                          LN0->isInvariant(), Align);
8339       Chain = Load.getValue(1);
8340       if (NVT.bitsLT(LVT))
8341         Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
8342       else
8343         Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
8344     }
8345     WorkListRemover DeadNodes(*this);
8346     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8347     SDValue To[] = { Load, Chain };
8348     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8349     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8350     // worklist explicitly as well.
8351     AddToWorkList(Load.getNode());
8352     AddUsersToWorkList(Load.getNode()); // Add users too
8353     // Make sure to revisit this node to clean it up; it will usually be dead.
8354     AddToWorkList(N);
8355     return SDValue(N, 0);
8356   }
8357
8358   return SDValue();
8359 }
8360
8361 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8362 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8363   // We perform this optimization post type-legalization because
8364   // the type-legalizer often scalarizes integer-promoted vectors.
8365   // Performing this optimization before may create bit-casts which
8366   // will be type-legalized to complex code sequences.
8367   // We perform this optimization only before the operation legalizer because we
8368   // may introduce illegal operations.
8369   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8370     return SDValue();
8371
8372   unsigned NumInScalars = N->getNumOperands();
8373   DebugLoc dl = N->getDebugLoc();
8374   EVT VT = N->getValueType(0);
8375
8376   // Check to see if this is a BUILD_VECTOR of a bunch of values
8377   // which come from any_extend or zero_extend nodes. If so, we can create
8378   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8379   // optimizations. We do not handle sign-extend because we can't fill the sign
8380   // using shuffles.
8381   EVT SourceType = MVT::Other;
8382   bool AllAnyExt = true;
8383
8384   for (unsigned i = 0; i != NumInScalars; ++i) {
8385     SDValue In = N->getOperand(i);
8386     // Ignore undef inputs.
8387     if (In.getOpcode() == ISD::UNDEF) continue;
8388
8389     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8390     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8391
8392     // Abort if the element is not an extension.
8393     if (!ZeroExt && !AnyExt) {
8394       SourceType = MVT::Other;
8395       break;
8396     }
8397
8398     // The input is a ZeroExt or AnyExt. Check the original type.
8399     EVT InTy = In.getOperand(0).getValueType();
8400
8401     // Check that all of the widened source types are the same.
8402     if (SourceType == MVT::Other)
8403       // First time.
8404       SourceType = InTy;
8405     else if (InTy != SourceType) {
8406       // Multiple income types. Abort.
8407       SourceType = MVT::Other;
8408       break;
8409     }
8410
8411     // Check if all of the extends are ANY_EXTENDs.
8412     AllAnyExt &= AnyExt;
8413   }
8414
8415   // In order to have valid types, all of the inputs must be extended from the
8416   // same source type and all of the inputs must be any or zero extend.
8417   // Scalar sizes must be a power of two.
8418   EVT OutScalarTy = VT.getScalarType();
8419   bool ValidTypes = SourceType != MVT::Other &&
8420                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8421                  isPowerOf2_32(SourceType.getSizeInBits());
8422
8423   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8424   // turn into a single shuffle instruction.
8425   if (!ValidTypes)
8426     return SDValue();
8427
8428   bool isLE = TLI.isLittleEndian();
8429   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8430   assert(ElemRatio > 1 && "Invalid element size ratio");
8431   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8432                                DAG.getConstant(0, SourceType);
8433
8434   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8435   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8436
8437   // Populate the new build_vector
8438   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8439     SDValue Cast = N->getOperand(i);
8440     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8441             Cast.getOpcode() == ISD::ZERO_EXTEND ||
8442             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8443     SDValue In;
8444     if (Cast.getOpcode() == ISD::UNDEF)
8445       In = DAG.getUNDEF(SourceType);
8446     else
8447       In = Cast->getOperand(0);
8448     unsigned Index = isLE ? (i * ElemRatio) :
8449                             (i * ElemRatio + (ElemRatio - 1));
8450
8451     assert(Index < Ops.size() && "Invalid index");
8452     Ops[Index] = In;
8453   }
8454
8455   // The type of the new BUILD_VECTOR node.
8456   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8457   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8458          "Invalid vector size");
8459   // Check if the new vector type is legal.
8460   if (!isTypeLegal(VecVT)) return SDValue();
8461
8462   // Make the new BUILD_VECTOR.
8463   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8464
8465   // The new BUILD_VECTOR node has the potential to be further optimized.
8466   AddToWorkList(BV.getNode());
8467   // Bitcast to the desired type.
8468   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8469 }
8470
8471 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8472   EVT VT = N->getValueType(0);
8473
8474   unsigned NumInScalars = N->getNumOperands();
8475   DebugLoc dl = N->getDebugLoc();
8476
8477   EVT SrcVT = MVT::Other;
8478   unsigned Opcode = ISD::DELETED_NODE;
8479   unsigned NumDefs = 0;
8480
8481   for (unsigned i = 0; i != NumInScalars; ++i) {
8482     SDValue In = N->getOperand(i);
8483     unsigned Opc = In.getOpcode();
8484
8485     if (Opc == ISD::UNDEF)
8486       continue;
8487
8488     // If all scalar values are floats and converted from integers.
8489     if (Opcode == ISD::DELETED_NODE &&
8490         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8491       Opcode = Opc;
8492       // If not supported by target, bail out.
8493       if (TLI.getOperationAction(Opcode, VT) != TargetLowering::Legal &&
8494           TLI.getOperationAction(Opcode, VT) != TargetLowering::Custom)
8495         return SDValue();
8496     }
8497     if (Opc != Opcode)
8498       return SDValue();
8499
8500     EVT InVT = In.getOperand(0).getValueType();
8501
8502     // If all scalar values are typed differently, bail out. It's chosen to
8503     // simplify BUILD_VECTOR of integer types.
8504     if (SrcVT == MVT::Other)
8505       SrcVT = InVT;
8506     if (SrcVT != InVT)
8507       return SDValue();
8508     NumDefs++;
8509   }
8510
8511   // If the vector has just one element defined, it's not worth to fold it into
8512   // a vectorized one.
8513   if (NumDefs < 2)
8514     return SDValue();
8515
8516   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
8517          && "Should only handle conversion from integer to float.");
8518   assert(SrcVT != MVT::Other && "Cannot determine source type!");
8519
8520   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
8521   SmallVector<SDValue, 8> Opnds;
8522   for (unsigned i = 0; i != NumInScalars; ++i) {
8523     SDValue In = N->getOperand(i);
8524
8525     if (In.getOpcode() == ISD::UNDEF)
8526       Opnds.push_back(DAG.getUNDEF(SrcVT));
8527     else
8528       Opnds.push_back(In.getOperand(0));
8529   }
8530   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
8531                            &Opnds[0], Opnds.size());
8532   AddToWorkList(BV.getNode());
8533
8534   return DAG.getNode(Opcode, dl, VT, BV);
8535 }
8536
8537 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
8538   unsigned NumInScalars = N->getNumOperands();
8539   DebugLoc dl = N->getDebugLoc();
8540   EVT VT = N->getValueType(0);
8541
8542   // A vector built entirely of undefs is undef.
8543   if (ISD::allOperandsUndef(N))
8544     return DAG.getUNDEF(VT);
8545
8546   SDValue V = reduceBuildVecExtToExtBuildVec(N);
8547   if (V.getNode())
8548     return V;
8549
8550   V = reduceBuildVecConvertToConvertBuildVec(N);
8551   if (V.getNode())
8552     return V;
8553
8554   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
8555   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
8556   // at most two distinct vectors, turn this into a shuffle node.
8557
8558   // May only combine to shuffle after legalize if shuffle is legal.
8559   if (LegalOperations &&
8560       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
8561     return SDValue();
8562
8563   SDValue VecIn1, VecIn2;
8564   for (unsigned i = 0; i != NumInScalars; ++i) {
8565     // Ignore undef inputs.
8566     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
8567
8568     // If this input is something other than a EXTRACT_VECTOR_ELT with a
8569     // constant index, bail out.
8570     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8571         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
8572       VecIn1 = VecIn2 = SDValue(0, 0);
8573       break;
8574     }
8575
8576     // We allow up to two distinct input vectors.
8577     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
8578     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
8579       continue;
8580
8581     if (VecIn1.getNode() == 0) {
8582       VecIn1 = ExtractedFromVec;
8583     } else if (VecIn2.getNode() == 0) {
8584       VecIn2 = ExtractedFromVec;
8585     } else {
8586       // Too many inputs.
8587       VecIn1 = VecIn2 = SDValue(0, 0);
8588       break;
8589     }
8590   }
8591
8592     // If everything is good, we can make a shuffle operation.
8593   if (VecIn1.getNode()) {
8594     SmallVector<int, 8> Mask;
8595     for (unsigned i = 0; i != NumInScalars; ++i) {
8596       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
8597         Mask.push_back(-1);
8598         continue;
8599       }
8600
8601       // If extracting from the first vector, just use the index directly.
8602       SDValue Extract = N->getOperand(i);
8603       SDValue ExtVal = Extract.getOperand(1);
8604       if (Extract.getOperand(0) == VecIn1) {
8605         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
8606         if (ExtIndex > VT.getVectorNumElements())
8607           return SDValue();
8608
8609         Mask.push_back(ExtIndex);
8610         continue;
8611       }
8612
8613       // Otherwise, use InIdx + VecSize
8614       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
8615       Mask.push_back(Idx+NumInScalars);
8616     }
8617
8618     // We can't generate a shuffle node with mismatched input and output types.
8619     // Attempt to transform a single input vector to the correct type.
8620     if ((VT != VecIn1.getValueType())) {
8621       // We don't support shuffeling between TWO values of different types.
8622       if (VecIn2.getNode() != 0)
8623         return SDValue();
8624
8625       // We only support widening of vectors which are half the size of the
8626       // output registers. For example XMM->YMM widening on X86 with AVX.
8627       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
8628         return SDValue();
8629
8630       // If the input vector type has a different base type to the output
8631       // vector type, bail out.
8632       if (VecIn1.getValueType().getVectorElementType() !=
8633           VT.getVectorElementType())
8634         return SDValue();
8635
8636       // Widen the input vector by adding undef values.
8637       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8638                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
8639     }
8640
8641     // If VecIn2 is unused then change it to undef.
8642     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
8643
8644     // Check that we were able to transform all incoming values to the same
8645     // type.
8646     if (VecIn2.getValueType() != VecIn1.getValueType() ||
8647         VecIn1.getValueType() != VT)
8648           return SDValue();
8649
8650     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
8651     if (!isTypeLegal(VT))
8652       return SDValue();
8653
8654     // Return the new VECTOR_SHUFFLE node.
8655     SDValue Ops[2];
8656     Ops[0] = VecIn1;
8657     Ops[1] = VecIn2;
8658     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
8659   }
8660
8661   return SDValue();
8662 }
8663
8664 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
8665   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
8666   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
8667   // inputs come from at most two distinct vectors, turn this into a shuffle
8668   // node.
8669
8670   // If we only have one input vector, we don't need to do any concatenation.
8671   if (N->getNumOperands() == 1)
8672     return N->getOperand(0);
8673
8674   // Check if all of the operands are undefs.
8675   if (ISD::allOperandsUndef(N))
8676     return DAG.getUNDEF(N->getValueType(0));
8677
8678   return SDValue();
8679 }
8680
8681 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
8682   EVT NVT = N->getValueType(0);
8683   SDValue V = N->getOperand(0);
8684
8685   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
8686     // Handle only simple case where vector being inserted and vector
8687     // being extracted are of same type, and are half size of larger vectors.
8688     EVT BigVT = V->getOperand(0).getValueType();
8689     EVT SmallVT = V->getOperand(1).getValueType();
8690     if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
8691       return SDValue();
8692
8693     // Only handle cases where both indexes are constants with the same type.
8694     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
8695     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
8696
8697     if (InsIdx && ExtIdx &&
8698         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
8699         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
8700       // Combine:
8701       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
8702       // Into:
8703       //    indices are equal => V1
8704       //    otherwise => (extract_subvec V1, ExtIdx)
8705       if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
8706         return V->getOperand(1);
8707       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
8708                          V->getOperand(0), N->getOperand(1));
8709     }
8710   }
8711
8712   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
8713     // Combine:
8714     //    (extract_subvec (concat V1, V2, ...), i)
8715     // Into:
8716     //    Vi if possible
8717     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
8718     if (V->getOperand(0).getValueType() != NVT)
8719       return SDValue();
8720     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8721     unsigned NumElems = NVT.getVectorNumElements();
8722     assert((Idx % NumElems) == 0 &&
8723            "IDX in concat is not a multiple of the result vector length.");
8724     return V->getOperand(Idx / NumElems);
8725   }
8726
8727   return SDValue();
8728 }
8729
8730 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
8731   EVT VT = N->getValueType(0);
8732   unsigned NumElts = VT.getVectorNumElements();
8733
8734   SDValue N0 = N->getOperand(0);
8735   SDValue N1 = N->getOperand(1);
8736
8737   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
8738
8739   // Canonicalize shuffle undef, undef -> undef
8740   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
8741     return DAG.getUNDEF(VT);
8742
8743   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8744
8745   // Canonicalize shuffle v, v -> v, undef
8746   if (N0 == N1) {
8747     SmallVector<int, 8> NewMask;
8748     for (unsigned i = 0; i != NumElts; ++i) {
8749       int Idx = SVN->getMaskElt(i);
8750       if (Idx >= (int)NumElts) Idx -= NumElts;
8751       NewMask.push_back(Idx);
8752     }
8753     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
8754                                 &NewMask[0]);
8755   }
8756
8757   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
8758   if (N0.getOpcode() == ISD::UNDEF) {
8759     SmallVector<int, 8> NewMask;
8760     for (unsigned i = 0; i != NumElts; ++i) {
8761       int Idx = SVN->getMaskElt(i);
8762       if (Idx >= 0) {
8763         if (Idx < (int)NumElts)
8764           Idx += NumElts;
8765         else
8766           Idx -= NumElts;
8767       }
8768       NewMask.push_back(Idx);
8769     }
8770     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
8771                                 &NewMask[0]);
8772   }
8773
8774   // Remove references to rhs if it is undef
8775   if (N1.getOpcode() == ISD::UNDEF) {
8776     bool Changed = false;
8777     SmallVector<int, 8> NewMask;
8778     for (unsigned i = 0; i != NumElts; ++i) {
8779       int Idx = SVN->getMaskElt(i);
8780       if (Idx >= (int)NumElts) {
8781         Idx = -1;
8782         Changed = true;
8783       }
8784       NewMask.push_back(Idx);
8785     }
8786     if (Changed)
8787       return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
8788   }
8789
8790   // If it is a splat, check if the argument vector is another splat or a
8791   // build_vector with all scalar elements the same.
8792   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
8793     SDNode *V = N0.getNode();
8794
8795     // If this is a bit convert that changes the element type of the vector but
8796     // not the number of vector elements, look through it.  Be careful not to
8797     // look though conversions that change things like v4f32 to v2f64.
8798     if (V->getOpcode() == ISD::BITCAST) {
8799       SDValue ConvInput = V->getOperand(0);
8800       if (ConvInput.getValueType().isVector() &&
8801           ConvInput.getValueType().getVectorNumElements() == NumElts)
8802         V = ConvInput.getNode();
8803     }
8804
8805     if (V->getOpcode() == ISD::BUILD_VECTOR) {
8806       assert(V->getNumOperands() == NumElts &&
8807              "BUILD_VECTOR has wrong number of operands");
8808       SDValue Base;
8809       bool AllSame = true;
8810       for (unsigned i = 0; i != NumElts; ++i) {
8811         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
8812           Base = V->getOperand(i);
8813           break;
8814         }
8815       }
8816       // Splat of <u, u, u, u>, return <u, u, u, u>
8817       if (!Base.getNode())
8818         return N0;
8819       for (unsigned i = 0; i != NumElts; ++i) {
8820         if (V->getOperand(i) != Base) {
8821           AllSame = false;
8822           break;
8823         }
8824       }
8825       // Splat of <x, x, x, x>, return <x, x, x, x>
8826       if (AllSame)
8827         return N0;
8828     }
8829   }
8830
8831   // If this shuffle node is simply a swizzle of another shuffle node,
8832   // and it reverses the swizzle of the previous shuffle then we can
8833   // optimize shuffle(shuffle(x, undef), undef) -> x.
8834   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
8835       N1.getOpcode() == ISD::UNDEF) {
8836
8837     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
8838
8839     // Shuffle nodes can only reverse shuffles with a single non-undef value.
8840     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
8841       return SDValue();
8842
8843     // The incoming shuffle must be of the same type as the result of the
8844     // current shuffle.
8845     assert(OtherSV->getOperand(0).getValueType() == VT &&
8846            "Shuffle types don't match");
8847
8848     for (unsigned i = 0; i != NumElts; ++i) {
8849       int Idx = SVN->getMaskElt(i);
8850       assert(Idx < (int)NumElts && "Index references undef operand");
8851       // Next, this index comes from the first value, which is the incoming
8852       // shuffle. Adopt the incoming index.
8853       if (Idx >= 0)
8854         Idx = OtherSV->getMaskElt(Idx);
8855
8856       // The combined shuffle must map each index to itself.
8857       if (Idx >= 0 && (unsigned)Idx != i)
8858         return SDValue();
8859     }
8860
8861     return OtherSV->getOperand(0);
8862   }
8863
8864   return SDValue();
8865 }
8866
8867 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
8868   if (!TLI.getShouldFoldAtomicFences())
8869     return SDValue();
8870
8871   SDValue atomic = N->getOperand(0);
8872   switch (atomic.getOpcode()) {
8873     case ISD::ATOMIC_CMP_SWAP:
8874     case ISD::ATOMIC_SWAP:
8875     case ISD::ATOMIC_LOAD_ADD:
8876     case ISD::ATOMIC_LOAD_SUB:
8877     case ISD::ATOMIC_LOAD_AND:
8878     case ISD::ATOMIC_LOAD_OR:
8879     case ISD::ATOMIC_LOAD_XOR:
8880     case ISD::ATOMIC_LOAD_NAND:
8881     case ISD::ATOMIC_LOAD_MIN:
8882     case ISD::ATOMIC_LOAD_MAX:
8883     case ISD::ATOMIC_LOAD_UMIN:
8884     case ISD::ATOMIC_LOAD_UMAX:
8885       break;
8886     default:
8887       return SDValue();
8888   }
8889
8890   SDValue fence = atomic.getOperand(0);
8891   if (fence.getOpcode() != ISD::MEMBARRIER)
8892     return SDValue();
8893
8894   switch (atomic.getOpcode()) {
8895     case ISD::ATOMIC_CMP_SWAP:
8896       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8897                                     fence.getOperand(0),
8898                                     atomic.getOperand(1), atomic.getOperand(2),
8899                                     atomic.getOperand(3)), atomic.getResNo());
8900     case ISD::ATOMIC_SWAP:
8901     case ISD::ATOMIC_LOAD_ADD:
8902     case ISD::ATOMIC_LOAD_SUB:
8903     case ISD::ATOMIC_LOAD_AND:
8904     case ISD::ATOMIC_LOAD_OR:
8905     case ISD::ATOMIC_LOAD_XOR:
8906     case ISD::ATOMIC_LOAD_NAND:
8907     case ISD::ATOMIC_LOAD_MIN:
8908     case ISD::ATOMIC_LOAD_MAX:
8909     case ISD::ATOMIC_LOAD_UMIN:
8910     case ISD::ATOMIC_LOAD_UMAX:
8911       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8912                                     fence.getOperand(0),
8913                                     atomic.getOperand(1), atomic.getOperand(2)),
8914                      atomic.getResNo());
8915     default:
8916       return SDValue();
8917   }
8918 }
8919
8920 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
8921 /// an AND to a vector_shuffle with the destination vector and a zero vector.
8922 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
8923 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
8924 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
8925   EVT VT = N->getValueType(0);
8926   DebugLoc dl = N->getDebugLoc();
8927   SDValue LHS = N->getOperand(0);
8928   SDValue RHS = N->getOperand(1);
8929   if (N->getOpcode() == ISD::AND) {
8930     if (RHS.getOpcode() == ISD::BITCAST)
8931       RHS = RHS.getOperand(0);
8932     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
8933       SmallVector<int, 8> Indices;
8934       unsigned NumElts = RHS.getNumOperands();
8935       for (unsigned i = 0; i != NumElts; ++i) {
8936         SDValue Elt = RHS.getOperand(i);
8937         if (!isa<ConstantSDNode>(Elt))
8938           return SDValue();
8939
8940         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
8941           Indices.push_back(i);
8942         else if (cast<ConstantSDNode>(Elt)->isNullValue())
8943           Indices.push_back(NumElts);
8944         else
8945           return SDValue();
8946       }
8947
8948       // Let's see if the target supports this vector_shuffle.
8949       EVT RVT = RHS.getValueType();
8950       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
8951         return SDValue();
8952
8953       // Return the new VECTOR_SHUFFLE node.
8954       EVT EltVT = RVT.getVectorElementType();
8955       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
8956                                      DAG.getConstant(0, EltVT));
8957       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8958                                  RVT, &ZeroOps[0], ZeroOps.size());
8959       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
8960       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
8961       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
8962     }
8963   }
8964
8965   return SDValue();
8966 }
8967
8968 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
8969 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
8970   // After legalize, the target may be depending on adds and other
8971   // binary ops to provide legal ways to construct constants or other
8972   // things. Simplifying them may result in a loss of legality.
8973   if (LegalOperations) return SDValue();
8974
8975   assert(N->getValueType(0).isVector() &&
8976          "SimplifyVBinOp only works on vectors!");
8977
8978   SDValue LHS = N->getOperand(0);
8979   SDValue RHS = N->getOperand(1);
8980   SDValue Shuffle = XformToShuffleWithZero(N);
8981   if (Shuffle.getNode()) return Shuffle;
8982
8983   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
8984   // this operation.
8985   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
8986       RHS.getOpcode() == ISD::BUILD_VECTOR) {
8987     SmallVector<SDValue, 8> Ops;
8988     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
8989       SDValue LHSOp = LHS.getOperand(i);
8990       SDValue RHSOp = RHS.getOperand(i);
8991       // If these two elements can't be folded, bail out.
8992       if ((LHSOp.getOpcode() != ISD::UNDEF &&
8993            LHSOp.getOpcode() != ISD::Constant &&
8994            LHSOp.getOpcode() != ISD::ConstantFP) ||
8995           (RHSOp.getOpcode() != ISD::UNDEF &&
8996            RHSOp.getOpcode() != ISD::Constant &&
8997            RHSOp.getOpcode() != ISD::ConstantFP))
8998         break;
8999
9000       // Can't fold divide by zero.
9001       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9002           N->getOpcode() == ISD::FDIV) {
9003         if ((RHSOp.getOpcode() == ISD::Constant &&
9004              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9005             (RHSOp.getOpcode() == ISD::ConstantFP &&
9006              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9007           break;
9008       }
9009
9010       EVT VT = LHSOp.getValueType();
9011       EVT RVT = RHSOp.getValueType();
9012       if (RVT != VT) {
9013         // Integer BUILD_VECTOR operands may have types larger than the element
9014         // size (e.g., when the element type is not legal).  Prior to type
9015         // legalization, the types may not match between the two BUILD_VECTORS.
9016         // Truncate one of the operands to make them match.
9017         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9018           RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
9019         } else {
9020           LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
9021           VT = RVT;
9022         }
9023       }
9024       SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
9025                                    LHSOp, RHSOp);
9026       if (FoldOp.getOpcode() != ISD::UNDEF &&
9027           FoldOp.getOpcode() != ISD::Constant &&
9028           FoldOp.getOpcode() != ISD::ConstantFP)
9029         break;
9030       Ops.push_back(FoldOp);
9031       AddToWorkList(FoldOp.getNode());
9032     }
9033
9034     if (Ops.size() == LHS.getNumOperands())
9035       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9036                          LHS.getValueType(), &Ops[0], Ops.size());
9037   }
9038
9039   return SDValue();
9040 }
9041
9042 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9043 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9044   // After legalize, the target may be depending on adds and other
9045   // binary ops to provide legal ways to construct constants or other
9046   // things. Simplifying them may result in a loss of legality.
9047   if (LegalOperations) return SDValue();
9048
9049   assert(N->getValueType(0).isVector() &&
9050          "SimplifyVUnaryOp only works on vectors!");
9051
9052   SDValue N0 = N->getOperand(0);
9053
9054   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9055     return SDValue();
9056
9057   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9058   SmallVector<SDValue, 8> Ops;
9059   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9060     SDValue Op = N0.getOperand(i);
9061     if (Op.getOpcode() != ISD::UNDEF &&
9062         Op.getOpcode() != ISD::ConstantFP)
9063       break;
9064     EVT EltVT = Op.getValueType();
9065     SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op);
9066     if (FoldOp.getOpcode() != ISD::UNDEF &&
9067         FoldOp.getOpcode() != ISD::ConstantFP)
9068       break;
9069     Ops.push_back(FoldOp);
9070     AddToWorkList(FoldOp.getNode());
9071   }
9072
9073   if (Ops.size() != N0.getNumOperands())
9074     return SDValue();
9075
9076   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9077                      N0.getValueType(), &Ops[0], Ops.size());
9078 }
9079
9080 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
9081                                     SDValue N1, SDValue N2){
9082   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9083
9084   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9085                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9086
9087   // If we got a simplified select_cc node back from SimplifySelectCC, then
9088   // break it down into a new SETCC node, and a new SELECT node, and then return
9089   // the SELECT node, since we were called with a SELECT node.
9090   if (SCC.getNode()) {
9091     // Check to see if we got a select_cc back (to turn into setcc/select).
9092     // Otherwise, just return whatever node we got back, like fabs.
9093     if (SCC.getOpcode() == ISD::SELECT_CC) {
9094       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
9095                                   N0.getValueType(),
9096                                   SCC.getOperand(0), SCC.getOperand(1),
9097                                   SCC.getOperand(4));
9098       AddToWorkList(SETCC.getNode());
9099       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
9100                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
9101     }
9102
9103     return SCC;
9104   }
9105   return SDValue();
9106 }
9107
9108 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9109 /// are the two values being selected between, see if we can simplify the
9110 /// select.  Callers of this should assume that TheSelect is deleted if this
9111 /// returns true.  As such, they should return the appropriate thing (e.g. the
9112 /// node) back to the top-level of the DAG combiner loop to avoid it being
9113 /// looked at.
9114 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9115                                     SDValue RHS) {
9116
9117   // Cannot simplify select with vector condition
9118   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9119
9120   // If this is a select from two identical things, try to pull the operation
9121   // through the select.
9122   if (LHS.getOpcode() != RHS.getOpcode() ||
9123       !LHS.hasOneUse() || !RHS.hasOneUse())
9124     return false;
9125
9126   // If this is a load and the token chain is identical, replace the select
9127   // of two loads with a load through a select of the address to load from.
9128   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9129   // constants have been dropped into the constant pool.
9130   if (LHS.getOpcode() == ISD::LOAD) {
9131     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9132     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9133
9134     // Token chains must be identical.
9135     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9136         // Do not let this transformation reduce the number of volatile loads.
9137         LLD->isVolatile() || RLD->isVolatile() ||
9138         // If this is an EXTLOAD, the VT's must match.
9139         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9140         // If this is an EXTLOAD, the kind of extension must match.
9141         (LLD->getExtensionType() != RLD->getExtensionType() &&
9142          // The only exception is if one of the extensions is anyext.
9143          LLD->getExtensionType() != ISD::EXTLOAD &&
9144          RLD->getExtensionType() != ISD::EXTLOAD) ||
9145         // FIXME: this discards src value information.  This is
9146         // over-conservative. It would be beneficial to be able to remember
9147         // both potential memory locations.  Since we are discarding
9148         // src value info, don't do the transformation if the memory
9149         // locations are not in the default address space.
9150         LLD->getPointerInfo().getAddrSpace() != 0 ||
9151         RLD->getPointerInfo().getAddrSpace() != 0)
9152       return false;
9153
9154     // Check that the select condition doesn't reach either load.  If so,
9155     // folding this will induce a cycle into the DAG.  If not, this is safe to
9156     // xform, so create a select of the addresses.
9157     SDValue Addr;
9158     if (TheSelect->getOpcode() == ISD::SELECT) {
9159       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9160       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9161           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9162         return false;
9163       // The loads must not depend on one another.
9164       if (LLD->isPredecessorOf(RLD) ||
9165           RLD->isPredecessorOf(LLD))
9166         return false;
9167       Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
9168                          LLD->getBasePtr().getValueType(),
9169                          TheSelect->getOperand(0), LLD->getBasePtr(),
9170                          RLD->getBasePtr());
9171     } else {  // Otherwise SELECT_CC
9172       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9173       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9174
9175       if ((LLD->hasAnyUseOfValue(1) &&
9176            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9177           (RLD->hasAnyUseOfValue(1) &&
9178            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9179         return false;
9180
9181       Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
9182                          LLD->getBasePtr().getValueType(),
9183                          TheSelect->getOperand(0),
9184                          TheSelect->getOperand(1),
9185                          LLD->getBasePtr(), RLD->getBasePtr(),
9186                          TheSelect->getOperand(4));
9187     }
9188
9189     SDValue Load;
9190     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9191       Load = DAG.getLoad(TheSelect->getValueType(0),
9192                          TheSelect->getDebugLoc(),
9193                          // FIXME: Discards pointer info.
9194                          LLD->getChain(), Addr, MachinePointerInfo(),
9195                          LLD->isVolatile(), LLD->isNonTemporal(),
9196                          LLD->isInvariant(), LLD->getAlignment());
9197     } else {
9198       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9199                             RLD->getExtensionType() : LLD->getExtensionType(),
9200                             TheSelect->getDebugLoc(),
9201                             TheSelect->getValueType(0),
9202                             // FIXME: Discards pointer info.
9203                             LLD->getChain(), Addr, MachinePointerInfo(),
9204                             LLD->getMemoryVT(), LLD->isVolatile(),
9205                             LLD->isNonTemporal(), LLD->getAlignment());
9206     }
9207
9208     // Users of the select now use the result of the load.
9209     CombineTo(TheSelect, Load);
9210
9211     // Users of the old loads now use the new load's chain.  We know the
9212     // old-load value is dead now.
9213     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9214     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9215     return true;
9216   }
9217
9218   return false;
9219 }
9220
9221 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9222 /// where 'cond' is the comparison specified by CC.
9223 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
9224                                       SDValue N2, SDValue N3,
9225                                       ISD::CondCode CC, bool NotExtCompare) {
9226   // (x ? y : y) -> y.
9227   if (N2 == N3) return N2;
9228
9229   EVT VT = N2.getValueType();
9230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9231   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9232   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9233
9234   // Determine if the condition we're dealing with is constant
9235   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
9236                               N0, N1, CC, DL, false);
9237   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9238   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9239
9240   // fold select_cc true, x, y -> x
9241   if (SCCC && !SCCC->isNullValue())
9242     return N2;
9243   // fold select_cc false, x, y -> y
9244   if (SCCC && SCCC->isNullValue())
9245     return N3;
9246
9247   // Check to see if we can simplify the select into an fabs node
9248   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9249     // Allow either -0.0 or 0.0
9250     if (CFP->getValueAPF().isZero()) {
9251       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9252       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9253           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9254           N2 == N3.getOperand(0))
9255         return DAG.getNode(ISD::FABS, DL, VT, N0);
9256
9257       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9258       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9259           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9260           N2.getOperand(0) == N3)
9261         return DAG.getNode(ISD::FABS, DL, VT, N3);
9262     }
9263   }
9264
9265   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9266   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9267   // in it.  This is a win when the constant is not otherwise available because
9268   // it replaces two constant pool loads with one.  We only do this if the FP
9269   // type is known to be legal, because if it isn't, then we are before legalize
9270   // types an we want the other legalization to happen first (e.g. to avoid
9271   // messing with soft float) and if the ConstantFP is not legal, because if
9272   // it is legal, we may not need to store the FP constant in a constant pool.
9273   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9274     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9275       if (TLI.isTypeLegal(N2.getValueType()) &&
9276           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9277            TargetLowering::Legal) &&
9278           // If both constants have multiple uses, then we won't need to do an
9279           // extra load, they are likely around in registers for other users.
9280           (TV->hasOneUse() || FV->hasOneUse())) {
9281         Constant *Elts[] = {
9282           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9283           const_cast<ConstantFP*>(TV->getConstantFPValue())
9284         };
9285         Type *FPTy = Elts[0]->getType();
9286         const DataLayout &TD = *TLI.getDataLayout();
9287
9288         // Create a ConstantArray of the two constants.
9289         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9290         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9291                                             TD.getPrefTypeAlignment(FPTy));
9292         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9293
9294         // Get the offsets to the 0 and 1 element of the array so that we can
9295         // select between them.
9296         SDValue Zero = DAG.getIntPtrConstant(0);
9297         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9298         SDValue One = DAG.getIntPtrConstant(EltSize);
9299
9300         SDValue Cond = DAG.getSetCC(DL,
9301                                     TLI.getSetCCResultType(N0.getValueType()),
9302                                     N0, N1, CC);
9303         AddToWorkList(Cond.getNode());
9304         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
9305                                         Cond, One, Zero);
9306         AddToWorkList(CstOffset.getNode());
9307         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9308                             CstOffset);
9309         AddToWorkList(CPIdx.getNode());
9310         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9311                            MachinePointerInfo::getConstantPool(), false,
9312                            false, false, Alignment);
9313
9314       }
9315     }
9316
9317   // Check to see if we can perform the "gzip trick", transforming
9318   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9319   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9320       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9321        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9322     EVT XType = N0.getValueType();
9323     EVT AType = N2.getValueType();
9324     if (XType.bitsGE(AType)) {
9325       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9326       // single-bit constant.
9327       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9328         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9329         ShCtV = XType.getSizeInBits()-ShCtV-1;
9330         SDValue ShCt = DAG.getConstant(ShCtV,
9331                                        getShiftAmountTy(N0.getValueType()));
9332         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
9333                                     XType, N0, ShCt);
9334         AddToWorkList(Shift.getNode());
9335
9336         if (XType.bitsGT(AType)) {
9337           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9338           AddToWorkList(Shift.getNode());
9339         }
9340
9341         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9342       }
9343
9344       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
9345                                   XType, N0,
9346                                   DAG.getConstant(XType.getSizeInBits()-1,
9347                                          getShiftAmountTy(N0.getValueType())));
9348       AddToWorkList(Shift.getNode());
9349
9350       if (XType.bitsGT(AType)) {
9351         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9352         AddToWorkList(Shift.getNode());
9353       }
9354
9355       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9356     }
9357   }
9358
9359   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9360   // where y is has a single bit set.
9361   // A plaintext description would be, we can turn the SELECT_CC into an AND
9362   // when the condition can be materialized as an all-ones register.  Any
9363   // single bit-test can be materialized as an all-ones register with
9364   // shift-left and shift-right-arith.
9365   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9366       N0->getValueType(0) == VT &&
9367       N1C && N1C->isNullValue() &&
9368       N2C && N2C->isNullValue()) {
9369     SDValue AndLHS = N0->getOperand(0);
9370     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9371     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9372       // Shift the tested bit over the sign bit.
9373       APInt AndMask = ConstAndRHS->getAPIntValue();
9374       SDValue ShlAmt =
9375         DAG.getConstant(AndMask.countLeadingZeros(),
9376                         getShiftAmountTy(AndLHS.getValueType()));
9377       SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
9378
9379       // Now arithmetic right shift it all the way over, so the result is either
9380       // all-ones, or zero.
9381       SDValue ShrAmt =
9382         DAG.getConstant(AndMask.getBitWidth()-1,
9383                         getShiftAmountTy(Shl.getValueType()));
9384       SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
9385
9386       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9387     }
9388   }
9389
9390   // fold select C, 16, 0 -> shl C, 4
9391   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9392     TLI.getBooleanContents(N0.getValueType().isVector()) ==
9393       TargetLowering::ZeroOrOneBooleanContent) {
9394
9395     // If the caller doesn't want us to simplify this into a zext of a compare,
9396     // don't do it.
9397     if (NotExtCompare && N2C->getAPIntValue() == 1)
9398       return SDValue();
9399
9400     // Get a SetCC of the condition
9401     // FIXME: Should probably make sure that setcc is legal if we ever have a
9402     // target where it isn't.
9403     SDValue Temp, SCC;
9404     // cast from setcc result type to select result type
9405     if (LegalTypes) {
9406       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
9407                           N0, N1, CC);
9408       if (N2.getValueType().bitsLT(SCC.getValueType()))
9409         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
9410       else
9411         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9412                            N2.getValueType(), SCC);
9413     } else {
9414       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
9415       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9416                          N2.getValueType(), SCC);
9417     }
9418
9419     AddToWorkList(SCC.getNode());
9420     AddToWorkList(Temp.getNode());
9421
9422     if (N2C->getAPIntValue() == 1)
9423       return Temp;
9424
9425     // shl setcc result by log2 n2c
9426     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9427                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
9428                                        getShiftAmountTy(Temp.getValueType())));
9429   }
9430
9431   // Check to see if this is the equivalent of setcc
9432   // FIXME: Turn all of these into setcc if setcc if setcc is legal
9433   // otherwise, go ahead with the folds.
9434   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9435     EVT XType = N0.getValueType();
9436     if (!LegalOperations ||
9437         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
9438       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
9439       if (Res.getValueType() != VT)
9440         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9441       return Res;
9442     }
9443
9444     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9445     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9446         (!LegalOperations ||
9447          TLI.isOperationLegal(ISD::CTLZ, XType))) {
9448       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
9449       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9450                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
9451                                        getShiftAmountTy(Ctlz.getValueType())));
9452     }
9453     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9454     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9455       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
9456                                   XType, DAG.getConstant(0, XType), N0);
9457       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
9458       return DAG.getNode(ISD::SRL, DL, XType,
9459                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
9460                          DAG.getConstant(XType.getSizeInBits()-1,
9461                                          getShiftAmountTy(XType)));
9462     }
9463     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
9464     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
9465       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
9466                                  DAG.getConstant(XType.getSizeInBits()-1,
9467                                          getShiftAmountTy(N0.getValueType())));
9468       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
9469     }
9470   }
9471
9472   // Check to see if this is an integer abs.
9473   // select_cc setg[te] X,  0,  X, -X ->
9474   // select_cc setgt    X, -1,  X, -X ->
9475   // select_cc setl[te] X,  0, -X,  X ->
9476   // select_cc setlt    X,  1, -X,  X ->
9477   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9478   if (N1C) {
9479     ConstantSDNode *SubC = NULL;
9480     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
9481          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
9482         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
9483       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
9484     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
9485               (N1C->isOne() && CC == ISD::SETLT)) &&
9486              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
9487       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
9488
9489     EVT XType = N0.getValueType();
9490     if (SubC && SubC->isNullValue() && XType.isInteger()) {
9491       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
9492                                   N0,
9493                                   DAG.getConstant(XType.getSizeInBits()-1,
9494                                          getShiftAmountTy(N0.getValueType())));
9495       SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
9496                                 XType, N0, Shift);
9497       AddToWorkList(Shift.getNode());
9498       AddToWorkList(Add.getNode());
9499       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
9500     }
9501   }
9502
9503   return SDValue();
9504 }
9505
9506 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
9507 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
9508                                    SDValue N1, ISD::CondCode Cond,
9509                                    DebugLoc DL, bool foldBooleans) {
9510   TargetLowering::DAGCombinerInfo
9511     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
9512   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
9513 }
9514
9515 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
9516 /// return a DAG expression to select that will generate the same value by
9517 /// multiplying by a magic number.  See:
9518 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9519 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
9520   std::vector<SDNode*> Built;
9521   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
9522
9523   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9524        ii != ee; ++ii)
9525     AddToWorkList(*ii);
9526   return S;
9527 }
9528
9529 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
9530 /// return a DAG expression to select that will generate the same value by
9531 /// multiplying by a magic number.  See:
9532 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9533 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
9534   std::vector<SDNode*> Built;
9535   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
9536
9537   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9538        ii != ee; ++ii)
9539     AddToWorkList(*ii);
9540   return S;
9541 }
9542
9543 /// FindBaseOffset - Return true if base is a frame index, which is known not
9544 // to alias with anything but itself.  Provides base object and offset as
9545 // results.
9546 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
9547                            const GlobalValue *&GV, const void *&CV) {
9548   // Assume it is a primitive operation.
9549   Base = Ptr; Offset = 0; GV = 0; CV = 0;
9550
9551   // If it's an adding a simple constant then integrate the offset.
9552   if (Base.getOpcode() == ISD::ADD) {
9553     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
9554       Base = Base.getOperand(0);
9555       Offset += C->getZExtValue();
9556     }
9557   }
9558
9559   // Return the underlying GlobalValue, and update the Offset.  Return false
9560   // for GlobalAddressSDNode since the same GlobalAddress may be represented
9561   // by multiple nodes with different offsets.
9562   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
9563     GV = G->getGlobal();
9564     Offset += G->getOffset();
9565     return false;
9566   }
9567
9568   // Return the underlying Constant value, and update the Offset.  Return false
9569   // for ConstantSDNodes since the same constant pool entry may be represented
9570   // by multiple nodes with different offsets.
9571   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
9572     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
9573                                          : (const void *)C->getConstVal();
9574     Offset += C->getOffset();
9575     return false;
9576   }
9577   // If it's any of the following then it can't alias with anything but itself.
9578   return isa<FrameIndexSDNode>(Base);
9579 }
9580
9581 /// isAlias - Return true if there is any possibility that the two addresses
9582 /// overlap.
9583 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
9584                           const Value *SrcValue1, int SrcValueOffset1,
9585                           unsigned SrcValueAlign1,
9586                           const MDNode *TBAAInfo1,
9587                           SDValue Ptr2, int64_t Size2,
9588                           const Value *SrcValue2, int SrcValueOffset2,
9589                           unsigned SrcValueAlign2,
9590                           const MDNode *TBAAInfo2) const {
9591   // If they are the same then they must be aliases.
9592   if (Ptr1 == Ptr2) return true;
9593
9594   // Gather base node and offset information.
9595   SDValue Base1, Base2;
9596   int64_t Offset1, Offset2;
9597   const GlobalValue *GV1, *GV2;
9598   const void *CV1, *CV2;
9599   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
9600   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
9601
9602   // If they have a same base address then check to see if they overlap.
9603   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
9604     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
9605
9606   // It is possible for different frame indices to alias each other, mostly
9607   // when tail call optimization reuses return address slots for arguments.
9608   // To catch this case, look up the actual index of frame indices to compute
9609   // the real alias relationship.
9610   if (isFrameIndex1 && isFrameIndex2) {
9611     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9612     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
9613     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
9614     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
9615   }
9616
9617   // Otherwise, if we know what the bases are, and they aren't identical, then
9618   // we know they cannot alias.
9619   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
9620     return false;
9621
9622   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
9623   // compared to the size and offset of the access, we may be able to prove they
9624   // do not alias.  This check is conservative for now to catch cases created by
9625   // splitting vector types.
9626   if ((SrcValueAlign1 == SrcValueAlign2) &&
9627       (SrcValueOffset1 != SrcValueOffset2) &&
9628       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
9629     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
9630     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
9631
9632     // There is no overlap between these relatively aligned accesses of similar
9633     // size, return no alias.
9634     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
9635       return false;
9636   }
9637
9638   if (CombinerGlobalAA) {
9639     // Use alias analysis information.
9640     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
9641     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
9642     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
9643     AliasAnalysis::AliasResult AAResult =
9644       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
9645                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
9646     if (AAResult == AliasAnalysis::NoAlias)
9647       return false;
9648   }
9649
9650   // Otherwise we have to assume they alias.
9651   return true;
9652 }
9653
9654 /// FindAliasInfo - Extracts the relevant alias information from the memory
9655 /// node.  Returns true if the operand was a load.
9656 bool DAGCombiner::FindAliasInfo(SDNode *N,
9657                                 SDValue &Ptr, int64_t &Size,
9658                                 const Value *&SrcValue,
9659                                 int &SrcValueOffset,
9660                                 unsigned &SrcValueAlign,
9661                                 const MDNode *&TBAAInfo) const {
9662   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
9663
9664   Ptr = LS->getBasePtr();
9665   Size = LS->getMemoryVT().getSizeInBits() >> 3;
9666   SrcValue = LS->getSrcValue();
9667   SrcValueOffset = LS->getSrcValueOffset();
9668   SrcValueAlign = LS->getOriginalAlignment();
9669   TBAAInfo = LS->getTBAAInfo();
9670   return isa<LoadSDNode>(LS);
9671 }
9672
9673 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
9674 /// looking for aliasing nodes and adding them to the Aliases vector.
9675 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
9676                                    SmallVector<SDValue, 8> &Aliases) {
9677   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
9678   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
9679
9680   // Get alias information for node.
9681   SDValue Ptr;
9682   int64_t Size;
9683   const Value *SrcValue;
9684   int SrcValueOffset;
9685   unsigned SrcValueAlign;
9686   const MDNode *SrcTBAAInfo;
9687   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
9688                               SrcValueAlign, SrcTBAAInfo);
9689
9690   // Starting off.
9691   Chains.push_back(OriginalChain);
9692   unsigned Depth = 0;
9693
9694   // Look at each chain and determine if it is an alias.  If so, add it to the
9695   // aliases list.  If not, then continue up the chain looking for the next
9696   // candidate.
9697   while (!Chains.empty()) {
9698     SDValue Chain = Chains.back();
9699     Chains.pop_back();
9700
9701     // For TokenFactor nodes, look at each operand and only continue up the
9702     // chain until we find two aliases.  If we've seen two aliases, assume we'll
9703     // find more and revert to original chain since the xform is unlikely to be
9704     // profitable.
9705     //
9706     // FIXME: The depth check could be made to return the last non-aliasing
9707     // chain we found before we hit a tokenfactor rather than the original
9708     // chain.
9709     if (Depth > 6 || Aliases.size() == 2) {
9710       Aliases.clear();
9711       Aliases.push_back(OriginalChain);
9712       break;
9713     }
9714
9715     // Don't bother if we've been before.
9716     if (!Visited.insert(Chain.getNode()))
9717       continue;
9718
9719     switch (Chain.getOpcode()) {
9720     case ISD::EntryToken:
9721       // Entry token is ideal chain operand, but handled in FindBetterChain.
9722       break;
9723
9724     case ISD::LOAD:
9725     case ISD::STORE: {
9726       // Get alias information for Chain.
9727       SDValue OpPtr;
9728       int64_t OpSize;
9729       const Value *OpSrcValue;
9730       int OpSrcValueOffset;
9731       unsigned OpSrcValueAlign;
9732       const MDNode *OpSrcTBAAInfo;
9733       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
9734                                     OpSrcValue, OpSrcValueOffset,
9735                                     OpSrcValueAlign,
9736                                     OpSrcTBAAInfo);
9737
9738       // If chain is alias then stop here.
9739       if (!(IsLoad && IsOpLoad) &&
9740           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
9741                   SrcTBAAInfo,
9742                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
9743                   OpSrcValueAlign, OpSrcTBAAInfo)) {
9744         Aliases.push_back(Chain);
9745       } else {
9746         // Look further up the chain.
9747         Chains.push_back(Chain.getOperand(0));
9748         ++Depth;
9749       }
9750       break;
9751     }
9752
9753     case ISD::TokenFactor:
9754       // We have to check each of the operands of the token factor for "small"
9755       // token factors, so we queue them up.  Adding the operands to the queue
9756       // (stack) in reverse order maintains the original order and increases the
9757       // likelihood that getNode will find a matching token factor (CSE.)
9758       if (Chain.getNumOperands() > 16) {
9759         Aliases.push_back(Chain);
9760         break;
9761       }
9762       for (unsigned n = Chain.getNumOperands(); n;)
9763         Chains.push_back(Chain.getOperand(--n));
9764       ++Depth;
9765       break;
9766
9767     default:
9768       // For all other instructions we will just have to take what we can get.
9769       Aliases.push_back(Chain);
9770       break;
9771     }
9772   }
9773 }
9774
9775 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
9776 /// for a better chain (aliasing node.)
9777 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
9778   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
9779
9780   // Accumulate all the aliases to this node.
9781   GatherAllAliases(N, OldChain, Aliases);
9782
9783   // If no operands then chain to entry token.
9784   if (Aliases.size() == 0)
9785     return DAG.getEntryNode();
9786
9787   // If a single operand then chain to it.  We don't need to revisit it.
9788   if (Aliases.size() == 1)
9789     return Aliases[0];
9790
9791   // Construct a custom tailored token factor.
9792   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
9793                      &Aliases[0], Aliases.size());
9794 }
9795
9796 // SelectionDAG::Combine - This is the entry point for the file.
9797 //
9798 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
9799                            CodeGenOpt::Level OptLevel) {
9800   /// run - This is the main entry point to this class.
9801   ///
9802   DAGCombiner(*this, AA, OptLevel).Run(Level);
9803 }