Remove unused but set variables.
[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/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NodesCombined   , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
45 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
46
47 namespace {
48   static cl::opt<bool>
49     CombinerAA("combiner-alias-analysis", cl::Hidden,
50                cl::desc("Turn on alias analysis during testing"));
51
52   static cl::opt<bool>
53     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54                cl::desc("Include global information in alias analysis"));
55
56 //------------------------------ DAGCombiner ---------------------------------//
57
58   class DAGCombiner {
59     SelectionDAG &DAG;
60     const TargetLowering &TLI;
61     CombineLevel Level;
62     CodeGenOpt::Level OptLevel;
63     bool LegalOperations;
64     bool LegalTypes;
65
66     // Worklist of all of the nodes that need to be simplified.
67     std::vector<SDNode*> WorkList;
68
69     // AA - Used for DAG load/store alias analysis.
70     AliasAnalysis &AA;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(SDNode *N) {
77       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
78            UI != UE; ++UI)
79         AddToWorkList(*UI);
80     }
81
82     /// visit - call the node-specific routine that knows how to fold each
83     /// particular type of node.
84     SDValue visit(SDNode *N);
85
86   public:
87     /// AddToWorkList - Add to the work list making sure it's instance is at the
88     /// the back (next to be processed.)
89     void AddToWorkList(SDNode *N) {
90       removeFromWorkList(N);
91       WorkList.push_back(N);
92     }
93
94     /// removeFromWorkList - remove all instances of N from the worklist.
95     ///
96     void removeFromWorkList(SDNode *N) {
97       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
98                      WorkList.end());
99     }
100
101     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
102                       bool AddTo = true);
103
104     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105       return CombineTo(N, &Res, 1, AddTo);
106     }
107
108     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
109                       bool AddTo = true) {
110       SDValue To[] = { Res0, Res1 };
111       return CombineTo(N, To, 2, AddTo);
112     }
113
114     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
115
116   private:
117
118     /// SimplifyDemandedBits - Check the specified integer node value to see if
119     /// it can be simplified or if things it uses can be simplified by bit
120     /// propagation.  If so, return true.
121     bool SimplifyDemandedBits(SDValue Op) {
122       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123       APInt Demanded = APInt::getAllOnesValue(BitWidth);
124       return SimplifyDemandedBits(Op, Demanded);
125     }
126
127     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
128
129     bool CombineToPreIndexedLoadStore(SDNode *N);
130     bool CombineToPostIndexedLoadStore(SDNode *N);
131
132     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
133     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
134     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
135     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
136     SDValue PromoteIntBinOp(SDValue Op);
137     SDValue PromoteIntShiftOp(SDValue Op);
138     SDValue PromoteExtend(SDValue Op);
139     bool PromoteLoad(SDValue Op);
140
141     void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
142                          SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
143                          ISD::NodeType ExtType);
144
145     /// combine - call the node-specific routine that knows how to fold each
146     /// particular type of node. If that doesn't do anything, try the
147     /// target-specific DAG combines.
148     SDValue combine(SDNode *N);
149
150     // Visitation implementation - Implement dag node combining for different
151     // node types.  The semantics are as follows:
152     // Return Value:
153     //   SDValue.getNode() == 0 - No change was made
154     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
155     //   otherwise              - N should be replaced by the returned Operand.
156     //
157     SDValue visitTokenFactor(SDNode *N);
158     SDValue visitMERGE_VALUES(SDNode *N);
159     SDValue visitADD(SDNode *N);
160     SDValue visitSUB(SDNode *N);
161     SDValue visitADDC(SDNode *N);
162     SDValue visitADDE(SDNode *N);
163     SDValue visitMUL(SDNode *N);
164     SDValue visitSDIV(SDNode *N);
165     SDValue visitUDIV(SDNode *N);
166     SDValue visitSREM(SDNode *N);
167     SDValue visitUREM(SDNode *N);
168     SDValue visitMULHU(SDNode *N);
169     SDValue visitMULHS(SDNode *N);
170     SDValue visitSMUL_LOHI(SDNode *N);
171     SDValue visitUMUL_LOHI(SDNode *N);
172     SDValue visitSMULO(SDNode *N);
173     SDValue visitUMULO(SDNode *N);
174     SDValue visitSDIVREM(SDNode *N);
175     SDValue visitUDIVREM(SDNode *N);
176     SDValue visitAND(SDNode *N);
177     SDValue visitOR(SDNode *N);
178     SDValue visitXOR(SDNode *N);
179     SDValue SimplifyVBinOp(SDNode *N);
180     SDValue visitSHL(SDNode *N);
181     SDValue visitSRA(SDNode *N);
182     SDValue visitSRL(SDNode *N);
183     SDValue visitCTLZ(SDNode *N);
184     SDValue visitCTTZ(SDNode *N);
185     SDValue visitCTPOP(SDNode *N);
186     SDValue visitSELECT(SDNode *N);
187     SDValue visitSELECT_CC(SDNode *N);
188     SDValue visitSETCC(SDNode *N);
189     SDValue visitSIGN_EXTEND(SDNode *N);
190     SDValue visitZERO_EXTEND(SDNode *N);
191     SDValue visitANY_EXTEND(SDNode *N);
192     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
193     SDValue visitTRUNCATE(SDNode *N);
194     SDValue visitBITCAST(SDNode *N);
195     SDValue visitBUILD_PAIR(SDNode *N);
196     SDValue visitFADD(SDNode *N);
197     SDValue visitFSUB(SDNode *N);
198     SDValue visitFMUL(SDNode *N);
199     SDValue visitFDIV(SDNode *N);
200     SDValue visitFREM(SDNode *N);
201     SDValue visitFCOPYSIGN(SDNode *N);
202     SDValue visitSINT_TO_FP(SDNode *N);
203     SDValue visitUINT_TO_FP(SDNode *N);
204     SDValue visitFP_TO_SINT(SDNode *N);
205     SDValue visitFP_TO_UINT(SDNode *N);
206     SDValue visitFP_ROUND(SDNode *N);
207     SDValue visitFP_ROUND_INREG(SDNode *N);
208     SDValue visitFP_EXTEND(SDNode *N);
209     SDValue visitFNEG(SDNode *N);
210     SDValue visitFABS(SDNode *N);
211     SDValue visitBRCOND(SDNode *N);
212     SDValue visitBR_CC(SDNode *N);
213     SDValue visitLOAD(SDNode *N);
214     SDValue visitSTORE(SDNode *N);
215     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
216     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
217     SDValue visitBUILD_VECTOR(SDNode *N);
218     SDValue visitCONCAT_VECTORS(SDNode *N);
219     SDValue visitVECTOR_SHUFFLE(SDNode *N);
220     SDValue visitMEMBARRIER(SDNode *N);
221
222     SDValue XformToShuffleWithZero(SDNode *N);
223     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
224
225     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
226
227     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
228     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
229     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
230     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
231                              SDValue N3, ISD::CondCode CC,
232                              bool NotExtCompare = false);
233     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
234                           DebugLoc DL, bool foldBooleans = true);
235     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
236                                          unsigned HiOp);
237     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
238     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
239     SDValue BuildSDIV(SDNode *N);
240     SDValue BuildUDIV(SDNode *N);
241     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
242     SDValue ReduceLoadWidth(SDNode *N);
243     SDValue ReduceLoadOpStoreWidth(SDNode *N);
244     SDValue TransformFPLoadStorePair(SDNode *N);
245
246     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
247
248     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
249     /// looking for aliasing nodes and adding them to the Aliases vector.
250     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
251                           SmallVector<SDValue, 8> &Aliases);
252
253     /// isAlias - Return true if there is any possibility that the two addresses
254     /// overlap.
255     bool isAlias(SDValue Ptr1, int64_t Size1,
256                  const Value *SrcValue1, int SrcValueOffset1,
257                  unsigned SrcValueAlign1,
258                  const MDNode *TBAAInfo1,
259                  SDValue Ptr2, int64_t Size2,
260                  const Value *SrcValue2, int SrcValueOffset2,
261                  unsigned SrcValueAlign2,
262                  const MDNode *TBAAInfo2) const;
263
264     /// FindAliasInfo - Extracts the relevant alias information from the memory
265     /// node.  Returns true if the operand was a load.
266     bool FindAliasInfo(SDNode *N,
267                        SDValue &Ptr, int64_t &Size,
268                        const Value *&SrcValue, int &SrcValueOffset,
269                        unsigned &SrcValueAlignment,
270                        const MDNode *&TBAAInfo) const;
271
272     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
273     /// looking for a better chain (aliasing node.)
274     SDValue FindBetterChain(SDNode *N, SDValue Chain);
275
276   public:
277     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
278       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
279         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
280
281     /// Run - runs the dag combiner on all nodes in the work list
282     void Run(CombineLevel AtLevel);
283
284     SelectionDAG &getDAG() const { return DAG; }
285
286     /// getShiftAmountTy - Returns a type large enough to hold any valid
287     /// shift amount - before type legalization these can be huge.
288     EVT getShiftAmountTy(EVT LHSTy) {
289       return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
290     }
291
292     /// isTypeLegal - This method returns true if we are running before type
293     /// legalization or if the specified VT is legal.
294     bool isTypeLegal(const EVT &VT) {
295       if (!LegalTypes) return true;
296       return TLI.isTypeLegal(VT);
297     }
298   };
299 }
300
301
302 namespace {
303 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
304 /// nodes from the worklist.
305 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
306   DAGCombiner &DC;
307 public:
308   explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
309
310   virtual void NodeDeleted(SDNode *N, SDNode *E) {
311     DC.removeFromWorkList(N);
312   }
313
314   virtual void NodeUpdated(SDNode *N) {
315     // Ignore updates.
316   }
317 };
318 }
319
320 //===----------------------------------------------------------------------===//
321 //  TargetLowering::DAGCombinerInfo implementation
322 //===----------------------------------------------------------------------===//
323
324 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
325   ((DAGCombiner*)DC)->AddToWorkList(N);
326 }
327
328 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
329   ((DAGCombiner*)DC)->removeFromWorkList(N);
330 }
331
332 SDValue TargetLowering::DAGCombinerInfo::
333 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
334   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
335 }
336
337 SDValue TargetLowering::DAGCombinerInfo::
338 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
339   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
340 }
341
342
343 SDValue TargetLowering::DAGCombinerInfo::
344 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
345   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
346 }
347
348 void TargetLowering::DAGCombinerInfo::
349 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
350   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
351 }
352
353 //===----------------------------------------------------------------------===//
354 // Helper Functions
355 //===----------------------------------------------------------------------===//
356
357 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
358 /// specified expression for the same cost as the expression itself, or 2 if we
359 /// can compute the negated form more cheaply than the expression itself.
360 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
361                                unsigned Depth = 0) {
362   // No compile time optimizations on this type.
363   if (Op.getValueType() == MVT::ppcf128)
364     return 0;
365
366   // fneg is removable even if it has multiple uses.
367   if (Op.getOpcode() == ISD::FNEG) return 2;
368
369   // Don't allow anything with multiple uses.
370   if (!Op.hasOneUse()) return 0;
371
372   // Don't recurse exponentially.
373   if (Depth > 6) return 0;
374
375   switch (Op.getOpcode()) {
376   default: return false;
377   case ISD::ConstantFP:
378     // Don't invert constant FP values after legalize.  The negated constant
379     // isn't necessarily legal.
380     return LegalOperations ? 0 : 1;
381   case ISD::FADD:
382     // FIXME: determine better conditions for this xform.
383     if (!UnsafeFPMath) return 0;
384
385     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
386     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
387       return V;
388     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
389     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
390   case ISD::FSUB:
391     // We can't turn -(A-B) into B-A when we honor signed zeros.
392     if (!UnsafeFPMath) return 0;
393
394     // fold (fneg (fsub A, B)) -> (fsub B, A)
395     return 1;
396
397   case ISD::FMUL:
398   case ISD::FDIV:
399     if (HonorSignDependentRoundingFPMath()) return 0;
400
401     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
402     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
403       return V;
404
405     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
406
407   case ISD::FP_EXTEND:
408   case ISD::FP_ROUND:
409   case ISD::FSIN:
410     return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
411   }
412 }
413
414 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
415 /// returns the newly negated expression.
416 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
417                                     bool LegalOperations, unsigned Depth = 0) {
418   // fneg is removable even if it has multiple uses.
419   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
420
421   // Don't allow anything with multiple uses.
422   assert(Op.hasOneUse() && "Unknown reuse!");
423
424   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
425   switch (Op.getOpcode()) {
426   default: llvm_unreachable("Unknown code");
427   case ISD::ConstantFP: {
428     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
429     V.changeSign();
430     return DAG.getConstantFP(V, Op.getValueType());
431   }
432   case ISD::FADD:
433     // FIXME: determine better conditions for this xform.
434     assert(UnsafeFPMath);
435
436     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
437     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
438       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
439                          GetNegatedExpression(Op.getOperand(0), DAG,
440                                               LegalOperations, Depth+1),
441                          Op.getOperand(1));
442     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
443     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
444                        GetNegatedExpression(Op.getOperand(1), DAG,
445                                             LegalOperations, Depth+1),
446                        Op.getOperand(0));
447   case ISD::FSUB:
448     // We can't turn -(A-B) into B-A when we honor signed zeros.
449     assert(UnsafeFPMath);
450
451     // fold (fneg (fsub 0, B)) -> B
452     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
453       if (N0CFP->getValueAPF().isZero())
454         return Op.getOperand(1);
455
456     // fold (fneg (fsub A, B)) -> (fsub B, A)
457     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
458                        Op.getOperand(1), Op.getOperand(0));
459
460   case ISD::FMUL:
461   case ISD::FDIV:
462     assert(!HonorSignDependentRoundingFPMath());
463
464     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
465     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
466       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
467                          GetNegatedExpression(Op.getOperand(0), DAG,
468                                               LegalOperations, Depth+1),
469                          Op.getOperand(1));
470
471     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
472     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
473                        Op.getOperand(0),
474                        GetNegatedExpression(Op.getOperand(1), DAG,
475                                             LegalOperations, Depth+1));
476
477   case ISD::FP_EXTEND:
478   case ISD::FSIN:
479     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
480                        GetNegatedExpression(Op.getOperand(0), DAG,
481                                             LegalOperations, Depth+1));
482   case ISD::FP_ROUND:
483       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
484                          GetNegatedExpression(Op.getOperand(0), DAG,
485                                               LegalOperations, Depth+1),
486                          Op.getOperand(1));
487   }
488 }
489
490
491 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
492 // that selects between the values 1 and 0, making it equivalent to a setcc.
493 // Also, set the incoming LHS, RHS, and CC references to the appropriate
494 // nodes based on the type of node we are checking.  This simplifies life a
495 // bit for the callers.
496 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
497                               SDValue &CC) {
498   if (N.getOpcode() == ISD::SETCC) {
499     LHS = N.getOperand(0);
500     RHS = N.getOperand(1);
501     CC  = N.getOperand(2);
502     return true;
503   }
504   if (N.getOpcode() == ISD::SELECT_CC &&
505       N.getOperand(2).getOpcode() == ISD::Constant &&
506       N.getOperand(3).getOpcode() == ISD::Constant &&
507       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
508       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
509     LHS = N.getOperand(0);
510     RHS = N.getOperand(1);
511     CC  = N.getOperand(4);
512     return true;
513   }
514   return false;
515 }
516
517 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
518 // one use.  If this is true, it allows the users to invert the operation for
519 // free when it is profitable to do so.
520 static bool isOneUseSetCC(SDValue N) {
521   SDValue N0, N1, N2;
522   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
523     return true;
524   return false;
525 }
526
527 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
528                                     SDValue N0, SDValue N1) {
529   EVT VT = N0.getValueType();
530   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
531     if (isa<ConstantSDNode>(N1)) {
532       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
533       SDValue OpNode =
534         DAG.FoldConstantArithmetic(Opc, VT,
535                                    cast<ConstantSDNode>(N0.getOperand(1)),
536                                    cast<ConstantSDNode>(N1));
537       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
538     }
539     if (N0.hasOneUse()) {
540       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
541       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
542                                    N0.getOperand(0), N1);
543       AddToWorkList(OpNode.getNode());
544       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
545     }
546   }
547
548   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
549     if (isa<ConstantSDNode>(N0)) {
550       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
551       SDValue OpNode =
552         DAG.FoldConstantArithmetic(Opc, VT,
553                                    cast<ConstantSDNode>(N1.getOperand(1)),
554                                    cast<ConstantSDNode>(N0));
555       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
556     }
557     if (N1.hasOneUse()) {
558       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
559       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
560                                    N1.getOperand(0), N0);
561       AddToWorkList(OpNode.getNode());
562       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
563     }
564   }
565
566   return SDValue();
567 }
568
569 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
570                                bool AddTo) {
571   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
572   ++NodesCombined;
573   DEBUG(dbgs() << "\nReplacing.1 ";
574         N->dump(&DAG);
575         dbgs() << "\nWith: ";
576         To[0].getNode()->dump(&DAG);
577         dbgs() << " and " << NumTo-1 << " other values\n";
578         for (unsigned i = 0, e = NumTo; i != e; ++i)
579           assert((!To[i].getNode() ||
580                   N->getValueType(i) == To[i].getValueType()) &&
581                  "Cannot combine value to value of different type!"));
582   WorkListRemover DeadNodes(*this);
583   DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
584
585   if (AddTo) {
586     // Push the new nodes and any users onto the worklist
587     for (unsigned i = 0, e = NumTo; i != e; ++i) {
588       if (To[i].getNode()) {
589         AddToWorkList(To[i].getNode());
590         AddUsersToWorkList(To[i].getNode());
591       }
592     }
593   }
594
595   // Finally, if the node is now dead, remove it from the graph.  The node
596   // may not be dead if the replacement process recursively simplified to
597   // something else needing this node.
598   if (N->use_empty()) {
599     // Nodes can be reintroduced into the worklist.  Make sure we do not
600     // process a node that has been replaced.
601     removeFromWorkList(N);
602
603     // Finally, since the node is now dead, remove it from the graph.
604     DAG.DeleteNode(N);
605   }
606   return SDValue(N, 0);
607 }
608
609 void DAGCombiner::
610 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
611   // Replace all uses.  If any nodes become isomorphic to other nodes and
612   // are deleted, make sure to remove them from our worklist.
613   WorkListRemover DeadNodes(*this);
614   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
615
616   // Push the new node and any (possibly new) users onto the worklist.
617   AddToWorkList(TLO.New.getNode());
618   AddUsersToWorkList(TLO.New.getNode());
619
620   // Finally, if the node is now dead, remove it from the graph.  The node
621   // may not be dead if the replacement process recursively simplified to
622   // something else needing this node.
623   if (TLO.Old.getNode()->use_empty()) {
624     removeFromWorkList(TLO.Old.getNode());
625
626     // If the operands of this node are only used by the node, they will now
627     // be dead.  Make sure to visit them first to delete dead nodes early.
628     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
629       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
630         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
631
632     DAG.DeleteNode(TLO.Old.getNode());
633   }
634 }
635
636 /// SimplifyDemandedBits - Check the specified integer node value to see if
637 /// it can be simplified or if things it uses can be simplified by bit
638 /// propagation.  If so, return true.
639 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
640   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
641   APInt KnownZero, KnownOne;
642   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
643     return false;
644
645   // Revisit the node.
646   AddToWorkList(Op.getNode());
647
648   // Replace the old value with the new one.
649   ++NodesCombined;
650   DEBUG(dbgs() << "\nReplacing.2 ";
651         TLO.Old.getNode()->dump(&DAG);
652         dbgs() << "\nWith: ";
653         TLO.New.getNode()->dump(&DAG);
654         dbgs() << '\n');
655
656   CommitTargetLoweringOpt(TLO);
657   return true;
658 }
659
660 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
661   DebugLoc dl = Load->getDebugLoc();
662   EVT VT = Load->getValueType(0);
663   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
664
665   DEBUG(dbgs() << "\nReplacing.9 ";
666         Load->dump(&DAG);
667         dbgs() << "\nWith: ";
668         Trunc.getNode()->dump(&DAG);
669         dbgs() << '\n');
670   WorkListRemover DeadNodes(*this);
671   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
672   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
673                                 &DeadNodes);
674   removeFromWorkList(Load);
675   DAG.DeleteNode(Load);
676   AddToWorkList(Trunc.getNode());
677 }
678
679 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
680   Replace = false;
681   DebugLoc dl = Op.getDebugLoc();
682   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
683     EVT MemVT = LD->getMemoryVT();
684     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
685       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
686                                                   : ISD::EXTLOAD)
687       : LD->getExtensionType();
688     Replace = true;
689     return DAG.getExtLoad(ExtType, dl, PVT,
690                           LD->getChain(), LD->getBasePtr(),
691                           LD->getPointerInfo(),
692                           MemVT, LD->isVolatile(),
693                           LD->isNonTemporal(), LD->getAlignment());
694   }
695
696   unsigned Opc = Op.getOpcode();
697   switch (Opc) {
698   default: break;
699   case ISD::AssertSext:
700     return DAG.getNode(ISD::AssertSext, dl, PVT,
701                        SExtPromoteOperand(Op.getOperand(0), PVT),
702                        Op.getOperand(1));
703   case ISD::AssertZext:
704     return DAG.getNode(ISD::AssertZext, dl, PVT,
705                        ZExtPromoteOperand(Op.getOperand(0), PVT),
706                        Op.getOperand(1));
707   case ISD::Constant: {
708     unsigned ExtOpc =
709       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
710     return DAG.getNode(ExtOpc, dl, PVT, Op);
711   }
712   }
713
714   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
715     return SDValue();
716   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
717 }
718
719 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
720   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
721     return SDValue();
722   EVT OldVT = Op.getValueType();
723   DebugLoc dl = Op.getDebugLoc();
724   bool Replace = false;
725   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
726   if (NewOp.getNode() == 0)
727     return SDValue();
728   AddToWorkList(NewOp.getNode());
729
730   if (Replace)
731     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
732   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
733                      DAG.getValueType(OldVT));
734 }
735
736 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
737   EVT OldVT = Op.getValueType();
738   DebugLoc dl = Op.getDebugLoc();
739   bool Replace = false;
740   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
741   if (NewOp.getNode() == 0)
742     return SDValue();
743   AddToWorkList(NewOp.getNode());
744
745   if (Replace)
746     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
747   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
748 }
749
750 /// PromoteIntBinOp - Promote the specified integer binary operation if the
751 /// target indicates it is beneficial. e.g. On x86, it's usually better to
752 /// promote i16 operations to i32 since i16 instructions are longer.
753 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
754   if (!LegalOperations)
755     return SDValue();
756
757   EVT VT = Op.getValueType();
758   if (VT.isVector() || !VT.isInteger())
759     return SDValue();
760
761   // If operation type is 'undesirable', e.g. i16 on x86, consider
762   // promoting it.
763   unsigned Opc = Op.getOpcode();
764   if (TLI.isTypeDesirableForOp(Opc, VT))
765     return SDValue();
766
767   EVT PVT = VT;
768   // Consult target whether it is a good idea to promote this operation and
769   // what's the right type to promote it to.
770   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
771     assert(PVT != VT && "Don't know what type to promote to!");
772
773     bool Replace0 = false;
774     SDValue N0 = Op.getOperand(0);
775     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
776     if (NN0.getNode() == 0)
777       return SDValue();
778
779     bool Replace1 = false;
780     SDValue N1 = Op.getOperand(1);
781     SDValue NN1;
782     if (N0 == N1)
783       NN1 = NN0;
784     else {
785       NN1 = PromoteOperand(N1, PVT, Replace1);
786       if (NN1.getNode() == 0)
787         return SDValue();
788     }
789
790     AddToWorkList(NN0.getNode());
791     if (NN1.getNode())
792       AddToWorkList(NN1.getNode());
793
794     if (Replace0)
795       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
796     if (Replace1)
797       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
798
799     DEBUG(dbgs() << "\nPromoting ";
800           Op.getNode()->dump(&DAG));
801     DebugLoc dl = Op.getDebugLoc();
802     return DAG.getNode(ISD::TRUNCATE, dl, VT,
803                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
804   }
805   return SDValue();
806 }
807
808 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
809 /// target indicates it is beneficial. e.g. On x86, it's usually better to
810 /// promote i16 operations to i32 since i16 instructions are longer.
811 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
812   if (!LegalOperations)
813     return SDValue();
814
815   EVT VT = Op.getValueType();
816   if (VT.isVector() || !VT.isInteger())
817     return SDValue();
818
819   // If operation type is 'undesirable', e.g. i16 on x86, consider
820   // promoting it.
821   unsigned Opc = Op.getOpcode();
822   if (TLI.isTypeDesirableForOp(Opc, VT))
823     return SDValue();
824
825   EVT PVT = VT;
826   // Consult target whether it is a good idea to promote this operation and
827   // what's the right type to promote it to.
828   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
829     assert(PVT != VT && "Don't know what type to promote to!");
830
831     bool Replace = false;
832     SDValue N0 = Op.getOperand(0);
833     if (Opc == ISD::SRA)
834       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
835     else if (Opc == ISD::SRL)
836       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
837     else
838       N0 = PromoteOperand(N0, PVT, Replace);
839     if (N0.getNode() == 0)
840       return SDValue();
841
842     AddToWorkList(N0.getNode());
843     if (Replace)
844       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
845
846     DEBUG(dbgs() << "\nPromoting ";
847           Op.getNode()->dump(&DAG));
848     DebugLoc dl = Op.getDebugLoc();
849     return DAG.getNode(ISD::TRUNCATE, dl, VT,
850                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
851   }
852   return SDValue();
853 }
854
855 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
856   if (!LegalOperations)
857     return SDValue();
858
859   EVT VT = Op.getValueType();
860   if (VT.isVector() || !VT.isInteger())
861     return SDValue();
862
863   // If operation type is 'undesirable', e.g. i16 on x86, consider
864   // promoting it.
865   unsigned Opc = Op.getOpcode();
866   if (TLI.isTypeDesirableForOp(Opc, VT))
867     return SDValue();
868
869   EVT PVT = VT;
870   // Consult target whether it is a good idea to promote this operation and
871   // what's the right type to promote it to.
872   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
873     assert(PVT != VT && "Don't know what type to promote to!");
874     // fold (aext (aext x)) -> (aext x)
875     // fold (aext (zext x)) -> (zext x)
876     // fold (aext (sext x)) -> (sext x)
877     DEBUG(dbgs() << "\nPromoting ";
878           Op.getNode()->dump(&DAG));
879     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
880   }
881   return SDValue();
882 }
883
884 bool DAGCombiner::PromoteLoad(SDValue Op) {
885   if (!LegalOperations)
886     return false;
887
888   EVT VT = Op.getValueType();
889   if (VT.isVector() || !VT.isInteger())
890     return false;
891
892   // If operation type is 'undesirable', e.g. i16 on x86, consider
893   // promoting it.
894   unsigned Opc = Op.getOpcode();
895   if (TLI.isTypeDesirableForOp(Opc, VT))
896     return false;
897
898   EVT PVT = VT;
899   // Consult target whether it is a good idea to promote this operation and
900   // what's the right type to promote it to.
901   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
902     assert(PVT != VT && "Don't know what type to promote to!");
903
904     DebugLoc dl = Op.getDebugLoc();
905     SDNode *N = Op.getNode();
906     LoadSDNode *LD = cast<LoadSDNode>(N);
907     EVT MemVT = LD->getMemoryVT();
908     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
909       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
910                                                   : ISD::EXTLOAD)
911       : LD->getExtensionType();
912     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
913                                    LD->getChain(), LD->getBasePtr(),
914                                    LD->getPointerInfo(),
915                                    MemVT, LD->isVolatile(),
916                                    LD->isNonTemporal(), LD->getAlignment());
917     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
918
919     DEBUG(dbgs() << "\nPromoting ";
920           N->dump(&DAG);
921           dbgs() << "\nTo: ";
922           Result.getNode()->dump(&DAG);
923           dbgs() << '\n');
924     WorkListRemover DeadNodes(*this);
925     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
926     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
927     removeFromWorkList(N);
928     DAG.DeleteNode(N);
929     AddToWorkList(Result.getNode());
930     return true;
931   }
932   return false;
933 }
934
935
936 //===----------------------------------------------------------------------===//
937 //  Main DAG Combiner implementation
938 //===----------------------------------------------------------------------===//
939
940 void DAGCombiner::Run(CombineLevel AtLevel) {
941   // set the instance variables, so that the various visit routines may use it.
942   Level = AtLevel;
943   LegalOperations = Level >= NoIllegalOperations;
944   LegalTypes = Level >= NoIllegalTypes;
945
946   // Add all the dag nodes to the worklist.
947   WorkList.reserve(DAG.allnodes_size());
948   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
949        E = DAG.allnodes_end(); I != E; ++I)
950     WorkList.push_back(I);
951
952   // Create a dummy node (which is not added to allnodes), that adds a reference
953   // to the root node, preventing it from being deleted, and tracking any
954   // changes of the root.
955   HandleSDNode Dummy(DAG.getRoot());
956
957   // The root of the dag may dangle to deleted nodes until the dag combiner is
958   // done.  Set it to null to avoid confusion.
959   DAG.setRoot(SDValue());
960
961   // while the worklist isn't empty, inspect the node on the end of it and
962   // try and combine it.
963   while (!WorkList.empty()) {
964     SDNode *N = WorkList.back();
965     WorkList.pop_back();
966
967     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
968     // N is deleted from the DAG, since they too may now be dead or may have a
969     // reduced number of uses, allowing other xforms.
970     if (N->use_empty() && N != &Dummy) {
971       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
972         AddToWorkList(N->getOperand(i).getNode());
973
974       DAG.DeleteNode(N);
975       continue;
976     }
977
978     SDValue RV = combine(N);
979
980     if (RV.getNode() == 0)
981       continue;
982
983     ++NodesCombined;
984
985     // If we get back the same node we passed in, rather than a new node or
986     // zero, we know that the node must have defined multiple values and
987     // CombineTo was used.  Since CombineTo takes care of the worklist
988     // mechanics for us, we have no work to do in this case.
989     if (RV.getNode() == N)
990       continue;
991
992     assert(N->getOpcode() != ISD::DELETED_NODE &&
993            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
994            "Node was deleted but visit returned new node!");
995
996     DEBUG(dbgs() << "\nReplacing.3 ";
997           N->dump(&DAG);
998           dbgs() << "\nWith: ";
999           RV.getNode()->dump(&DAG);
1000           dbgs() << '\n');
1001     
1002     // Transfer debug value.
1003     DAG.TransferDbgValues(SDValue(N, 0), RV);
1004     WorkListRemover DeadNodes(*this);
1005     if (N->getNumValues() == RV.getNode()->getNumValues())
1006       DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
1007     else {
1008       assert(N->getValueType(0) == RV.getValueType() &&
1009              N->getNumValues() == 1 && "Type mismatch");
1010       SDValue OpV = RV;
1011       DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
1012     }
1013
1014     // Push the new node and any users onto the worklist
1015     AddToWorkList(RV.getNode());
1016     AddUsersToWorkList(RV.getNode());
1017
1018     // Add any uses of the old node to the worklist in case this node is the
1019     // last one that uses them.  They may become dead after this node is
1020     // deleted.
1021     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1022       AddToWorkList(N->getOperand(i).getNode());
1023
1024     // Finally, if the node is now dead, remove it from the graph.  The node
1025     // may not be dead if the replacement process recursively simplified to
1026     // something else needing this node.
1027     if (N->use_empty()) {
1028       // Nodes can be reintroduced into the worklist.  Make sure we do not
1029       // process a node that has been replaced.
1030       removeFromWorkList(N);
1031
1032       // Finally, since the node is now dead, remove it from the graph.
1033       DAG.DeleteNode(N);
1034     }
1035   }
1036
1037   // If the root changed (e.g. it was a dead load, update the root).
1038   DAG.setRoot(Dummy.getValue());
1039 }
1040
1041 SDValue DAGCombiner::visit(SDNode *N) {
1042   switch (N->getOpcode()) {
1043   default: break;
1044   case ISD::TokenFactor:        return visitTokenFactor(N);
1045   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1046   case ISD::ADD:                return visitADD(N);
1047   case ISD::SUB:                return visitSUB(N);
1048   case ISD::ADDC:               return visitADDC(N);
1049   case ISD::ADDE:               return visitADDE(N);
1050   case ISD::MUL:                return visitMUL(N);
1051   case ISD::SDIV:               return visitSDIV(N);
1052   case ISD::UDIV:               return visitUDIV(N);
1053   case ISD::SREM:               return visitSREM(N);
1054   case ISD::UREM:               return visitUREM(N);
1055   case ISD::MULHU:              return visitMULHU(N);
1056   case ISD::MULHS:              return visitMULHS(N);
1057   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1058   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1059   case ISD::SMULO:              return visitSMULO(N);
1060   case ISD::UMULO:              return visitUMULO(N);
1061   case ISD::SDIVREM:            return visitSDIVREM(N);
1062   case ISD::UDIVREM:            return visitUDIVREM(N);
1063   case ISD::AND:                return visitAND(N);
1064   case ISD::OR:                 return visitOR(N);
1065   case ISD::XOR:                return visitXOR(N);
1066   case ISD::SHL:                return visitSHL(N);
1067   case ISD::SRA:                return visitSRA(N);
1068   case ISD::SRL:                return visitSRL(N);
1069   case ISD::CTLZ:               return visitCTLZ(N);
1070   case ISD::CTTZ:               return visitCTTZ(N);
1071   case ISD::CTPOP:              return visitCTPOP(N);
1072   case ISD::SELECT:             return visitSELECT(N);
1073   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1074   case ISD::SETCC:              return visitSETCC(N);
1075   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1076   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1077   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1078   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1079   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1080   case ISD::BITCAST:            return visitBITCAST(N);
1081   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1082   case ISD::FADD:               return visitFADD(N);
1083   case ISD::FSUB:               return visitFSUB(N);
1084   case ISD::FMUL:               return visitFMUL(N);
1085   case ISD::FDIV:               return visitFDIV(N);
1086   case ISD::FREM:               return visitFREM(N);
1087   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1088   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1089   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1090   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1091   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1092   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1093   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1094   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1095   case ISD::FNEG:               return visitFNEG(N);
1096   case ISD::FABS:               return visitFABS(N);
1097   case ISD::BRCOND:             return visitBRCOND(N);
1098   case ISD::BR_CC:              return visitBR_CC(N);
1099   case ISD::LOAD:               return visitLOAD(N);
1100   case ISD::STORE:              return visitSTORE(N);
1101   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1102   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1103   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1104   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1105   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1106   case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
1107   }
1108   return SDValue();
1109 }
1110
1111 SDValue DAGCombiner::combine(SDNode *N) {
1112   SDValue RV = visit(N);
1113
1114   // If nothing happened, try a target-specific DAG combine.
1115   if (RV.getNode() == 0) {
1116     assert(N->getOpcode() != ISD::DELETED_NODE &&
1117            "Node was deleted but visit returned NULL!");
1118
1119     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1120         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1121
1122       // Expose the DAG combiner to the target combiner impls.
1123       TargetLowering::DAGCombinerInfo
1124         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1125
1126       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1127     }
1128   }
1129
1130   // If nothing happened still, try promoting the operation.
1131   if (RV.getNode() == 0) {
1132     switch (N->getOpcode()) {
1133     default: break;
1134     case ISD::ADD:
1135     case ISD::SUB:
1136     case ISD::MUL:
1137     case ISD::AND:
1138     case ISD::OR:
1139     case ISD::XOR:
1140       RV = PromoteIntBinOp(SDValue(N, 0));
1141       break;
1142     case ISD::SHL:
1143     case ISD::SRA:
1144     case ISD::SRL:
1145       RV = PromoteIntShiftOp(SDValue(N, 0));
1146       break;
1147     case ISD::SIGN_EXTEND:
1148     case ISD::ZERO_EXTEND:
1149     case ISD::ANY_EXTEND:
1150       RV = PromoteExtend(SDValue(N, 0));
1151       break;
1152     case ISD::LOAD:
1153       if (PromoteLoad(SDValue(N, 0)))
1154         RV = SDValue(N, 0);
1155       break;
1156     }
1157   }
1158
1159   // If N is a commutative binary node, try commuting it to enable more
1160   // sdisel CSE.
1161   if (RV.getNode() == 0 &&
1162       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1163       N->getNumValues() == 1) {
1164     SDValue N0 = N->getOperand(0);
1165     SDValue N1 = N->getOperand(1);
1166
1167     // Constant operands are canonicalized to RHS.
1168     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1169       SDValue Ops[] = { N1, N0 };
1170       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1171                                             Ops, 2);
1172       if (CSENode)
1173         return SDValue(CSENode, 0);
1174     }
1175   }
1176
1177   return RV;
1178 }
1179
1180 /// getInputChainForNode - Given a node, return its input chain if it has one,
1181 /// otherwise return a null sd operand.
1182 static SDValue getInputChainForNode(SDNode *N) {
1183   if (unsigned NumOps = N->getNumOperands()) {
1184     if (N->getOperand(0).getValueType() == MVT::Other)
1185       return N->getOperand(0);
1186     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1187       return N->getOperand(NumOps-1);
1188     for (unsigned i = 1; i < NumOps-1; ++i)
1189       if (N->getOperand(i).getValueType() == MVT::Other)
1190         return N->getOperand(i);
1191   }
1192   return SDValue();
1193 }
1194
1195 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1196   // If N has two operands, where one has an input chain equal to the other,
1197   // the 'other' chain is redundant.
1198   if (N->getNumOperands() == 2) {
1199     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1200       return N->getOperand(0);
1201     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1202       return N->getOperand(1);
1203   }
1204
1205   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1206   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1207   SmallPtrSet<SDNode*, 16> SeenOps;
1208   bool Changed = false;             // If we should replace this token factor.
1209
1210   // Start out with this token factor.
1211   TFs.push_back(N);
1212
1213   // Iterate through token factors.  The TFs grows when new token factors are
1214   // encountered.
1215   for (unsigned i = 0; i < TFs.size(); ++i) {
1216     SDNode *TF = TFs[i];
1217
1218     // Check each of the operands.
1219     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1220       SDValue Op = TF->getOperand(i);
1221
1222       switch (Op.getOpcode()) {
1223       case ISD::EntryToken:
1224         // Entry tokens don't need to be added to the list. They are
1225         // rededundant.
1226         Changed = true;
1227         break;
1228
1229       case ISD::TokenFactor:
1230         if (Op.hasOneUse() &&
1231             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1232           // Queue up for processing.
1233           TFs.push_back(Op.getNode());
1234           // Clean up in case the token factor is removed.
1235           AddToWorkList(Op.getNode());
1236           Changed = true;
1237           break;
1238         }
1239         // Fall thru
1240
1241       default:
1242         // Only add if it isn't already in the list.
1243         if (SeenOps.insert(Op.getNode()))
1244           Ops.push_back(Op);
1245         else
1246           Changed = true;
1247         break;
1248       }
1249     }
1250   }
1251
1252   SDValue Result;
1253
1254   // If we've change things around then replace token factor.
1255   if (Changed) {
1256     if (Ops.empty()) {
1257       // The entry token is the only possible outcome.
1258       Result = DAG.getEntryNode();
1259     } else {
1260       // New and improved token factor.
1261       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1262                            MVT::Other, &Ops[0], Ops.size());
1263     }
1264
1265     // Don't add users to work list.
1266     return CombineTo(N, Result, false);
1267   }
1268
1269   return Result;
1270 }
1271
1272 /// MERGE_VALUES can always be eliminated.
1273 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1274   WorkListRemover DeadNodes(*this);
1275   // Replacing results may cause a different MERGE_VALUES to suddenly
1276   // be CSE'd with N, and carry its uses with it. Iterate until no
1277   // uses remain, to ensure that the node can be safely deleted.
1278   do {
1279     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1280       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1281                                     &DeadNodes);
1282   } while (!N->use_empty());
1283   removeFromWorkList(N);
1284   DAG.DeleteNode(N);
1285   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1286 }
1287
1288 static
1289 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1290                               SelectionDAG &DAG) {
1291   EVT VT = N0.getValueType();
1292   SDValue N00 = N0.getOperand(0);
1293   SDValue N01 = N0.getOperand(1);
1294   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1295
1296   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1297       isa<ConstantSDNode>(N00.getOperand(1))) {
1298     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1299     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1300                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1301                                  N00.getOperand(0), N01),
1302                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1303                                  N00.getOperand(1), N01));
1304     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1305   }
1306
1307   return SDValue();
1308 }
1309
1310 /// isCarryMaterialization - Returns true if V is an ADDE node that is known to
1311 /// return 0 or 1 depending on the carry flag.
1312 static bool isCarryMaterialization(SDValue V) {
1313   if (V.getOpcode() != ISD::ADDE)
1314     return false;
1315
1316   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(0));
1317   return C && C->isNullValue() && V.getOperand(0) == V.getOperand(1);
1318 }
1319
1320 SDValue DAGCombiner::visitADD(SDNode *N) {
1321   SDValue N0 = N->getOperand(0);
1322   SDValue N1 = N->getOperand(1);
1323   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1324   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1325   EVT VT = N0.getValueType();
1326
1327   // fold vector ops
1328   if (VT.isVector()) {
1329     SDValue FoldedVOp = SimplifyVBinOp(N);
1330     if (FoldedVOp.getNode()) return FoldedVOp;
1331   }
1332
1333   // fold (add x, undef) -> undef
1334   if (N0.getOpcode() == ISD::UNDEF)
1335     return N0;
1336   if (N1.getOpcode() == ISD::UNDEF)
1337     return N1;
1338   // fold (add c1, c2) -> c1+c2
1339   if (N0C && N1C)
1340     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1341   // canonicalize constant to RHS
1342   if (N0C && !N1C)
1343     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1344   // fold (add x, 0) -> x
1345   if (N1C && N1C->isNullValue())
1346     return N0;
1347   // fold (add Sym, c) -> Sym+c
1348   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1349     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1350         GA->getOpcode() == ISD::GlobalAddress)
1351       return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1352                                   GA->getOffset() +
1353                                     (uint64_t)N1C->getSExtValue());
1354   // fold ((c1-A)+c2) -> (c1+c2)-A
1355   if (N1C && N0.getOpcode() == ISD::SUB)
1356     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1357       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1358                          DAG.getConstant(N1C->getAPIntValue()+
1359                                          N0C->getAPIntValue(), VT),
1360                          N0.getOperand(1));
1361   // reassociate add
1362   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1363   if (RADD.getNode() != 0)
1364     return RADD;
1365   // fold ((0-A) + B) -> B-A
1366   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1367       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1368     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1369   // fold (A + (0-B)) -> A-B
1370   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1371       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1372     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1373   // fold (A+(B-A)) -> B
1374   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1375     return N1.getOperand(0);
1376   // fold ((B-A)+A) -> B
1377   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1378     return N0.getOperand(0);
1379   // fold (A+(B-(A+C))) to (B-C)
1380   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1381       N0 == N1.getOperand(1).getOperand(0))
1382     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1383                        N1.getOperand(1).getOperand(1));
1384   // fold (A+(B-(C+A))) to (B-C)
1385   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1386       N0 == N1.getOperand(1).getOperand(1))
1387     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1388                        N1.getOperand(1).getOperand(0));
1389   // fold (A+((B-A)+or-C)) to (B+or-C)
1390   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1391       N1.getOperand(0).getOpcode() == ISD::SUB &&
1392       N0 == N1.getOperand(0).getOperand(1))
1393     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1394                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1395
1396   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1397   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1398     SDValue N00 = N0.getOperand(0);
1399     SDValue N01 = N0.getOperand(1);
1400     SDValue N10 = N1.getOperand(0);
1401     SDValue N11 = N1.getOperand(1);
1402
1403     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1404       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1405                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1406                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1407   }
1408
1409   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1410     return SDValue(N, 0);
1411
1412   // fold (a+b) -> (a|b) iff a and b share no bits.
1413   if (VT.isInteger() && !VT.isVector()) {
1414     APInt LHSZero, LHSOne;
1415     APInt RHSZero, RHSOne;
1416     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1417     DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1418
1419     if (LHSZero.getBoolValue()) {
1420       DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1421
1422       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1423       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1424       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1425           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1426         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1427     }
1428   }
1429
1430   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1431   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1432     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1433     if (Result.getNode()) return Result;
1434   }
1435   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1436     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1437     if (Result.getNode()) return Result;
1438   }
1439
1440   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1441   if (N1.getOpcode() == ISD::SHL &&
1442       N1.getOperand(0).getOpcode() == ISD::SUB)
1443     if (ConstantSDNode *C =
1444           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1445       if (C->getAPIntValue() == 0)
1446         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1447                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1448                                        N1.getOperand(0).getOperand(1),
1449                                        N1.getOperand(1)));
1450   if (N0.getOpcode() == ISD::SHL &&
1451       N0.getOperand(0).getOpcode() == ISD::SUB)
1452     if (ConstantSDNode *C =
1453           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1454       if (C->getAPIntValue() == 0)
1455         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1456                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1457                                        N0.getOperand(0).getOperand(1),
1458                                        N0.getOperand(1)));
1459
1460   if (N1.getOpcode() == ISD::AND) {
1461     SDValue AndOp0 = N1.getOperand(0);
1462     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1463     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1464     unsigned DestBits = VT.getScalarType().getSizeInBits();
1465
1466     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1467     // and similar xforms where the inner op is either ~0 or 0.
1468     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1469       DebugLoc DL = N->getDebugLoc();
1470       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1471     }
1472   }
1473
1474   // add (sext i1), X -> sub X, (zext i1)
1475   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1476       N0.getOperand(0).getValueType() == MVT::i1 &&
1477       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1478     DebugLoc DL = N->getDebugLoc();
1479     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1480     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1481   }
1482
1483   // add (adde 0, 0, glue), X -> adde X, 0, glue
1484   if (N0->hasOneUse() && isCarryMaterialization(N0))
1485     return DAG.getNode(ISD::ADDE, N->getDebugLoc(),
1486                        DAG.getVTList(VT, MVT::Glue), N1, N0.getOperand(0),
1487                        N0.getOperand(2));
1488
1489   // add X, (adde 0, 0, glue) -> adde X, 0, glue
1490   if (N1->hasOneUse() && isCarryMaterialization(N1))
1491     return DAG.getNode(ISD::ADDE, N->getDebugLoc(),
1492                        DAG.getVTList(VT, MVT::Glue), N0, N1.getOperand(0),
1493                        N1.getOperand(2));
1494
1495   return SDValue();
1496 }
1497
1498 SDValue DAGCombiner::visitADDC(SDNode *N) {
1499   SDValue N0 = N->getOperand(0);
1500   SDValue N1 = N->getOperand(1);
1501   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1502   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1503   EVT VT = N0.getValueType();
1504
1505   // If the flag result is dead, turn this into an ADD.
1506   if (N->hasNUsesOfValue(0, 1))
1507     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1508                      DAG.getNode(ISD::CARRY_FALSE,
1509                                  N->getDebugLoc(), MVT::Glue));
1510
1511   // canonicalize constant to RHS.
1512   if (N0C && !N1C)
1513     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1514
1515   // fold (addc x, 0) -> x + no carry out
1516   if (N1C && N1C->isNullValue())
1517     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1518                                         N->getDebugLoc(), MVT::Glue));
1519
1520   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1521   APInt LHSZero, LHSOne;
1522   APInt RHSZero, RHSOne;
1523   APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1524   DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1525
1526   if (LHSZero.getBoolValue()) {
1527     DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1528
1529     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1530     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1531     if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1532         (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1533       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1534                        DAG.getNode(ISD::CARRY_FALSE,
1535                                    N->getDebugLoc(), MVT::Glue));
1536   }
1537
1538   // addc (adde 0, 0, glue), X -> adde X, 0, glue
1539   if (N0->hasOneUse() && isCarryMaterialization(N0))
1540     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), N1,
1541                        DAG.getConstant(0, VT), N0.getOperand(2));
1542
1543   // addc X, (adde 0, 0, glue) -> adde X, 0, glue
1544   if (N1->hasOneUse() && isCarryMaterialization(N1))
1545     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), N0,
1546                        DAG.getConstant(0, VT), N1.getOperand(2));
1547
1548   return SDValue();
1549 }
1550
1551 SDValue DAGCombiner::visitADDE(SDNode *N) {
1552   SDValue N0 = N->getOperand(0);
1553   SDValue N1 = N->getOperand(1);
1554   SDValue CarryIn = N->getOperand(2);
1555   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1556   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1557
1558   // If both operands are null we know that carry out will always be false.
1559   if (N0C && N0C->isNullValue() && N0 == N1)
1560     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), DAG.getNode(ISD::CARRY_FALSE,
1561                                                              N->getDebugLoc(),
1562                                                              MVT::Glue));
1563
1564   // canonicalize constant to RHS
1565   if (N0C && !N1C)
1566     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1567                        N1, N0, CarryIn);
1568
1569   // fold (adde x, y, false) -> (addc x, y)
1570   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1571     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1572
1573   return SDValue();
1574 }
1575
1576 // Since it may not be valid to emit a fold to zero for vector initializers
1577 // check if we can before folding.
1578 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1579                              SelectionDAG &DAG, bool LegalOperations) {
1580   if (!VT.isVector()) {
1581     return DAG.getConstant(0, VT);
1582   }
1583   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1584     // Produce a vector of zeros.
1585     SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1586     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1587     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1588       &Ops[0], Ops.size());
1589   }
1590   return SDValue();
1591 }
1592
1593 SDValue DAGCombiner::visitSUB(SDNode *N) {
1594   SDValue N0 = N->getOperand(0);
1595   SDValue N1 = N->getOperand(1);
1596   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1597   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1598   EVT VT = N0.getValueType();
1599
1600   // fold vector ops
1601   if (VT.isVector()) {
1602     SDValue FoldedVOp = SimplifyVBinOp(N);
1603     if (FoldedVOp.getNode()) return FoldedVOp;
1604   }
1605
1606   // fold (sub x, x) -> 0
1607   // FIXME: Refactor this and xor and other similar operations together.
1608   if (N0 == N1)
1609     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1610   // fold (sub c1, c2) -> c1-c2
1611   if (N0C && N1C)
1612     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1613   // fold (sub x, c) -> (add x, -c)
1614   if (N1C)
1615     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1616                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1617   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1618   if (N0C && N0C->isAllOnesValue())
1619     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1620   // fold A-(A-B) -> B
1621   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1622     return N1.getOperand(1);
1623   // fold (A+B)-A -> B
1624   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1625     return N0.getOperand(1);
1626   // fold (A+B)-B -> A
1627   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1628     return N0.getOperand(0);
1629   // fold ((A+(B+or-C))-B) -> A+or-C
1630   if (N0.getOpcode() == ISD::ADD &&
1631       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1632        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1633       N0.getOperand(1).getOperand(0) == N1)
1634     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1635                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1636   // fold ((A+(C+B))-B) -> A+C
1637   if (N0.getOpcode() == ISD::ADD &&
1638       N0.getOperand(1).getOpcode() == ISD::ADD &&
1639       N0.getOperand(1).getOperand(1) == N1)
1640     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1641                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1642   // fold ((A-(B-C))-C) -> A-B
1643   if (N0.getOpcode() == ISD::SUB &&
1644       N0.getOperand(1).getOpcode() == ISD::SUB &&
1645       N0.getOperand(1).getOperand(1) == N1)
1646     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1647                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1648
1649   // If either operand of a sub is undef, the result is undef
1650   if (N0.getOpcode() == ISD::UNDEF)
1651     return N0;
1652   if (N1.getOpcode() == ISD::UNDEF)
1653     return N1;
1654
1655   // If the relocation model supports it, consider symbol offsets.
1656   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1657     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1658       // fold (sub Sym, c) -> Sym-c
1659       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1660         return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1661                                     GA->getOffset() -
1662                                       (uint64_t)N1C->getSExtValue());
1663       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1664       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1665         if (GA->getGlobal() == GB->getGlobal())
1666           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1667                                  VT);
1668     }
1669
1670   return SDValue();
1671 }
1672
1673 SDValue DAGCombiner::visitMUL(SDNode *N) {
1674   SDValue N0 = N->getOperand(0);
1675   SDValue N1 = N->getOperand(1);
1676   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1677   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1678   EVT VT = N0.getValueType();
1679
1680   // fold vector ops
1681   if (VT.isVector()) {
1682     SDValue FoldedVOp = SimplifyVBinOp(N);
1683     if (FoldedVOp.getNode()) return FoldedVOp;
1684   }
1685
1686   // fold (mul x, undef) -> 0
1687   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1688     return DAG.getConstant(0, VT);
1689   // fold (mul c1, c2) -> c1*c2
1690   if (N0C && N1C)
1691     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1692   // canonicalize constant to RHS
1693   if (N0C && !N1C)
1694     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1695   // fold (mul x, 0) -> 0
1696   if (N1C && N1C->isNullValue())
1697     return N1;
1698   // fold (mul x, -1) -> 0-x
1699   if (N1C && N1C->isAllOnesValue())
1700     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1701                        DAG.getConstant(0, VT), N0);
1702   // fold (mul x, (1 << c)) -> x << c
1703   if (N1C && N1C->getAPIntValue().isPowerOf2())
1704     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1705                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1706                                        getShiftAmountTy(N0.getValueType())));
1707   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1708   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1709     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1710     // FIXME: If the input is something that is easily negated (e.g. a
1711     // single-use add), we should put the negate there.
1712     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1713                        DAG.getConstant(0, VT),
1714                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1715                             DAG.getConstant(Log2Val,
1716                                       getShiftAmountTy(N0.getValueType()))));
1717   }
1718   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1719   if (N1C && N0.getOpcode() == ISD::SHL &&
1720       isa<ConstantSDNode>(N0.getOperand(1))) {
1721     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1722                              N1, N0.getOperand(1));
1723     AddToWorkList(C3.getNode());
1724     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1725                        N0.getOperand(0), C3);
1726   }
1727
1728   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1729   // use.
1730   {
1731     SDValue Sh(0,0), Y(0,0);
1732     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1733     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1734         N0.getNode()->hasOneUse()) {
1735       Sh = N0; Y = N1;
1736     } else if (N1.getOpcode() == ISD::SHL &&
1737                isa<ConstantSDNode>(N1.getOperand(1)) &&
1738                N1.getNode()->hasOneUse()) {
1739       Sh = N1; Y = N0;
1740     }
1741
1742     if (Sh.getNode()) {
1743       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1744                                 Sh.getOperand(0), Y);
1745       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1746                          Mul, Sh.getOperand(1));
1747     }
1748   }
1749
1750   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1751   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1752       isa<ConstantSDNode>(N0.getOperand(1)))
1753     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1754                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1755                                    N0.getOperand(0), N1),
1756                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1757                                    N0.getOperand(1), N1));
1758
1759   // reassociate mul
1760   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1761   if (RMUL.getNode() != 0)
1762     return RMUL;
1763
1764   return SDValue();
1765 }
1766
1767 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1768   SDValue N0 = N->getOperand(0);
1769   SDValue N1 = N->getOperand(1);
1770   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1771   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1772   EVT VT = N->getValueType(0);
1773
1774   // fold vector ops
1775   if (VT.isVector()) {
1776     SDValue FoldedVOp = SimplifyVBinOp(N);
1777     if (FoldedVOp.getNode()) return FoldedVOp;
1778   }
1779
1780   // fold (sdiv c1, c2) -> c1/c2
1781   if (N0C && N1C && !N1C->isNullValue())
1782     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1783   // fold (sdiv X, 1) -> X
1784   if (N1C && N1C->getSExtValue() == 1LL)
1785     return N0;
1786   // fold (sdiv X, -1) -> 0-X
1787   if (N1C && N1C->isAllOnesValue())
1788     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1789                        DAG.getConstant(0, VT), N0);
1790   // If we know the sign bits of both operands are zero, strength reduce to a
1791   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1792   if (!VT.isVector()) {
1793     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1794       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1795                          N0, N1);
1796   }
1797   // fold (sdiv X, pow2) -> simple ops after legalize
1798   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1799       (isPowerOf2_64(N1C->getSExtValue()) ||
1800        isPowerOf2_64(-N1C->getSExtValue()))) {
1801     // If dividing by powers of two is cheap, then don't perform the following
1802     // fold.
1803     if (TLI.isPow2DivCheap())
1804       return SDValue();
1805
1806     int64_t pow2 = N1C->getSExtValue();
1807     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1808     unsigned lg2 = Log2_64(abs2);
1809
1810     // Splat the sign bit into the register
1811     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1812                               DAG.getConstant(VT.getSizeInBits()-1,
1813                                        getShiftAmountTy(N0.getValueType())));
1814     AddToWorkList(SGN.getNode());
1815
1816     // Add (N0 < 0) ? abs2 - 1 : 0;
1817     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1818                               DAG.getConstant(VT.getSizeInBits() - lg2,
1819                                        getShiftAmountTy(SGN.getValueType())));
1820     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1821     AddToWorkList(SRL.getNode());
1822     AddToWorkList(ADD.getNode());    // Divide by pow2
1823     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1824                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1825
1826     // If we're dividing by a positive value, we're done.  Otherwise, we must
1827     // negate the result.
1828     if (pow2 > 0)
1829       return SRA;
1830
1831     AddToWorkList(SRA.getNode());
1832     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1833                        DAG.getConstant(0, VT), SRA);
1834   }
1835
1836   // if integer divide is expensive and we satisfy the requirements, emit an
1837   // alternate sequence.
1838   if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1839       !TLI.isIntDivCheap()) {
1840     SDValue Op = BuildSDIV(N);
1841     if (Op.getNode()) return Op;
1842   }
1843
1844   // undef / X -> 0
1845   if (N0.getOpcode() == ISD::UNDEF)
1846     return DAG.getConstant(0, VT);
1847   // X / undef -> undef
1848   if (N1.getOpcode() == ISD::UNDEF)
1849     return N1;
1850
1851   return SDValue();
1852 }
1853
1854 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1855   SDValue N0 = N->getOperand(0);
1856   SDValue N1 = N->getOperand(1);
1857   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1858   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1859   EVT VT = N->getValueType(0);
1860
1861   // fold vector ops
1862   if (VT.isVector()) {
1863     SDValue FoldedVOp = SimplifyVBinOp(N);
1864     if (FoldedVOp.getNode()) return FoldedVOp;
1865   }
1866
1867   // fold (udiv c1, c2) -> c1/c2
1868   if (N0C && N1C && !N1C->isNullValue())
1869     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1870   // fold (udiv x, (1 << c)) -> x >>u c
1871   if (N1C && N1C->getAPIntValue().isPowerOf2())
1872     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1873                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1874                                        getShiftAmountTy(N0.getValueType())));
1875   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1876   if (N1.getOpcode() == ISD::SHL) {
1877     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1878       if (SHC->getAPIntValue().isPowerOf2()) {
1879         EVT ADDVT = N1.getOperand(1).getValueType();
1880         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1881                                   N1.getOperand(1),
1882                                   DAG.getConstant(SHC->getAPIntValue()
1883                                                                   .logBase2(),
1884                                                   ADDVT));
1885         AddToWorkList(Add.getNode());
1886         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1887       }
1888     }
1889   }
1890   // fold (udiv x, c) -> alternate
1891   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1892     SDValue Op = BuildUDIV(N);
1893     if (Op.getNode()) return Op;
1894   }
1895
1896   // undef / X -> 0
1897   if (N0.getOpcode() == ISD::UNDEF)
1898     return DAG.getConstant(0, VT);
1899   // X / undef -> undef
1900   if (N1.getOpcode() == ISD::UNDEF)
1901     return N1;
1902
1903   return SDValue();
1904 }
1905
1906 SDValue DAGCombiner::visitSREM(SDNode *N) {
1907   SDValue N0 = N->getOperand(0);
1908   SDValue N1 = N->getOperand(1);
1909   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1910   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1911   EVT VT = N->getValueType(0);
1912
1913   // fold (srem c1, c2) -> c1%c2
1914   if (N0C && N1C && !N1C->isNullValue())
1915     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1916   // If we know the sign bits of both operands are zero, strength reduce to a
1917   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1918   if (!VT.isVector()) {
1919     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1920       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1921   }
1922
1923   // If X/C can be simplified by the division-by-constant logic, lower
1924   // X%C to the equivalent of X-X/C*C.
1925   if (N1C && !N1C->isNullValue()) {
1926     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1927     AddToWorkList(Div.getNode());
1928     SDValue OptimizedDiv = combine(Div.getNode());
1929     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1930       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1931                                 OptimizedDiv, N1);
1932       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1933       AddToWorkList(Mul.getNode());
1934       return Sub;
1935     }
1936   }
1937
1938   // undef % X -> 0
1939   if (N0.getOpcode() == ISD::UNDEF)
1940     return DAG.getConstant(0, VT);
1941   // X % undef -> undef
1942   if (N1.getOpcode() == ISD::UNDEF)
1943     return N1;
1944
1945   return SDValue();
1946 }
1947
1948 SDValue DAGCombiner::visitUREM(SDNode *N) {
1949   SDValue N0 = N->getOperand(0);
1950   SDValue N1 = N->getOperand(1);
1951   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1952   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1953   EVT VT = N->getValueType(0);
1954
1955   // fold (urem c1, c2) -> c1%c2
1956   if (N0C && N1C && !N1C->isNullValue())
1957     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1958   // fold (urem x, pow2) -> (and x, pow2-1)
1959   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1960     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1961                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
1962   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1963   if (N1.getOpcode() == ISD::SHL) {
1964     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1965       if (SHC->getAPIntValue().isPowerOf2()) {
1966         SDValue Add =
1967           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1968                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1969                                  VT));
1970         AddToWorkList(Add.getNode());
1971         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1972       }
1973     }
1974   }
1975
1976   // If X/C can be simplified by the division-by-constant logic, lower
1977   // X%C to the equivalent of X-X/C*C.
1978   if (N1C && !N1C->isNullValue()) {
1979     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1980     AddToWorkList(Div.getNode());
1981     SDValue OptimizedDiv = combine(Div.getNode());
1982     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1983       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1984                                 OptimizedDiv, N1);
1985       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1986       AddToWorkList(Mul.getNode());
1987       return Sub;
1988     }
1989   }
1990
1991   // undef % X -> 0
1992   if (N0.getOpcode() == ISD::UNDEF)
1993     return DAG.getConstant(0, VT);
1994   // X % undef -> undef
1995   if (N1.getOpcode() == ISD::UNDEF)
1996     return N1;
1997
1998   return SDValue();
1999 }
2000
2001 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2002   SDValue N0 = N->getOperand(0);
2003   SDValue N1 = N->getOperand(1);
2004   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2005   EVT VT = N->getValueType(0);
2006   DebugLoc DL = N->getDebugLoc();
2007
2008   // fold (mulhs x, 0) -> 0
2009   if (N1C && N1C->isNullValue())
2010     return N1;
2011   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2012   if (N1C && N1C->getAPIntValue() == 1)
2013     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2014                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2015                                        getShiftAmountTy(N0.getValueType())));
2016   // fold (mulhs x, undef) -> 0
2017   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2018     return DAG.getConstant(0, VT);
2019
2020   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2021   // plus a shift.
2022   if (VT.isSimple() && !VT.isVector()) {
2023     MVT Simple = VT.getSimpleVT();
2024     unsigned SimpleSize = Simple.getSizeInBits();
2025     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2026     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2027       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2028       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2029       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2030       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2031             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2032       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2033     }
2034   }
2035
2036   return SDValue();
2037 }
2038
2039 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2040   SDValue N0 = N->getOperand(0);
2041   SDValue N1 = N->getOperand(1);
2042   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2043   EVT VT = N->getValueType(0);
2044   DebugLoc DL = N->getDebugLoc();
2045
2046   // fold (mulhu x, 0) -> 0
2047   if (N1C && N1C->isNullValue())
2048     return N1;
2049   // fold (mulhu x, 1) -> 0
2050   if (N1C && N1C->getAPIntValue() == 1)
2051     return DAG.getConstant(0, N0.getValueType());
2052   // fold (mulhu x, undef) -> 0
2053   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2054     return DAG.getConstant(0, VT);
2055
2056   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2057   // plus a shift.
2058   if (VT.isSimple() && !VT.isVector()) {
2059     MVT Simple = VT.getSimpleVT();
2060     unsigned SimpleSize = Simple.getSizeInBits();
2061     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2062     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2063       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2064       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2065       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2066       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2067             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2068       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2069     }
2070   }
2071
2072   return SDValue();
2073 }
2074
2075 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2076 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2077 /// that are being performed. Return true if a simplification was made.
2078 ///
2079 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2080                                                 unsigned HiOp) {
2081   // If the high half is not needed, just compute the low half.
2082   bool HiExists = N->hasAnyUseOfValue(1);
2083   if (!HiExists &&
2084       (!LegalOperations ||
2085        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2086     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2087                               N->op_begin(), N->getNumOperands());
2088     return CombineTo(N, Res, Res);
2089   }
2090
2091   // If the low half is not needed, just compute the high half.
2092   bool LoExists = N->hasAnyUseOfValue(0);
2093   if (!LoExists &&
2094       (!LegalOperations ||
2095        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2096     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2097                               N->op_begin(), N->getNumOperands());
2098     return CombineTo(N, Res, Res);
2099   }
2100
2101   // If both halves are used, return as it is.
2102   if (LoExists && HiExists)
2103     return SDValue();
2104
2105   // If the two computed results can be simplified separately, separate them.
2106   if (LoExists) {
2107     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2108                              N->op_begin(), N->getNumOperands());
2109     AddToWorkList(Lo.getNode());
2110     SDValue LoOpt = combine(Lo.getNode());
2111     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2112         (!LegalOperations ||
2113          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2114       return CombineTo(N, LoOpt, LoOpt);
2115   }
2116
2117   if (HiExists) {
2118     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2119                              N->op_begin(), N->getNumOperands());
2120     AddToWorkList(Hi.getNode());
2121     SDValue HiOpt = combine(Hi.getNode());
2122     if (HiOpt.getNode() && HiOpt != Hi &&
2123         (!LegalOperations ||
2124          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2125       return CombineTo(N, HiOpt, HiOpt);
2126   }
2127
2128   return SDValue();
2129 }
2130
2131 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2132   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2133   if (Res.getNode()) return Res;
2134
2135   EVT VT = N->getValueType(0);
2136   DebugLoc DL = N->getDebugLoc();
2137
2138   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2139   // plus a shift.
2140   if (VT.isSimple() && !VT.isVector()) {
2141     MVT Simple = VT.getSimpleVT();
2142     unsigned SimpleSize = Simple.getSizeInBits();
2143     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2144     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2145       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2146       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2147       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2148       // Compute the high part as N1.
2149       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2150             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2151       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2152       // Compute the low part as N0.
2153       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2154       return CombineTo(N, Lo, Hi);
2155     }
2156   }
2157
2158   return SDValue();
2159 }
2160
2161 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2162   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2163   if (Res.getNode()) return Res;
2164
2165   EVT VT = N->getValueType(0);
2166   DebugLoc DL = N->getDebugLoc();
2167
2168   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2169   // plus a shift.
2170   if (VT.isSimple() && !VT.isVector()) {
2171     MVT Simple = VT.getSimpleVT();
2172     unsigned SimpleSize = Simple.getSizeInBits();
2173     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2174     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2175       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2176       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2177       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2178       // Compute the high part as N1.
2179       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2180             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2181       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2182       // Compute the low part as N0.
2183       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2184       return CombineTo(N, Lo, Hi);
2185     }
2186   }
2187
2188   return SDValue();
2189 }
2190
2191 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2192   // (smulo x, 2) -> (saddo x, x)
2193   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2194     if (C2->getAPIntValue() == 2)
2195       return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2196                          N->getOperand(0), N->getOperand(0));
2197
2198   return SDValue();
2199 }
2200
2201 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2202   // (umulo x, 2) -> (uaddo x, x)
2203   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2204     if (C2->getAPIntValue() == 2)
2205       return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2206                          N->getOperand(0), N->getOperand(0));
2207
2208   return SDValue();
2209 }
2210
2211 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2212   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2213   if (Res.getNode()) return Res;
2214
2215   return SDValue();
2216 }
2217
2218 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2219   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2220   if (Res.getNode()) return Res;
2221
2222   return SDValue();
2223 }
2224
2225 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2226 /// two operands of the same opcode, try to simplify it.
2227 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2228   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2229   EVT VT = N0.getValueType();
2230   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2231
2232   // Bail early if none of these transforms apply.
2233   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2234
2235   // For each of OP in AND/OR/XOR:
2236   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2237   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2238   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2239   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2240   //
2241   // do not sink logical op inside of a vector extend, since it may combine
2242   // into a vsetcc.
2243   EVT Op0VT = N0.getOperand(0).getValueType();
2244   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2245        N0.getOpcode() == ISD::SIGN_EXTEND ||
2246        // Avoid infinite looping with PromoteIntBinOp.
2247        (N0.getOpcode() == ISD::ANY_EXTEND &&
2248         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2249        (N0.getOpcode() == ISD::TRUNCATE &&
2250         (!TLI.isZExtFree(VT, Op0VT) ||
2251          !TLI.isTruncateFree(Op0VT, VT)) &&
2252         TLI.isTypeLegal(Op0VT))) &&
2253       !VT.isVector() &&
2254       Op0VT == N1.getOperand(0).getValueType() &&
2255       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2256     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2257                                  N0.getOperand(0).getValueType(),
2258                                  N0.getOperand(0), N1.getOperand(0));
2259     AddToWorkList(ORNode.getNode());
2260     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2261   }
2262
2263   // For each of OP in SHL/SRL/SRA/AND...
2264   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2265   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2266   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2267   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2268        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2269       N0.getOperand(1) == N1.getOperand(1)) {
2270     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2271                                  N0.getOperand(0).getValueType(),
2272                                  N0.getOperand(0), N1.getOperand(0));
2273     AddToWorkList(ORNode.getNode());
2274     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2275                        ORNode, N0.getOperand(1));
2276   }
2277
2278   return SDValue();
2279 }
2280
2281 SDValue DAGCombiner::visitAND(SDNode *N) {
2282   SDValue N0 = N->getOperand(0);
2283   SDValue N1 = N->getOperand(1);
2284   SDValue LL, LR, RL, RR, CC0, CC1;
2285   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2286   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2287   EVT VT = N1.getValueType();
2288   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2289
2290   // fold vector ops
2291   if (VT.isVector()) {
2292     SDValue FoldedVOp = SimplifyVBinOp(N);
2293     if (FoldedVOp.getNode()) return FoldedVOp;
2294   }
2295
2296   // fold (and x, undef) -> 0
2297   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2298     return DAG.getConstant(0, VT);
2299   // fold (and c1, c2) -> c1&c2
2300   if (N0C && N1C)
2301     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2302   // canonicalize constant to RHS
2303   if (N0C && !N1C)
2304     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2305   // fold (and x, -1) -> x
2306   if (N1C && N1C->isAllOnesValue())
2307     return N0;
2308   // if (and x, c) is known to be zero, return 0
2309   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2310                                    APInt::getAllOnesValue(BitWidth)))
2311     return DAG.getConstant(0, VT);
2312   // reassociate and
2313   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2314   if (RAND.getNode() != 0)
2315     return RAND;
2316   // fold (and (or x, C), D) -> D if (C & D) == D
2317   if (N1C && N0.getOpcode() == ISD::OR)
2318     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2319       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2320         return N1;
2321   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2322   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2323     SDValue N0Op0 = N0.getOperand(0);
2324     APInt Mask = ~N1C->getAPIntValue();
2325     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2326     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2327       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2328                                  N0.getValueType(), N0Op0);
2329
2330       // Replace uses of the AND with uses of the Zero extend node.
2331       CombineTo(N, Zext);
2332
2333       // We actually want to replace all uses of the any_extend with the
2334       // zero_extend, to avoid duplicating things.  This will later cause this
2335       // AND to be folded.
2336       CombineTo(N0.getNode(), Zext);
2337       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2338     }
2339   }
2340   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2341   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2342     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2343     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2344
2345     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2346         LL.getValueType().isInteger()) {
2347       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2348       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2349         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2350                                      LR.getValueType(), LL, RL);
2351         AddToWorkList(ORNode.getNode());
2352         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2353       }
2354       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2355       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2356         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2357                                       LR.getValueType(), LL, RL);
2358         AddToWorkList(ANDNode.getNode());
2359         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2360       }
2361       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2362       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2363         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2364                                      LR.getValueType(), LL, RL);
2365         AddToWorkList(ORNode.getNode());
2366         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2367       }
2368     }
2369     // canonicalize equivalent to ll == rl
2370     if (LL == RR && LR == RL) {
2371       Op1 = ISD::getSetCCSwappedOperands(Op1);
2372       std::swap(RL, RR);
2373     }
2374     if (LL == RL && LR == RR) {
2375       bool isInteger = LL.getValueType().isInteger();
2376       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2377       if (Result != ISD::SETCC_INVALID &&
2378           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2379         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2380                             LL, LR, Result);
2381     }
2382   }
2383
2384   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2385   if (N0.getOpcode() == N1.getOpcode()) {
2386     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2387     if (Tmp.getNode()) return Tmp;
2388   }
2389
2390   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2391   // fold (and (sra)) -> (and (srl)) when possible.
2392   if (!VT.isVector() &&
2393       SimplifyDemandedBits(SDValue(N, 0)))
2394     return SDValue(N, 0);
2395
2396   // fold (zext_inreg (extload x)) -> (zextload x)
2397   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2398     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2399     EVT MemVT = LN0->getMemoryVT();
2400     // If we zero all the possible extended bits, then we can turn this into
2401     // a zextload if we are running before legalize or the operation is legal.
2402     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2403     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2404                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2405         ((!LegalOperations && !LN0->isVolatile()) ||
2406          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2407       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2408                                        LN0->getChain(), LN0->getBasePtr(),
2409                                        LN0->getPointerInfo(), MemVT,
2410                                        LN0->isVolatile(), LN0->isNonTemporal(),
2411                                        LN0->getAlignment());
2412       AddToWorkList(N);
2413       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2414       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2415     }
2416   }
2417   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2418   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2419       N0.hasOneUse()) {
2420     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2421     EVT MemVT = LN0->getMemoryVT();
2422     // If we zero all the possible extended bits, then we can turn this into
2423     // a zextload if we are running before legalize or the operation is legal.
2424     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2425     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2426                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2427         ((!LegalOperations && !LN0->isVolatile()) ||
2428          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2429       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2430                                        LN0->getChain(),
2431                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2432                                        MemVT,
2433                                        LN0->isVolatile(), LN0->isNonTemporal(),
2434                                        LN0->getAlignment());
2435       AddToWorkList(N);
2436       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2437       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2438     }
2439   }
2440
2441   // fold (and (load x), 255) -> (zextload x, i8)
2442   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2443   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2444   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2445               (N0.getOpcode() == ISD::ANY_EXTEND &&
2446                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2447     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2448     LoadSDNode *LN0 = HasAnyExt
2449       ? cast<LoadSDNode>(N0.getOperand(0))
2450       : cast<LoadSDNode>(N0);
2451     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2452         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2453       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2454       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2455         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2456         EVT LoadedVT = LN0->getMemoryVT();
2457
2458         if (ExtVT == LoadedVT &&
2459             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2460           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2461
2462           SDValue NewLoad =
2463             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2464                            LN0->getChain(), LN0->getBasePtr(),
2465                            LN0->getPointerInfo(),
2466                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2467                            LN0->getAlignment());
2468           AddToWorkList(N);
2469           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2470           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2471         }
2472
2473         // Do not change the width of a volatile load.
2474         // Do not generate loads of non-round integer types since these can
2475         // be expensive (and would be wrong if the type is not byte sized).
2476         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2477             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2478           EVT PtrType = LN0->getOperand(1).getValueType();
2479
2480           unsigned Alignment = LN0->getAlignment();
2481           SDValue NewPtr = LN0->getBasePtr();
2482
2483           // For big endian targets, we need to add an offset to the pointer
2484           // to load the correct bytes.  For little endian systems, we merely
2485           // need to read fewer bytes from the same pointer.
2486           if (TLI.isBigEndian()) {
2487             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2488             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2489             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2490             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2491                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2492             Alignment = MinAlign(Alignment, PtrOff);
2493           }
2494
2495           AddToWorkList(NewPtr.getNode());
2496
2497           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2498           SDValue Load =
2499             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2500                            LN0->getChain(), NewPtr,
2501                            LN0->getPointerInfo(),
2502                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2503                            Alignment);
2504           AddToWorkList(N);
2505           CombineTo(LN0, Load, Load.getValue(1));
2506           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2507         }
2508       }
2509     }
2510   }
2511
2512   return SDValue();
2513 }
2514
2515 SDValue DAGCombiner::visitOR(SDNode *N) {
2516   SDValue N0 = N->getOperand(0);
2517   SDValue N1 = N->getOperand(1);
2518   SDValue LL, LR, RL, RR, CC0, CC1;
2519   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2520   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2521   EVT VT = N1.getValueType();
2522
2523   // fold vector ops
2524   if (VT.isVector()) {
2525     SDValue FoldedVOp = SimplifyVBinOp(N);
2526     if (FoldedVOp.getNode()) return FoldedVOp;
2527   }
2528
2529   // fold (or x, undef) -> -1
2530   if (!LegalOperations &&
2531       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2532     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2533     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2534   }
2535   // fold (or c1, c2) -> c1|c2
2536   if (N0C && N1C)
2537     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2538   // canonicalize constant to RHS
2539   if (N0C && !N1C)
2540     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2541   // fold (or x, 0) -> x
2542   if (N1C && N1C->isNullValue())
2543     return N0;
2544   // fold (or x, -1) -> -1
2545   if (N1C && N1C->isAllOnesValue())
2546     return N1;
2547   // fold (or x, c) -> c iff (x & ~c) == 0
2548   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2549     return N1;
2550   // reassociate or
2551   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2552   if (ROR.getNode() != 0)
2553     return ROR;
2554   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2555   // iff (c1 & c2) == 0.
2556   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2557              isa<ConstantSDNode>(N0.getOperand(1))) {
2558     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2559     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2560       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2561                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2562                                      N0.getOperand(0), N1),
2563                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2564   }
2565   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2566   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2567     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2568     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2569
2570     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2571         LL.getValueType().isInteger()) {
2572       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2573       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2574       if (cast<ConstantSDNode>(LR)->isNullValue() &&
2575           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2576         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2577                                      LR.getValueType(), LL, RL);
2578         AddToWorkList(ORNode.getNode());
2579         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2580       }
2581       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2582       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
2583       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2584           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2585         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2586                                       LR.getValueType(), LL, RL);
2587         AddToWorkList(ANDNode.getNode());
2588         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2589       }
2590     }
2591     // canonicalize equivalent to ll == rl
2592     if (LL == RR && LR == RL) {
2593       Op1 = ISD::getSetCCSwappedOperands(Op1);
2594       std::swap(RL, RR);
2595     }
2596     if (LL == RL && LR == RR) {
2597       bool isInteger = LL.getValueType().isInteger();
2598       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2599       if (Result != ISD::SETCC_INVALID &&
2600           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2601         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2602                             LL, LR, Result);
2603     }
2604   }
2605
2606   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
2607   if (N0.getOpcode() == N1.getOpcode()) {
2608     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2609     if (Tmp.getNode()) return Tmp;
2610   }
2611
2612   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
2613   if (N0.getOpcode() == ISD::AND &&
2614       N1.getOpcode() == ISD::AND &&
2615       N0.getOperand(1).getOpcode() == ISD::Constant &&
2616       N1.getOperand(1).getOpcode() == ISD::Constant &&
2617       // Don't increase # computations.
2618       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2619     // We can only do this xform if we know that bits from X that are set in C2
2620     // but not in C1 are already zero.  Likewise for Y.
2621     const APInt &LHSMask =
2622       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2623     const APInt &RHSMask =
2624       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2625
2626     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2627         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2628       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2629                               N0.getOperand(0), N1.getOperand(0));
2630       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2631                          DAG.getConstant(LHSMask | RHSMask, VT));
2632     }
2633   }
2634
2635   // See if this is some rotate idiom.
2636   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2637     return SDValue(Rot, 0);
2638
2639   // Simplify the operands using demanded-bits information.
2640   if (!VT.isVector() &&
2641       SimplifyDemandedBits(SDValue(N, 0)))
2642     return SDValue(N, 0);
2643
2644   return SDValue();
2645 }
2646
2647 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2648 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2649   if (Op.getOpcode() == ISD::AND) {
2650     if (isa<ConstantSDNode>(Op.getOperand(1))) {
2651       Mask = Op.getOperand(1);
2652       Op = Op.getOperand(0);
2653     } else {
2654       return false;
2655     }
2656   }
2657
2658   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2659     Shift = Op;
2660     return true;
2661   }
2662
2663   return false;
2664 }
2665
2666 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
2667 // idioms for rotate, and if the target supports rotation instructions, generate
2668 // a rot[lr].
2669 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2670   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
2671   EVT VT = LHS.getValueType();
2672   if (!TLI.isTypeLegal(VT)) return 0;
2673
2674   // The target must have at least one rotate flavor.
2675   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2676   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2677   if (!HasROTL && !HasROTR) return 0;
2678
2679   // Match "(X shl/srl V1) & V2" where V2 may not be present.
2680   SDValue LHSShift;   // The shift.
2681   SDValue LHSMask;    // AND value if any.
2682   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2683     return 0; // Not part of a rotate.
2684
2685   SDValue RHSShift;   // The shift.
2686   SDValue RHSMask;    // AND value if any.
2687   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2688     return 0; // Not part of a rotate.
2689
2690   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2691     return 0;   // Not shifting the same value.
2692
2693   if (LHSShift.getOpcode() == RHSShift.getOpcode())
2694     return 0;   // Shifts must disagree.
2695
2696   // Canonicalize shl to left side in a shl/srl pair.
2697   if (RHSShift.getOpcode() == ISD::SHL) {
2698     std::swap(LHS, RHS);
2699     std::swap(LHSShift, RHSShift);
2700     std::swap(LHSMask , RHSMask );
2701   }
2702
2703   unsigned OpSizeInBits = VT.getSizeInBits();
2704   SDValue LHSShiftArg = LHSShift.getOperand(0);
2705   SDValue LHSShiftAmt = LHSShift.getOperand(1);
2706   SDValue RHSShiftAmt = RHSShift.getOperand(1);
2707
2708   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2709   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2710   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2711       RHSShiftAmt.getOpcode() == ISD::Constant) {
2712     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2713     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2714     if ((LShVal + RShVal) != OpSizeInBits)
2715       return 0;
2716
2717     SDValue Rot;
2718     if (HasROTL)
2719       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2720     else
2721       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2722
2723     // If there is an AND of either shifted operand, apply it to the result.
2724     if (LHSMask.getNode() || RHSMask.getNode()) {
2725       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2726
2727       if (LHSMask.getNode()) {
2728         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2729         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2730       }
2731       if (RHSMask.getNode()) {
2732         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2733         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2734       }
2735
2736       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2737     }
2738
2739     return Rot.getNode();
2740   }
2741
2742   // If there is a mask here, and we have a variable shift, we can't be sure
2743   // that we're masking out the right stuff.
2744   if (LHSMask.getNode() || RHSMask.getNode())
2745     return 0;
2746
2747   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2748   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2749   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2750       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2751     if (ConstantSDNode *SUBC =
2752           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2753       if (SUBC->getAPIntValue() == OpSizeInBits) {
2754         if (HasROTL)
2755           return DAG.getNode(ISD::ROTL, DL, VT,
2756                              LHSShiftArg, LHSShiftAmt).getNode();
2757         else
2758           return DAG.getNode(ISD::ROTR, DL, VT,
2759                              LHSShiftArg, RHSShiftAmt).getNode();
2760       }
2761     }
2762   }
2763
2764   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2765   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2766   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2767       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2768     if (ConstantSDNode *SUBC =
2769           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2770       if (SUBC->getAPIntValue() == OpSizeInBits) {
2771         if (HasROTR)
2772           return DAG.getNode(ISD::ROTR, DL, VT,
2773                              LHSShiftArg, RHSShiftAmt).getNode();
2774         else
2775           return DAG.getNode(ISD::ROTL, DL, VT,
2776                              LHSShiftArg, LHSShiftAmt).getNode();
2777       }
2778     }
2779   }
2780
2781   // Look for sign/zext/any-extended or truncate cases:
2782   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2783        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2784        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2785        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2786       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2787        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2788        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2789        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2790     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2791     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2792     if (RExtOp0.getOpcode() == ISD::SUB &&
2793         RExtOp0.getOperand(1) == LExtOp0) {
2794       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2795       //   (rotl x, y)
2796       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2797       //   (rotr x, (sub 32, y))
2798       if (ConstantSDNode *SUBC =
2799             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2800         if (SUBC->getAPIntValue() == OpSizeInBits) {
2801           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2802                              LHSShiftArg,
2803                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2804         }
2805       }
2806     } else if (LExtOp0.getOpcode() == ISD::SUB &&
2807                RExtOp0 == LExtOp0.getOperand(1)) {
2808       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2809       //   (rotr x, y)
2810       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2811       //   (rotl x, (sub 32, y))
2812       if (ConstantSDNode *SUBC =
2813             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2814         if (SUBC->getAPIntValue() == OpSizeInBits) {
2815           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2816                              LHSShiftArg,
2817                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2818         }
2819       }
2820     }
2821   }
2822
2823   return 0;
2824 }
2825
2826 SDValue DAGCombiner::visitXOR(SDNode *N) {
2827   SDValue N0 = N->getOperand(0);
2828   SDValue N1 = N->getOperand(1);
2829   SDValue LHS, RHS, CC;
2830   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2831   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2832   EVT VT = N0.getValueType();
2833
2834   // fold vector ops
2835   if (VT.isVector()) {
2836     SDValue FoldedVOp = SimplifyVBinOp(N);
2837     if (FoldedVOp.getNode()) return FoldedVOp;
2838   }
2839
2840   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2841   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2842     return DAG.getConstant(0, VT);
2843   // fold (xor x, undef) -> undef
2844   if (N0.getOpcode() == ISD::UNDEF)
2845     return N0;
2846   if (N1.getOpcode() == ISD::UNDEF)
2847     return N1;
2848   // fold (xor c1, c2) -> c1^c2
2849   if (N0C && N1C)
2850     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2851   // canonicalize constant to RHS
2852   if (N0C && !N1C)
2853     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2854   // fold (xor x, 0) -> x
2855   if (N1C && N1C->isNullValue())
2856     return N0;
2857   // reassociate xor
2858   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2859   if (RXOR.getNode() != 0)
2860     return RXOR;
2861
2862   // fold !(x cc y) -> (x !cc y)
2863   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2864     bool isInt = LHS.getValueType().isInteger();
2865     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2866                                                isInt);
2867
2868     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2869       switch (N0.getOpcode()) {
2870       default:
2871         llvm_unreachable("Unhandled SetCC Equivalent!");
2872       case ISD::SETCC:
2873         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2874       case ISD::SELECT_CC:
2875         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2876                                N0.getOperand(3), NotCC);
2877       }
2878     }
2879   }
2880
2881   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2882   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2883       N0.getNode()->hasOneUse() &&
2884       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2885     SDValue V = N0.getOperand(0);
2886     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2887                     DAG.getConstant(1, V.getValueType()));
2888     AddToWorkList(V.getNode());
2889     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2890   }
2891
2892   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2893   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2894       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2895     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2896     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2897       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2898       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2899       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2900       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2901       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2902     }
2903   }
2904   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2905   if (N1C && N1C->isAllOnesValue() &&
2906       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2907     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2908     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2909       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2910       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2911       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2912       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2913       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2914     }
2915   }
2916   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2917   if (N1C && N0.getOpcode() == ISD::XOR) {
2918     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2919     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2920     if (N00C)
2921       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2922                          DAG.getConstant(N1C->getAPIntValue() ^
2923                                          N00C->getAPIntValue(), VT));
2924     if (N01C)
2925       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2926                          DAG.getConstant(N1C->getAPIntValue() ^
2927                                          N01C->getAPIntValue(), VT));
2928   }
2929   // fold (xor x, x) -> 0
2930   if (N0 == N1)
2931     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
2932
2933   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
2934   if (N0.getOpcode() == N1.getOpcode()) {
2935     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2936     if (Tmp.getNode()) return Tmp;
2937   }
2938
2939   // Simplify the expression using non-local knowledge.
2940   if (!VT.isVector() &&
2941       SimplifyDemandedBits(SDValue(N, 0)))
2942     return SDValue(N, 0);
2943
2944   return SDValue();
2945 }
2946
2947 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2948 /// the shift amount is a constant.
2949 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2950   SDNode *LHS = N->getOperand(0).getNode();
2951   if (!LHS->hasOneUse()) return SDValue();
2952
2953   // We want to pull some binops through shifts, so that we have (and (shift))
2954   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
2955   // thing happens with address calculations, so it's important to canonicalize
2956   // it.
2957   bool HighBitSet = false;  // Can we transform this if the high bit is set?
2958
2959   switch (LHS->getOpcode()) {
2960   default: return SDValue();
2961   case ISD::OR:
2962   case ISD::XOR:
2963     HighBitSet = false; // We can only transform sra if the high bit is clear.
2964     break;
2965   case ISD::AND:
2966     HighBitSet = true;  // We can only transform sra if the high bit is set.
2967     break;
2968   case ISD::ADD:
2969     if (N->getOpcode() != ISD::SHL)
2970       return SDValue(); // only shl(add) not sr[al](add).
2971     HighBitSet = false; // We can only transform sra if the high bit is clear.
2972     break;
2973   }
2974
2975   // We require the RHS of the binop to be a constant as well.
2976   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2977   if (!BinOpCst) return SDValue();
2978
2979   // FIXME: disable this unless the input to the binop is a shift by a constant.
2980   // If it is not a shift, it pessimizes some common cases like:
2981   //
2982   //    void foo(int *X, int i) { X[i & 1235] = 1; }
2983   //    int bar(int *X, int i) { return X[i & 255]; }
2984   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2985   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2986        BinOpLHSVal->getOpcode() != ISD::SRA &&
2987        BinOpLHSVal->getOpcode() != ISD::SRL) ||
2988       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2989     return SDValue();
2990
2991   EVT VT = N->getValueType(0);
2992
2993   // If this is a signed shift right, and the high bit is modified by the
2994   // logical operation, do not perform the transformation. The highBitSet
2995   // boolean indicates the value of the high bit of the constant which would
2996   // cause it to be modified for this operation.
2997   if (N->getOpcode() == ISD::SRA) {
2998     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2999     if (BinOpRHSSignSet != HighBitSet)
3000       return SDValue();
3001   }
3002
3003   // Fold the constants, shifting the binop RHS by the shift amount.
3004   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3005                                N->getValueType(0),
3006                                LHS->getOperand(1), N->getOperand(1));
3007
3008   // Create the new shift.
3009   SDValue NewShift = DAG.getNode(N->getOpcode(),
3010                                  LHS->getOperand(0).getDebugLoc(),
3011                                  VT, LHS->getOperand(0), N->getOperand(1));
3012
3013   // Create the new binop.
3014   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3015 }
3016
3017 SDValue DAGCombiner::visitSHL(SDNode *N) {
3018   SDValue N0 = N->getOperand(0);
3019   SDValue N1 = N->getOperand(1);
3020   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3021   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3022   EVT VT = N0.getValueType();
3023   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3024
3025   // fold (shl c1, c2) -> c1<<c2
3026   if (N0C && N1C)
3027     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3028   // fold (shl 0, x) -> 0
3029   if (N0C && N0C->isNullValue())
3030     return N0;
3031   // fold (shl x, c >= size(x)) -> undef
3032   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3033     return DAG.getUNDEF(VT);
3034   // fold (shl x, 0) -> x
3035   if (N1C && N1C->isNullValue())
3036     return N0;
3037   // fold (shl undef, x) -> 0
3038   if (N0.getOpcode() == ISD::UNDEF)
3039     return DAG.getConstant(0, VT);
3040   // if (shl x, c) is known to be zero, return 0
3041   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3042                             APInt::getAllOnesValue(OpSizeInBits)))
3043     return DAG.getConstant(0, VT);
3044   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3045   if (N1.getOpcode() == ISD::TRUNCATE &&
3046       N1.getOperand(0).getOpcode() == ISD::AND &&
3047       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3048     SDValue N101 = N1.getOperand(0).getOperand(1);
3049     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3050       EVT TruncVT = N1.getValueType();
3051       SDValue N100 = N1.getOperand(0).getOperand(0);
3052       APInt TruncC = N101C->getAPIntValue();
3053       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3054       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3055                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3056                                      DAG.getNode(ISD::TRUNCATE,
3057                                                  N->getDebugLoc(),
3058                                                  TruncVT, N100),
3059                                      DAG.getConstant(TruncC, TruncVT)));
3060     }
3061   }
3062
3063   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3064     return SDValue(N, 0);
3065
3066   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3067   if (N1C && N0.getOpcode() == ISD::SHL &&
3068       N0.getOperand(1).getOpcode() == ISD::Constant) {
3069     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3070     uint64_t c2 = N1C->getZExtValue();
3071     if (c1 + c2 >= OpSizeInBits)
3072       return DAG.getConstant(0, VT);
3073     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3074                        DAG.getConstant(c1 + c2, N1.getValueType()));
3075   }
3076
3077   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3078   // For this to be valid, the second form must not preserve any of the bits
3079   // that are shifted out by the inner shift in the first form.  This means
3080   // the outer shift size must be >= the number of bits added by the ext.
3081   // As a corollary, we don't care what kind of ext it is.
3082   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3083               N0.getOpcode() == ISD::ANY_EXTEND ||
3084               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3085       N0.getOperand(0).getOpcode() == ISD::SHL &&
3086       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3087     uint64_t c1 =
3088       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3089     uint64_t c2 = N1C->getZExtValue();
3090     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3091     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3092     if (c2 >= OpSizeInBits - InnerShiftSize) {
3093       if (c1 + c2 >= OpSizeInBits)
3094         return DAG.getConstant(0, VT);
3095       return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3096                          DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3097                                      N0.getOperand(0)->getOperand(0)),
3098                          DAG.getConstant(c1 + c2, N1.getValueType()));
3099     }
3100   }
3101
3102   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3103   //                               (and (srl x, (sub c1, c2), MASK)
3104   if (N1C && N0.getOpcode() == ISD::SRL &&
3105       N0.getOperand(1).getOpcode() == ISD::Constant) {
3106     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3107     if (c1 < VT.getSizeInBits()) {
3108       uint64_t c2 = N1C->getZExtValue();
3109       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3110                                          VT.getSizeInBits() - c1);
3111       SDValue Shift;
3112       if (c2 > c1) {
3113         Mask = Mask.shl(c2-c1);
3114         Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3115                             DAG.getConstant(c2-c1, N1.getValueType()));
3116       } else {
3117         Mask = Mask.lshr(c1-c2);
3118         Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3119                             DAG.getConstant(c1-c2, N1.getValueType()));
3120       }
3121       return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3122                          DAG.getConstant(Mask, VT));
3123     }
3124   }
3125   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3126   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3127     SDValue HiBitsMask =
3128       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3129                                             VT.getSizeInBits() -
3130                                               N1C->getZExtValue()),
3131                       VT);
3132     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3133                        HiBitsMask);
3134   }
3135
3136   if (N1C) {
3137     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3138     if (NewSHL.getNode())
3139       return NewSHL;
3140   }
3141
3142   return SDValue();
3143 }
3144
3145 SDValue DAGCombiner::visitSRA(SDNode *N) {
3146   SDValue N0 = N->getOperand(0);
3147   SDValue N1 = N->getOperand(1);
3148   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3149   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3150   EVT VT = N0.getValueType();
3151   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3152
3153   // fold (sra c1, c2) -> (sra c1, c2)
3154   if (N0C && N1C)
3155     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3156   // fold (sra 0, x) -> 0
3157   if (N0C && N0C->isNullValue())
3158     return N0;
3159   // fold (sra -1, x) -> -1
3160   if (N0C && N0C->isAllOnesValue())
3161     return N0;
3162   // fold (sra x, (setge c, size(x))) -> undef
3163   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3164     return DAG.getUNDEF(VT);
3165   // fold (sra x, 0) -> x
3166   if (N1C && N1C->isNullValue())
3167     return N0;
3168   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3169   // sext_inreg.
3170   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3171     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3172     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3173     if (VT.isVector())
3174       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3175                                ExtVT, VT.getVectorNumElements());
3176     if ((!LegalOperations ||
3177          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3178       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3179                          N0.getOperand(0), DAG.getValueType(ExtVT));
3180   }
3181
3182   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3183   if (N1C && N0.getOpcode() == ISD::SRA) {
3184     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3185       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3186       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3187       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3188                          DAG.getConstant(Sum, N1C->getValueType(0)));
3189     }
3190   }
3191
3192   // fold (sra (shl X, m), (sub result_size, n))
3193   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3194   // result_size - n != m.
3195   // If truncate is free for the target sext(shl) is likely to result in better
3196   // code.
3197   if (N0.getOpcode() == ISD::SHL) {
3198     // Get the two constanst of the shifts, CN0 = m, CN = n.
3199     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3200     if (N01C && N1C) {
3201       // Determine what the truncate's result bitsize and type would be.
3202       EVT TruncVT =
3203         EVT::getIntegerVT(*DAG.getContext(),
3204                           OpSizeInBits - N1C->getZExtValue());
3205       // Determine the residual right-shift amount.
3206       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3207
3208       // If the shift is not a no-op (in which case this should be just a sign
3209       // extend already), the truncated to type is legal, sign_extend is legal
3210       // on that type, and the truncate to that type is both legal and free,
3211       // perform the transform.
3212       if ((ShiftAmt > 0) &&
3213           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3214           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3215           TLI.isTruncateFree(VT, TruncVT)) {
3216
3217           SDValue Amt = DAG.getConstant(ShiftAmt,
3218               getShiftAmountTy(N0.getOperand(0).getValueType()));
3219           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3220                                       N0.getOperand(0), Amt);
3221           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3222                                       Shift);
3223           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3224                              N->getValueType(0), Trunc);
3225       }
3226     }
3227   }
3228
3229   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3230   if (N1.getOpcode() == ISD::TRUNCATE &&
3231       N1.getOperand(0).getOpcode() == ISD::AND &&
3232       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3233     SDValue N101 = N1.getOperand(0).getOperand(1);
3234     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3235       EVT TruncVT = N1.getValueType();
3236       SDValue N100 = N1.getOperand(0).getOperand(0);
3237       APInt TruncC = N101C->getAPIntValue();
3238       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3239       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3240                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3241                                      TruncVT,
3242                                      DAG.getNode(ISD::TRUNCATE,
3243                                                  N->getDebugLoc(),
3244                                                  TruncVT, N100),
3245                                      DAG.getConstant(TruncC, TruncVT)));
3246     }
3247   }
3248
3249   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3250   //      if c1 is equal to the number of bits the trunc removes
3251   if (N0.getOpcode() == ISD::TRUNCATE &&
3252       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3253        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3254       N0.getOperand(0).hasOneUse() &&
3255       N0.getOperand(0).getOperand(1).hasOneUse() &&
3256       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3257     EVT LargeVT = N0.getOperand(0).getValueType();
3258     ConstantSDNode *LargeShiftAmt =
3259       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3260
3261     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3262         LargeShiftAmt->getZExtValue()) {
3263       SDValue Amt =
3264         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3265               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3266       SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3267                                 N0.getOperand(0).getOperand(0), Amt);
3268       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3269     }
3270   }
3271
3272   // Simplify, based on bits shifted out of the LHS.
3273   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3274     return SDValue(N, 0);
3275
3276
3277   // If the sign bit is known to be zero, switch this to a SRL.
3278   if (DAG.SignBitIsZero(N0))
3279     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3280
3281   if (N1C) {
3282     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3283     if (NewSRA.getNode())
3284       return NewSRA;
3285   }
3286
3287   return SDValue();
3288 }
3289
3290 SDValue DAGCombiner::visitSRL(SDNode *N) {
3291   SDValue N0 = N->getOperand(0);
3292   SDValue N1 = N->getOperand(1);
3293   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3294   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3295   EVT VT = N0.getValueType();
3296   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3297
3298   // fold (srl c1, c2) -> c1 >>u c2
3299   if (N0C && N1C)
3300     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3301   // fold (srl 0, x) -> 0
3302   if (N0C && N0C->isNullValue())
3303     return N0;
3304   // fold (srl x, c >= size(x)) -> undef
3305   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3306     return DAG.getUNDEF(VT);
3307   // fold (srl x, 0) -> x
3308   if (N1C && N1C->isNullValue())
3309     return N0;
3310   // if (srl x, c) is known to be zero, return 0
3311   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3312                                    APInt::getAllOnesValue(OpSizeInBits)))
3313     return DAG.getConstant(0, VT);
3314
3315   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3316   if (N1C && N0.getOpcode() == ISD::SRL &&
3317       N0.getOperand(1).getOpcode() == ISD::Constant) {
3318     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3319     uint64_t c2 = N1C->getZExtValue();
3320     if (c1 + c2 >= OpSizeInBits)
3321       return DAG.getConstant(0, VT);
3322     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3323                        DAG.getConstant(c1 + c2, N1.getValueType()));
3324   }
3325
3326   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3327   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3328       N0.getOperand(0).getOpcode() == ISD::SRL &&
3329       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3330     uint64_t c1 =
3331       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3332     uint64_t c2 = N1C->getZExtValue();
3333     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3334     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3335     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3336     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3337     if (c1 + OpSizeInBits == InnerShiftSize) {
3338       if (c1 + c2 >= InnerShiftSize)
3339         return DAG.getConstant(0, VT);
3340       return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3341                          DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3342                                      N0.getOperand(0)->getOperand(0),
3343                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3344     }
3345   }
3346
3347   // fold (srl (shl x, c), c) -> (and x, cst2)
3348   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3349       N0.getValueSizeInBits() <= 64) {
3350     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3351     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3352                        DAG.getConstant(~0ULL >> ShAmt, VT));
3353   }
3354
3355
3356   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3357   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3358     // Shifting in all undef bits?
3359     EVT SmallVT = N0.getOperand(0).getValueType();
3360     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3361       return DAG.getUNDEF(VT);
3362
3363     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3364       uint64_t ShiftAmt = N1C->getZExtValue();
3365       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3366                                        N0.getOperand(0),
3367                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3368       AddToWorkList(SmallShift.getNode());
3369       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3370     }
3371   }
3372
3373   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3374   // bit, which is unmodified by sra.
3375   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3376     if (N0.getOpcode() == ISD::SRA)
3377       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3378   }
3379
3380   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3381   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3382       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3383     APInt KnownZero, KnownOne;
3384     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3385     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3386
3387     // If any of the input bits are KnownOne, then the input couldn't be all
3388     // zeros, thus the result of the srl will always be zero.
3389     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3390
3391     // If all of the bits input the to ctlz node are known to be zero, then
3392     // the result of the ctlz is "32" and the result of the shift is one.
3393     APInt UnknownBits = ~KnownZero & Mask;
3394     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3395
3396     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3397     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3398       // Okay, we know that only that the single bit specified by UnknownBits
3399       // could be set on input to the CTLZ node. If this bit is set, the SRL
3400       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3401       // to an SRL/XOR pair, which is likely to simplify more.
3402       unsigned ShAmt = UnknownBits.countTrailingZeros();
3403       SDValue Op = N0.getOperand(0);
3404
3405       if (ShAmt) {
3406         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3407                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3408         AddToWorkList(Op.getNode());
3409       }
3410
3411       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3412                          Op, DAG.getConstant(1, VT));
3413     }
3414   }
3415
3416   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3417   if (N1.getOpcode() == ISD::TRUNCATE &&
3418       N1.getOperand(0).getOpcode() == ISD::AND &&
3419       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3420     SDValue N101 = N1.getOperand(0).getOperand(1);
3421     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3422       EVT TruncVT = N1.getValueType();
3423       SDValue N100 = N1.getOperand(0).getOperand(0);
3424       APInt TruncC = N101C->getAPIntValue();
3425       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3426       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3427                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3428                                      TruncVT,
3429                                      DAG.getNode(ISD::TRUNCATE,
3430                                                  N->getDebugLoc(),
3431                                                  TruncVT, N100),
3432                                      DAG.getConstant(TruncC, TruncVT)));
3433     }
3434   }
3435
3436   // fold operands of srl based on knowledge that the low bits are not
3437   // demanded.
3438   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3439     return SDValue(N, 0);
3440
3441   if (N1C) {
3442     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3443     if (NewSRL.getNode())
3444       return NewSRL;
3445   }
3446
3447   // Attempt to convert a srl of a load into a narrower zero-extending load.
3448   SDValue NarrowLoad = ReduceLoadWidth(N);
3449   if (NarrowLoad.getNode())
3450     return NarrowLoad;
3451
3452   // Here is a common situation. We want to optimize:
3453   //
3454   //   %a = ...
3455   //   %b = and i32 %a, 2
3456   //   %c = srl i32 %b, 1
3457   //   brcond i32 %c ...
3458   //
3459   // into
3460   //
3461   //   %a = ...
3462   //   %b = and %a, 2
3463   //   %c = setcc eq %b, 0
3464   //   brcond %c ...
3465   //
3466   // However when after the source operand of SRL is optimized into AND, the SRL
3467   // itself may not be optimized further. Look for it and add the BRCOND into
3468   // the worklist.
3469   if (N->hasOneUse()) {
3470     SDNode *Use = *N->use_begin();
3471     if (Use->getOpcode() == ISD::BRCOND)
3472       AddToWorkList(Use);
3473     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3474       // Also look pass the truncate.
3475       Use = *Use->use_begin();
3476       if (Use->getOpcode() == ISD::BRCOND)
3477         AddToWorkList(Use);
3478     }
3479   }
3480
3481   return SDValue();
3482 }
3483
3484 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3485   SDValue N0 = N->getOperand(0);
3486   EVT VT = N->getValueType(0);
3487
3488   // fold (ctlz c1) -> c2
3489   if (isa<ConstantSDNode>(N0))
3490     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3491   return SDValue();
3492 }
3493
3494 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3495   SDValue N0 = N->getOperand(0);
3496   EVT VT = N->getValueType(0);
3497
3498   // fold (cttz c1) -> c2
3499   if (isa<ConstantSDNode>(N0))
3500     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3501   return SDValue();
3502 }
3503
3504 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3505   SDValue N0 = N->getOperand(0);
3506   EVT VT = N->getValueType(0);
3507
3508   // fold (ctpop c1) -> c2
3509   if (isa<ConstantSDNode>(N0))
3510     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3511   return SDValue();
3512 }
3513
3514 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3515   SDValue N0 = N->getOperand(0);
3516   SDValue N1 = N->getOperand(1);
3517   SDValue N2 = N->getOperand(2);
3518   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3519   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3520   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3521   EVT VT = N->getValueType(0);
3522   EVT VT0 = N0.getValueType();
3523
3524   // fold (select C, X, X) -> X
3525   if (N1 == N2)
3526     return N1;
3527   // fold (select true, X, Y) -> X
3528   if (N0C && !N0C->isNullValue())
3529     return N1;
3530   // fold (select false, X, Y) -> Y
3531   if (N0C && N0C->isNullValue())
3532     return N2;
3533   // fold (select C, 1, X) -> (or C, X)
3534   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3535     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3536   // fold (select C, 0, 1) -> (xor C, 1)
3537   if (VT.isInteger() &&
3538       (VT0 == MVT::i1 ||
3539        (VT0.isInteger() &&
3540         TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3541       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3542     SDValue XORNode;
3543     if (VT == VT0)
3544       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3545                          N0, DAG.getConstant(1, VT0));
3546     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3547                           N0, DAG.getConstant(1, VT0));
3548     AddToWorkList(XORNode.getNode());
3549     if (VT.bitsGT(VT0))
3550       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3551     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3552   }
3553   // fold (select C, 0, X) -> (and (not C), X)
3554   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3555     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3556     AddToWorkList(NOTNode.getNode());
3557     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3558   }
3559   // fold (select C, X, 1) -> (or (not C), X)
3560   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3561     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3562     AddToWorkList(NOTNode.getNode());
3563     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3564   }
3565   // fold (select C, X, 0) -> (and C, X)
3566   if (VT == MVT::i1 && N2C && N2C->isNullValue())
3567     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3568   // fold (select X, X, Y) -> (or X, Y)
3569   // fold (select X, 1, Y) -> (or X, Y)
3570   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3571     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3572   // fold (select X, Y, X) -> (and X, Y)
3573   // fold (select X, Y, 0) -> (and X, Y)
3574   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3575     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3576
3577   // If we can fold this based on the true/false value, do so.
3578   if (SimplifySelectOps(N, N1, N2))
3579     return SDValue(N, 0);  // Don't revisit N.
3580
3581   // fold selects based on a setcc into other things, such as min/max/abs
3582   if (N0.getOpcode() == ISD::SETCC) {
3583     // FIXME:
3584     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3585     // having to say they don't support SELECT_CC on every type the DAG knows
3586     // about, since there is no way to mark an opcode illegal at all value types
3587     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3588         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3589       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3590                          N0.getOperand(0), N0.getOperand(1),
3591                          N1, N2, N0.getOperand(2));
3592     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3593   }
3594
3595   return SDValue();
3596 }
3597
3598 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3599   SDValue N0 = N->getOperand(0);
3600   SDValue N1 = N->getOperand(1);
3601   SDValue N2 = N->getOperand(2);
3602   SDValue N3 = N->getOperand(3);
3603   SDValue N4 = N->getOperand(4);
3604   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3605
3606   // fold select_cc lhs, rhs, x, x, cc -> x
3607   if (N2 == N3)
3608     return N2;
3609
3610   // Determine if the condition we're dealing with is constant
3611   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3612                               N0, N1, CC, N->getDebugLoc(), false);
3613   if (SCC.getNode()) AddToWorkList(SCC.getNode());
3614
3615   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3616     if (!SCCC->isNullValue())
3617       return N2;    // cond always true -> true val
3618     else
3619       return N3;    // cond always false -> false val
3620   }
3621
3622   // Fold to a simpler select_cc
3623   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3624     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3625                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3626                        SCC.getOperand(2));
3627
3628   // If we can fold this based on the true/false value, do so.
3629   if (SimplifySelectOps(N, N2, N3))
3630     return SDValue(N, 0);  // Don't revisit N.
3631
3632   // fold select_cc into other things, such as min/max/abs
3633   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3634 }
3635
3636 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3637   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3638                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
3639                        N->getDebugLoc());
3640 }
3641
3642 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3643 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3644 // transformation. Returns true if extension are possible and the above
3645 // mentioned transformation is profitable.
3646 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3647                                     unsigned ExtOpc,
3648                                     SmallVector<SDNode*, 4> &ExtendNodes,
3649                                     const TargetLowering &TLI) {
3650   bool HasCopyToRegUses = false;
3651   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3652   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3653                             UE = N0.getNode()->use_end();
3654        UI != UE; ++UI) {
3655     SDNode *User = *UI;
3656     if (User == N)
3657       continue;
3658     if (UI.getUse().getResNo() != N0.getResNo())
3659       continue;
3660     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3661     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3662       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3663       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3664         // Sign bits will be lost after a zext.
3665         return false;
3666       bool Add = false;
3667       for (unsigned i = 0; i != 2; ++i) {
3668         SDValue UseOp = User->getOperand(i);
3669         if (UseOp == N0)
3670           continue;
3671         if (!isa<ConstantSDNode>(UseOp))
3672           return false;
3673         Add = true;
3674       }
3675       if (Add)
3676         ExtendNodes.push_back(User);
3677       continue;
3678     }
3679     // If truncates aren't free and there are users we can't
3680     // extend, it isn't worthwhile.
3681     if (!isTruncFree)
3682       return false;
3683     // Remember if this value is live-out.
3684     if (User->getOpcode() == ISD::CopyToReg)
3685       HasCopyToRegUses = true;
3686   }
3687
3688   if (HasCopyToRegUses) {
3689     bool BothLiveOut = false;
3690     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3691          UI != UE; ++UI) {
3692       SDUse &Use = UI.getUse();
3693       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3694         BothLiveOut = true;
3695         break;
3696       }
3697     }
3698     if (BothLiveOut)
3699       // Both unextended and extended values are live out. There had better be
3700       // a good reason for the transformation.
3701       return ExtendNodes.size();
3702   }
3703   return true;
3704 }
3705
3706 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
3707                                   SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
3708                                   ISD::NodeType ExtType) {
3709   // Extend SetCC uses if necessary.
3710   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3711     SDNode *SetCC = SetCCs[i];
3712     SmallVector<SDValue, 4> Ops;
3713
3714     for (unsigned j = 0; j != 2; ++j) {
3715       SDValue SOp = SetCC->getOperand(j);
3716       if (SOp == Trunc)
3717         Ops.push_back(ExtLoad);
3718       else
3719         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
3720     }
3721
3722     Ops.push_back(SetCC->getOperand(2));
3723     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
3724                                  &Ops[0], Ops.size()));
3725   }
3726 }
3727
3728 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3729   SDValue N0 = N->getOperand(0);
3730   EVT VT = N->getValueType(0);
3731
3732   // fold (sext c1) -> c1
3733   if (isa<ConstantSDNode>(N0))
3734     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3735
3736   // fold (sext (sext x)) -> (sext x)
3737   // fold (sext (aext x)) -> (sext x)
3738   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3739     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3740                        N0.getOperand(0));
3741
3742   if (N0.getOpcode() == ISD::TRUNCATE) {
3743     // fold (sext (truncate (load x))) -> (sext (smaller load x))
3744     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3745     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3746     if (NarrowLoad.getNode()) {
3747       SDNode* oye = N0.getNode()->getOperand(0).getNode();
3748       if (NarrowLoad.getNode() != N0.getNode()) {
3749         CombineTo(N0.getNode(), NarrowLoad);
3750         // CombineTo deleted the truncate, if needed, but not what's under it.
3751         AddToWorkList(oye);
3752       }
3753       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3754     }
3755
3756     // See if the value being truncated is already sign extended.  If so, just
3757     // eliminate the trunc/sext pair.
3758     SDValue Op = N0.getOperand(0);
3759     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
3760     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
3761     unsigned DestBits = VT.getScalarType().getSizeInBits();
3762     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3763
3764     if (OpBits == DestBits) {
3765       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
3766       // bits, it is already ready.
3767       if (NumSignBits > DestBits-MidBits)
3768         return Op;
3769     } else if (OpBits < DestBits) {
3770       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
3771       // bits, just sext from i32.
3772       if (NumSignBits > OpBits-MidBits)
3773         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3774     } else {
3775       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
3776       // bits, just truncate to i32.
3777       if (NumSignBits > OpBits-MidBits)
3778         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3779     }
3780
3781     // fold (sext (truncate x)) -> (sextinreg x).
3782     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3783                                                  N0.getValueType())) {
3784       if (OpBits < DestBits)
3785         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3786       else if (OpBits > DestBits)
3787         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3788       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3789                          DAG.getValueType(N0.getValueType()));
3790     }
3791   }
3792
3793   // fold (sext (load x)) -> (sext (truncate (sextload x)))
3794   // None of the supported targets knows how to perform load and sign extend
3795   // on vectors in one instruction.  We only perform this transformation on
3796   // scalars.
3797   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
3798       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3799        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3800     bool DoXform = true;
3801     SmallVector<SDNode*, 4> SetCCs;
3802     if (!N0.hasOneUse())
3803       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3804     if (DoXform) {
3805       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3806       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3807                                        LN0->getChain(),
3808                                        LN0->getBasePtr(), LN0->getPointerInfo(),
3809                                        N0.getValueType(),
3810                                        LN0->isVolatile(), LN0->isNonTemporal(),
3811                                        LN0->getAlignment());
3812       CombineTo(N, ExtLoad);
3813       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3814                                   N0.getValueType(), ExtLoad);
3815       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3816       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
3817                       ISD::SIGN_EXTEND);
3818       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3819     }
3820   }
3821
3822   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3823   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3824   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3825       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3826     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3827     EVT MemVT = LN0->getMemoryVT();
3828     if ((!LegalOperations && !LN0->isVolatile()) ||
3829         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3830       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3831                                        LN0->getChain(),
3832                                        LN0->getBasePtr(), LN0->getPointerInfo(),
3833                                        MemVT,
3834                                        LN0->isVolatile(), LN0->isNonTemporal(),
3835                                        LN0->getAlignment());
3836       CombineTo(N, ExtLoad);
3837       CombineTo(N0.getNode(),
3838                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3839                             N0.getValueType(), ExtLoad),
3840                 ExtLoad.getValue(1));
3841       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3842     }
3843   }
3844
3845   // fold (sext (and/or/xor (load x), cst)) ->
3846   //      (and/or/xor (sextload x), (sext cst))
3847   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
3848        N0.getOpcode() == ISD::XOR) &&
3849       isa<LoadSDNode>(N0.getOperand(0)) &&
3850       N0.getOperand(1).getOpcode() == ISD::Constant &&
3851       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
3852       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
3853     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
3854     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
3855       bool DoXform = true;
3856       SmallVector<SDNode*, 4> SetCCs;
3857       if (!N0.hasOneUse())
3858         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
3859                                           SetCCs, TLI);
3860       if (DoXform) {
3861         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
3862                                          LN0->getChain(), LN0->getBasePtr(),
3863                                          LN0->getPointerInfo(),
3864                                          LN0->getMemoryVT(),
3865                                          LN0->isVolatile(),
3866                                          LN0->isNonTemporal(),
3867                                          LN0->getAlignment());
3868         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3869         Mask = Mask.sext(VT.getSizeInBits());
3870         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
3871                                   ExtLoad, DAG.getConstant(Mask, VT));
3872         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
3873                                     N0.getOperand(0).getDebugLoc(),
3874                                     N0.getOperand(0).getValueType(), ExtLoad);
3875         CombineTo(N, And);
3876         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
3877         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
3878                         ISD::SIGN_EXTEND);
3879         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3880       }
3881     }
3882   }
3883
3884   if (N0.getOpcode() == ISD::SETCC) {
3885     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3886     // Only do this before legalize for now.
3887     if (VT.isVector() && !LegalOperations) {
3888       EVT N0VT = N0.getOperand(0).getValueType();
3889         // We know that the # elements of the results is the same as the
3890         // # elements of the compare (and the # elements of the compare result
3891         // for that matter).  Check to see that they are the same size.  If so,
3892         // we know that the element size of the sext'd result matches the
3893         // element size of the compare operands.
3894       if (VT.getSizeInBits() == N0VT.getSizeInBits())
3895         return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3896                              N0.getOperand(1),
3897                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
3898       // If the desired elements are smaller or larger than the source
3899       // elements we can use a matching integer vector type and then
3900       // truncate/sign extend
3901       else {
3902         EVT MatchingElementType =
3903           EVT::getIntegerVT(*DAG.getContext(),
3904                             N0VT.getScalarType().getSizeInBits());
3905         EVT MatchingVectorType =
3906           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3907                            N0VT.getVectorNumElements());
3908         SDValue VsetCC =
3909           DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3910                         N0.getOperand(1),
3911                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
3912         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
3913       }
3914     }
3915
3916     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3917     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3918     SDValue NegOne =
3919       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3920     SDValue SCC =
3921       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3922                        NegOne, DAG.getConstant(0, VT),
3923                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3924     if (SCC.getNode()) return SCC;
3925     if (!LegalOperations ||
3926         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3927       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3928                          DAG.getSetCC(N->getDebugLoc(),
3929                                       TLI.getSetCCResultType(VT),
3930                                       N0.getOperand(0), N0.getOperand(1),
3931                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3932                          NegOne, DAG.getConstant(0, VT));
3933   }
3934
3935   // fold (sext x) -> (zext x) if the sign bit is known zero.
3936   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3937       DAG.SignBitIsZero(N0))
3938     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3939
3940   return SDValue();
3941 }
3942
3943 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3944   SDValue N0 = N->getOperand(0);
3945   EVT VT = N->getValueType(0);
3946
3947   // fold (zext c1) -> c1
3948   if (isa<ConstantSDNode>(N0))
3949     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3950   // fold (zext (zext x)) -> (zext x)
3951   // fold (zext (aext x)) -> (zext x)
3952   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3953     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3954                        N0.getOperand(0));
3955
3956   // fold (zext (truncate (load x))) -> (zext (smaller load x))
3957   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3958   if (N0.getOpcode() == ISD::TRUNCATE) {
3959     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3960     if (NarrowLoad.getNode()) {
3961       SDNode* oye = N0.getNode()->getOperand(0).getNode();
3962       if (NarrowLoad.getNode() != N0.getNode()) {
3963         CombineTo(N0.getNode(), NarrowLoad);
3964         // CombineTo deleted the truncate, if needed, but not what's under it.
3965         AddToWorkList(oye);
3966       }
3967       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3968     }
3969   }
3970
3971   // fold (zext (truncate x)) -> (and x, mask)
3972   if (N0.getOpcode() == ISD::TRUNCATE &&
3973       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3974
3975     // fold (zext (truncate (load x))) -> (zext (smaller load x))
3976     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
3977     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3978     if (NarrowLoad.getNode()) {
3979       SDNode* oye = N0.getNode()->getOperand(0).getNode();
3980       if (NarrowLoad.getNode() != N0.getNode()) {
3981         CombineTo(N0.getNode(), NarrowLoad);
3982         // CombineTo deleted the truncate, if needed, but not what's under it.
3983         AddToWorkList(oye);
3984       }
3985       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3986     }
3987
3988     SDValue Op = N0.getOperand(0);
3989     if (Op.getValueType().bitsLT(VT)) {
3990       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3991     } else if (Op.getValueType().bitsGT(VT)) {
3992       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3993     }
3994     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3995                                   N0.getValueType().getScalarType());
3996   }
3997
3998   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3999   // if either of the casts is not free.
4000   if (N0.getOpcode() == ISD::AND &&
4001       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4002       N0.getOperand(1).getOpcode() == ISD::Constant &&
4003       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4004                            N0.getValueType()) ||
4005        !TLI.isZExtFree(N0.getValueType(), VT))) {
4006     SDValue X = N0.getOperand(0).getOperand(0);
4007     if (X.getValueType().bitsLT(VT)) {
4008       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4009     } else if (X.getValueType().bitsGT(VT)) {
4010       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4011     }
4012     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4013     Mask = Mask.zext(VT.getSizeInBits());
4014     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4015                        X, DAG.getConstant(Mask, VT));
4016   }
4017
4018   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4019   // None of the supported targets knows how to perform load and vector_zext
4020   // on vectors in one instruction.  We only perform this transformation on
4021   // scalars.
4022   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4023       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4024        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4025     bool DoXform = true;
4026     SmallVector<SDNode*, 4> SetCCs;
4027     if (!N0.hasOneUse())
4028       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4029     if (DoXform) {
4030       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4031       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4032                                        LN0->getChain(),
4033                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4034                                        N0.getValueType(),
4035                                        LN0->isVolatile(), LN0->isNonTemporal(),
4036                                        LN0->getAlignment());
4037       CombineTo(N, ExtLoad);
4038       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4039                                   N0.getValueType(), ExtLoad);
4040       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4041
4042       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4043                       ISD::ZERO_EXTEND);
4044       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4045     }
4046   }
4047
4048   // fold (zext (and/or/xor (load x), cst)) ->
4049   //      (and/or/xor (zextload x), (zext cst))
4050   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4051        N0.getOpcode() == ISD::XOR) &&
4052       isa<LoadSDNode>(N0.getOperand(0)) &&
4053       N0.getOperand(1).getOpcode() == ISD::Constant &&
4054       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4055       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4056     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4057     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4058       bool DoXform = true;
4059       SmallVector<SDNode*, 4> SetCCs;
4060       if (!N0.hasOneUse())
4061         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4062                                           SetCCs, TLI);
4063       if (DoXform) {
4064         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4065                                          LN0->getChain(), LN0->getBasePtr(),
4066                                          LN0->getPointerInfo(),
4067                                          LN0->getMemoryVT(),
4068                                          LN0->isVolatile(),
4069                                          LN0->isNonTemporal(),
4070                                          LN0->getAlignment());
4071         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4072         Mask = Mask.zext(VT.getSizeInBits());
4073         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4074                                   ExtLoad, DAG.getConstant(Mask, VT));
4075         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4076                                     N0.getOperand(0).getDebugLoc(),
4077                                     N0.getOperand(0).getValueType(), ExtLoad);
4078         CombineTo(N, And);
4079         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4080         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4081                         ISD::ZERO_EXTEND);
4082         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4083       }
4084     }
4085   }
4086
4087   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4088   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4089   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4090       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4091     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4092     EVT MemVT = LN0->getMemoryVT();
4093     if ((!LegalOperations && !LN0->isVolatile()) ||
4094         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4095       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4096                                        LN0->getChain(),
4097                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4098                                        MemVT,
4099                                        LN0->isVolatile(), LN0->isNonTemporal(),
4100                                        LN0->getAlignment());
4101       CombineTo(N, ExtLoad);
4102       CombineTo(N0.getNode(),
4103                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4104                             ExtLoad),
4105                 ExtLoad.getValue(1));
4106       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4107     }
4108   }
4109
4110   if (N0.getOpcode() == ISD::SETCC) {
4111     if (!LegalOperations && VT.isVector()) {
4112       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4113       // Only do this before legalize for now.
4114       EVT N0VT = N0.getOperand(0).getValueType();
4115       EVT EltVT = VT.getVectorElementType();
4116       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4117                                     DAG.getConstant(1, EltVT));
4118       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4119         // We know that the # elements of the results is the same as the
4120         // # elements of the compare (and the # elements of the compare result
4121         // for that matter).  Check to see that they are the same size.  If so,
4122         // we know that the element size of the sext'd result matches the
4123         // element size of the compare operands.
4124         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4125                            DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4126                                          N0.getOperand(1),
4127                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4128                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4129                                        &OneOps[0], OneOps.size()));
4130
4131       // If the desired elements are smaller or larger than the source
4132       // elements we can use a matching integer vector type and then
4133       // truncate/sign extend
4134       EVT MatchingElementType =
4135         EVT::getIntegerVT(*DAG.getContext(),
4136                           N0VT.getScalarType().getSizeInBits());
4137       EVT MatchingVectorType =
4138         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4139                          N0VT.getVectorNumElements());
4140       SDValue VsetCC =
4141         DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4142                       N0.getOperand(1),
4143                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4144       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4145                          DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4146                          DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4147                                      &OneOps[0], OneOps.size()));
4148     }
4149
4150     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4151     SDValue SCC =
4152       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4153                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4154                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4155     if (SCC.getNode()) return SCC;
4156   }
4157
4158   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4159   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4160       isa<ConstantSDNode>(N0.getOperand(1)) &&
4161       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4162       N0.hasOneUse()) {
4163     SDValue ShAmt = N0.getOperand(1);
4164     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4165     if (N0.getOpcode() == ISD::SHL) {
4166       SDValue InnerZExt = N0.getOperand(0);
4167       // If the original shl may be shifting out bits, do not perform this
4168       // transformation.
4169       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4170         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4171       if (ShAmtVal > KnownZeroBits)
4172         return SDValue();
4173     }
4174
4175     DebugLoc DL = N->getDebugLoc();
4176
4177     // Ensure that the shift amount is wide enough for the shifted value.
4178     if (VT.getSizeInBits() >= 256)
4179       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4180
4181     return DAG.getNode(N0.getOpcode(), DL, VT,
4182                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4183                        ShAmt);
4184   }
4185
4186   return SDValue();
4187 }
4188
4189 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4190   SDValue N0 = N->getOperand(0);
4191   EVT VT = N->getValueType(0);
4192
4193   // fold (aext c1) -> c1
4194   if (isa<ConstantSDNode>(N0))
4195     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4196   // fold (aext (aext x)) -> (aext x)
4197   // fold (aext (zext x)) -> (zext x)
4198   // fold (aext (sext x)) -> (sext x)
4199   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4200       N0.getOpcode() == ISD::ZERO_EXTEND ||
4201       N0.getOpcode() == ISD::SIGN_EXTEND)
4202     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4203
4204   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4205   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4206   if (N0.getOpcode() == ISD::TRUNCATE) {
4207     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4208     if (NarrowLoad.getNode()) {
4209       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4210       if (NarrowLoad.getNode() != N0.getNode()) {
4211         CombineTo(N0.getNode(), NarrowLoad);
4212         // CombineTo deleted the truncate, if needed, but not what's under it.
4213         AddToWorkList(oye);
4214       }
4215       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4216     }
4217   }
4218
4219   // fold (aext (truncate x))
4220   if (N0.getOpcode() == ISD::TRUNCATE) {
4221     SDValue TruncOp = N0.getOperand(0);
4222     if (TruncOp.getValueType() == VT)
4223       return TruncOp; // x iff x size == zext size.
4224     if (TruncOp.getValueType().bitsGT(VT))
4225       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4226     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4227   }
4228
4229   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4230   // if the trunc is not free.
4231   if (N0.getOpcode() == ISD::AND &&
4232       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4233       N0.getOperand(1).getOpcode() == ISD::Constant &&
4234       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4235                           N0.getValueType())) {
4236     SDValue X = N0.getOperand(0).getOperand(0);
4237     if (X.getValueType().bitsLT(VT)) {
4238       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4239     } else if (X.getValueType().bitsGT(VT)) {
4240       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4241     }
4242     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4243     Mask = Mask.zext(VT.getSizeInBits());
4244     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4245                        X, DAG.getConstant(Mask, VT));
4246   }
4247
4248   // fold (aext (load x)) -> (aext (truncate (extload x)))
4249   // None of the supported targets knows how to perform load and any_ext
4250   // on vectors in one instruction.  We only perform this transformation on
4251   // scalars.
4252   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4253       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4254        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4255     bool DoXform = true;
4256     SmallVector<SDNode*, 4> SetCCs;
4257     if (!N0.hasOneUse())
4258       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4259     if (DoXform) {
4260       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4261       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4262                                        LN0->getChain(),
4263                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4264                                        N0.getValueType(),
4265                                        LN0->isVolatile(), LN0->isNonTemporal(),
4266                                        LN0->getAlignment());
4267       CombineTo(N, ExtLoad);
4268       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4269                                   N0.getValueType(), ExtLoad);
4270       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4271       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4272                       ISD::ANY_EXTEND);
4273       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4274     }
4275   }
4276
4277   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4278   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4279   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4280   if (N0.getOpcode() == ISD::LOAD &&
4281       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4282       N0.hasOneUse()) {
4283     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4284     EVT MemVT = LN0->getMemoryVT();
4285     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4286                                      VT, LN0->getChain(), LN0->getBasePtr(),
4287                                      LN0->getPointerInfo(), MemVT,
4288                                      LN0->isVolatile(), LN0->isNonTemporal(),
4289                                      LN0->getAlignment());
4290     CombineTo(N, ExtLoad);
4291     CombineTo(N0.getNode(),
4292               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4293                           N0.getValueType(), ExtLoad),
4294               ExtLoad.getValue(1));
4295     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4296   }
4297
4298   if (N0.getOpcode() == ISD::SETCC) {
4299     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4300     // Only do this before legalize for now.
4301     if (VT.isVector() && !LegalOperations) {
4302       EVT N0VT = N0.getOperand(0).getValueType();
4303         // We know that the # elements of the results is the same as the
4304         // # elements of the compare (and the # elements of the compare result
4305         // for that matter).  Check to see that they are the same size.  If so,
4306         // we know that the element size of the sext'd result matches the
4307         // element size of the compare operands.
4308       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4309         return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4310                              N0.getOperand(1),
4311                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4312       // If the desired elements are smaller or larger than the source
4313       // elements we can use a matching integer vector type and then
4314       // truncate/sign extend
4315       else {
4316         EVT MatchingElementType =
4317           EVT::getIntegerVT(*DAG.getContext(),
4318                             N0VT.getScalarType().getSizeInBits());
4319         EVT MatchingVectorType =
4320           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4321                            N0VT.getVectorNumElements());
4322         SDValue VsetCC =
4323           DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4324                         N0.getOperand(1),
4325                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
4326         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4327       }
4328     }
4329
4330     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4331     SDValue SCC =
4332       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4333                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4334                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4335     if (SCC.getNode())
4336       return SCC;
4337   }
4338
4339   return SDValue();
4340 }
4341
4342 /// GetDemandedBits - See if the specified operand can be simplified with the
4343 /// knowledge that only the bits specified by Mask are used.  If so, return the
4344 /// simpler operand, otherwise return a null SDValue.
4345 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4346   switch (V.getOpcode()) {
4347   default: break;
4348   case ISD::OR:
4349   case ISD::XOR:
4350     // If the LHS or RHS don't contribute bits to the or, drop them.
4351     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4352       return V.getOperand(1);
4353     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4354       return V.getOperand(0);
4355     break;
4356   case ISD::SRL:
4357     // Only look at single-use SRLs.
4358     if (!V.getNode()->hasOneUse())
4359       break;
4360     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4361       // See if we can recursively simplify the LHS.
4362       unsigned Amt = RHSC->getZExtValue();
4363
4364       // Watch out for shift count overflow though.
4365       if (Amt >= Mask.getBitWidth()) break;
4366       APInt NewMask = Mask << Amt;
4367       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4368       if (SimplifyLHS.getNode())
4369         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4370                            SimplifyLHS, V.getOperand(1));
4371     }
4372   }
4373   return SDValue();
4374 }
4375
4376 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4377 /// bits and then truncated to a narrower type and where N is a multiple
4378 /// of number of bits of the narrower type, transform it to a narrower load
4379 /// from address + N / num of bits of new type. If the result is to be
4380 /// extended, also fold the extension to form a extending load.
4381 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4382   unsigned Opc = N->getOpcode();
4383
4384   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4385   SDValue N0 = N->getOperand(0);
4386   EVT VT = N->getValueType(0);
4387   EVT ExtVT = VT;
4388
4389   // This transformation isn't valid for vector loads.
4390   if (VT.isVector())
4391     return SDValue();
4392
4393   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4394   // extended to VT.
4395   if (Opc == ISD::SIGN_EXTEND_INREG) {
4396     ExtType = ISD::SEXTLOAD;
4397     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4398   } else if (Opc == ISD::SRL) {
4399     // Another special-case: SRL is basically zero-extending a narrower value.
4400     ExtType = ISD::ZEXTLOAD;
4401     N0 = SDValue(N, 0);
4402     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4403     if (!N01) return SDValue();
4404     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4405                               VT.getSizeInBits() - N01->getZExtValue());
4406   }
4407   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4408     return SDValue();
4409
4410   unsigned EVTBits = ExtVT.getSizeInBits();
4411
4412   // Do not generate loads of non-round integer types since these can
4413   // be expensive (and would be wrong if the type is not byte sized).
4414   if (!ExtVT.isRound())
4415     return SDValue();
4416
4417   unsigned ShAmt = 0;
4418   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4419     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4420       ShAmt = N01->getZExtValue();
4421       // Is the shift amount a multiple of size of VT?
4422       if ((ShAmt & (EVTBits-1)) == 0) {
4423         N0 = N0.getOperand(0);
4424         // Is the load width a multiple of size of VT?
4425         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4426           return SDValue();
4427       }
4428
4429       // At this point, we must have a load or else we can't do the transform.
4430       if (!isa<LoadSDNode>(N0)) return SDValue();
4431
4432       // If the shift amount is larger than the input type then we're not
4433       // accessing any of the loaded bytes.  If the load was a zextload/extload
4434       // then the result of the shift+trunc is zero/undef (handled elsewhere).
4435       // If the load was a sextload then the result is a splat of the sign bit
4436       // of the extended byte.  This is not worth optimizing for.
4437       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4438         return SDValue();
4439     }
4440   }
4441
4442   // If the load is shifted left (and the result isn't shifted back right),
4443   // we can fold the truncate through the shift.
4444   unsigned ShLeftAmt = 0;
4445   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4446       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4447     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4448       ShLeftAmt = N01->getZExtValue();
4449       N0 = N0.getOperand(0);
4450     }
4451   }
4452
4453   // If we haven't found a load, we can't narrow it.  Don't transform one with
4454   // multiple uses, this would require adding a new load.
4455   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4456       // Don't change the width of a volatile load.
4457       cast<LoadSDNode>(N0)->isVolatile())
4458     return SDValue();
4459
4460   // Verify that we are actually reducing a load width here.
4461   if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
4462     return SDValue();
4463
4464   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4465   EVT PtrType = N0.getOperand(1).getValueType();
4466
4467   // For big endian targets, we need to adjust the offset to the pointer to
4468   // load the correct bytes.
4469   if (TLI.isBigEndian()) {
4470     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4471     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4472     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4473   }
4474
4475   uint64_t PtrOff = ShAmt / 8;
4476   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4477   SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4478                                PtrType, LN0->getBasePtr(),
4479                                DAG.getConstant(PtrOff, PtrType));
4480   AddToWorkList(NewPtr.getNode());
4481
4482   SDValue Load;
4483   if (ExtType == ISD::NON_EXTLOAD)
4484     Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4485                         LN0->getPointerInfo().getWithOffset(PtrOff),
4486                         LN0->isVolatile(), LN0->isNonTemporal(), NewAlign);
4487   else
4488     Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
4489                           LN0->getPointerInfo().getWithOffset(PtrOff),
4490                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4491                           NewAlign);
4492
4493   // Replace the old load's chain with the new load's chain.
4494   WorkListRemover DeadNodes(*this);
4495   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4496                                 &DeadNodes);
4497
4498   // Shift the result left, if we've swallowed a left shift.
4499   SDValue Result = Load;
4500   if (ShLeftAmt != 0) {
4501     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
4502     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4503       ShImmTy = VT;
4504     Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4505                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4506   }
4507
4508   // Return the new loaded value.
4509   return Result;
4510 }
4511
4512 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4513   SDValue N0 = N->getOperand(0);
4514   SDValue N1 = N->getOperand(1);
4515   EVT VT = N->getValueType(0);
4516   EVT EVT = cast<VTSDNode>(N1)->getVT();
4517   unsigned VTBits = VT.getScalarType().getSizeInBits();
4518   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4519
4520   // fold (sext_in_reg c1) -> c1
4521   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4522     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4523
4524   // If the input is already sign extended, just drop the extension.
4525   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4526     return N0;
4527
4528   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4529   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4530       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4531     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4532                        N0.getOperand(0), N1);
4533   }
4534
4535   // fold (sext_in_reg (sext x)) -> (sext x)
4536   // fold (sext_in_reg (aext x)) -> (sext x)
4537   // if x is small enough.
4538   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4539     SDValue N00 = N0.getOperand(0);
4540     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4541         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4542       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4543   }
4544
4545   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4546   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4547     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4548
4549   // fold operands of sext_in_reg based on knowledge that the top bits are not
4550   // demanded.
4551   if (SimplifyDemandedBits(SDValue(N, 0)))
4552     return SDValue(N, 0);
4553
4554   // fold (sext_in_reg (load x)) -> (smaller sextload x)
4555   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4556   SDValue NarrowLoad = ReduceLoadWidth(N);
4557   if (NarrowLoad.getNode())
4558     return NarrowLoad;
4559
4560   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4561   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4562   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4563   if (N0.getOpcode() == ISD::SRL) {
4564     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4565       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4566         // We can turn this into an SRA iff the input to the SRL is already sign
4567         // extended enough.
4568         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4569         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4570           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4571                              N0.getOperand(0), N0.getOperand(1));
4572       }
4573   }
4574
4575   // fold (sext_inreg (extload x)) -> (sextload x)
4576   if (ISD::isEXTLoad(N0.getNode()) &&
4577       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4578       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4579       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4580        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4581     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4582     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4583                                      LN0->getChain(),
4584                                      LN0->getBasePtr(), LN0->getPointerInfo(),
4585                                      EVT,
4586                                      LN0->isVolatile(), LN0->isNonTemporal(),
4587                                      LN0->getAlignment());
4588     CombineTo(N, ExtLoad);
4589     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4590     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4591   }
4592   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4593   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4594       N0.hasOneUse() &&
4595       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4596       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4597        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4598     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4599     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4600                                      LN0->getChain(),
4601                                      LN0->getBasePtr(), LN0->getPointerInfo(),
4602                                      EVT,
4603                                      LN0->isVolatile(), LN0->isNonTemporal(),
4604                                      LN0->getAlignment());
4605     CombineTo(N, ExtLoad);
4606     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4607     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4608   }
4609   return SDValue();
4610 }
4611
4612 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4613   SDValue N0 = N->getOperand(0);
4614   EVT VT = N->getValueType(0);
4615
4616   // noop truncate
4617   if (N0.getValueType() == N->getValueType(0))
4618     return N0;
4619   // fold (truncate c1) -> c1
4620   if (isa<ConstantSDNode>(N0))
4621     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4622   // fold (truncate (truncate x)) -> (truncate x)
4623   if (N0.getOpcode() == ISD::TRUNCATE)
4624     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4625   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4626   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4627       N0.getOpcode() == ISD::SIGN_EXTEND ||
4628       N0.getOpcode() == ISD::ANY_EXTEND) {
4629     if (N0.getOperand(0).getValueType().bitsLT(VT))
4630       // if the source is smaller than the dest, we still need an extend
4631       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4632                          N0.getOperand(0));
4633     else if (N0.getOperand(0).getValueType().bitsGT(VT))
4634       // if the source is larger than the dest, than we just need the truncate
4635       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4636     else
4637       // if the source and dest are the same type, we can drop both the extend
4638       // and the truncate.
4639       return N0.getOperand(0);
4640   }
4641
4642   // See if we can simplify the input to this truncate through knowledge that
4643   // only the low bits are being used.
4644   // For example "trunc (or (shl x, 8), y)" // -> trunc y
4645   // Currently we only perform this optimization on scalars because vectors
4646   // may have different active low bits.
4647   if (!VT.isVector()) {
4648     SDValue Shorter =
4649       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4650                                                VT.getSizeInBits()));
4651     if (Shorter.getNode())
4652       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4653   }
4654   // fold (truncate (load x)) -> (smaller load x)
4655   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4656   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4657     SDValue Reduced = ReduceLoadWidth(N);
4658     if (Reduced.getNode())
4659       return Reduced;
4660   }
4661
4662   // Simplify the operands using demanded-bits information.
4663   if (!VT.isVector() &&
4664       SimplifyDemandedBits(SDValue(N, 0)))
4665     return SDValue(N, 0);
4666
4667   return SDValue();
4668 }
4669
4670 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4671   SDValue Elt = N->getOperand(i);
4672   if (Elt.getOpcode() != ISD::MERGE_VALUES)
4673     return Elt.getNode();
4674   return Elt.getOperand(Elt.getResNo()).getNode();
4675 }
4676
4677 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4678 /// if load locations are consecutive.
4679 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4680   assert(N->getOpcode() == ISD::BUILD_PAIR);
4681
4682   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4683   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4684   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4685       LD1->getPointerInfo().getAddrSpace() !=
4686          LD2->getPointerInfo().getAddrSpace())
4687     return SDValue();
4688   EVT LD1VT = LD1->getValueType(0);
4689
4690   if (ISD::isNON_EXTLoad(LD2) &&
4691       LD2->hasOneUse() &&
4692       // If both are volatile this would reduce the number of volatile loads.
4693       // If one is volatile it might be ok, but play conservative and bail out.
4694       !LD1->isVolatile() &&
4695       !LD2->isVolatile() &&
4696       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4697     unsigned Align = LD1->getAlignment();
4698     unsigned NewAlign = TLI.getTargetData()->
4699       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4700
4701     if (NewAlign <= Align &&
4702         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4703       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4704                          LD1->getBasePtr(), LD1->getPointerInfo(),
4705                          false, false, Align);
4706   }
4707
4708   return SDValue();
4709 }
4710
4711 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
4712   SDValue N0 = N->getOperand(0);
4713   EVT VT = N->getValueType(0);
4714
4715   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4716   // Only do this before legalize, since afterward the target may be depending
4717   // on the bitconvert.
4718   // First check to see if this is all constant.
4719   if (!LegalTypes &&
4720       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4721       VT.isVector()) {
4722     bool isSimple = true;
4723     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4724       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4725           N0.getOperand(i).getOpcode() != ISD::Constant &&
4726           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4727         isSimple = false;
4728         break;
4729       }
4730
4731     EVT DestEltVT = N->getValueType(0).getVectorElementType();
4732     assert(!DestEltVT.isVector() &&
4733            "Element type of vector ValueType must not be vector!");
4734     if (isSimple)
4735       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4736   }
4737
4738   // If the input is a constant, let getNode fold it.
4739   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4740     SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
4741     if (Res.getNode() != N) {
4742       if (!LegalOperations ||
4743           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4744         return Res;
4745
4746       // Folding it resulted in an illegal node, and it's too late to
4747       // do that. Clean up the old node and forego the transformation.
4748       // Ideally this won't happen very often, because instcombine
4749       // and the earlier dagcombine runs (where illegal nodes are
4750       // permitted) should have folded most of them already.
4751       DAG.DeleteNode(Res.getNode());
4752     }
4753   }
4754
4755   // (conv (conv x, t1), t2) -> (conv x, t2)
4756   if (N0.getOpcode() == ISD::BITCAST)
4757     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
4758                        N0.getOperand(0));
4759
4760   // fold (conv (load x)) -> (load (conv*)x)
4761   // If the resultant load doesn't need a higher alignment than the original!
4762   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4763       // Do not change the width of a volatile load.
4764       !cast<LoadSDNode>(N0)->isVolatile() &&
4765       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4766     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4767     unsigned Align = TLI.getTargetData()->
4768       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4769     unsigned OrigAlign = LN0->getAlignment();
4770
4771     if (Align <= OrigAlign) {
4772       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4773                                  LN0->getBasePtr(), LN0->getPointerInfo(),
4774                                  LN0->isVolatile(), LN0->isNonTemporal(),
4775                                  OrigAlign);
4776       AddToWorkList(N);
4777       CombineTo(N0.getNode(),
4778                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4779                             N0.getValueType(), Load),
4780                 Load.getValue(1));
4781       return Load;
4782     }
4783   }
4784
4785   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4786   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4787   // This often reduces constant pool loads.
4788   if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4789       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4790     SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
4791                                   N0.getOperand(0));
4792     AddToWorkList(NewConv.getNode());
4793
4794     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4795     if (N0.getOpcode() == ISD::FNEG)
4796       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4797                          NewConv, DAG.getConstant(SignBit, VT));
4798     assert(N0.getOpcode() == ISD::FABS);
4799     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4800                        NewConv, DAG.getConstant(~SignBit, VT));
4801   }
4802
4803   // fold (bitconvert (fcopysign cst, x)) ->
4804   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
4805   // Note that we don't handle (copysign x, cst) because this can always be
4806   // folded to an fneg or fabs.
4807   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4808       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4809       VT.isInteger() && !VT.isVector()) {
4810     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4811     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4812     if (isTypeLegal(IntXVT)) {
4813       SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4814                               IntXVT, N0.getOperand(1));
4815       AddToWorkList(X.getNode());
4816
4817       // If X has a different width than the result/lhs, sext it or truncate it.
4818       unsigned VTWidth = VT.getSizeInBits();
4819       if (OrigXWidth < VTWidth) {
4820         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4821         AddToWorkList(X.getNode());
4822       } else if (OrigXWidth > VTWidth) {
4823         // To get the sign bit in the right place, we have to shift it right
4824         // before truncating.
4825         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4826                         X.getValueType(), X,
4827                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4828         AddToWorkList(X.getNode());
4829         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4830         AddToWorkList(X.getNode());
4831       }
4832
4833       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4834       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4835                       X, DAG.getConstant(SignBit, VT));
4836       AddToWorkList(X.getNode());
4837
4838       SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4839                                 VT, N0.getOperand(0));
4840       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4841                         Cst, DAG.getConstant(~SignBit, VT));
4842       AddToWorkList(Cst.getNode());
4843
4844       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4845     }
4846   }
4847
4848   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4849   if (N0.getOpcode() == ISD::BUILD_PAIR) {
4850     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4851     if (CombineLD.getNode())
4852       return CombineLD;
4853   }
4854
4855   return SDValue();
4856 }
4857
4858 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4859   EVT VT = N->getValueType(0);
4860   return CombineConsecutiveLoads(N, VT);
4861 }
4862
4863 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
4864 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
4865 /// destination element value type.
4866 SDValue DAGCombiner::
4867 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4868   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4869
4870   // If this is already the right type, we're done.
4871   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4872
4873   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4874   unsigned DstBitSize = DstEltVT.getSizeInBits();
4875
4876   // If this is a conversion of N elements of one type to N elements of another
4877   // type, convert each element.  This handles FP<->INT cases.
4878   if (SrcBitSize == DstBitSize) {
4879     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4880                               BV->getValueType(0).getVectorNumElements());
4881
4882     // Due to the FP element handling below calling this routine recursively,
4883     // we can end up with a scalar-to-vector node here.
4884     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
4885       return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4886                          DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4887                                      DstEltVT, BV->getOperand(0)));
4888
4889     SmallVector<SDValue, 8> Ops;
4890     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4891       SDValue Op = BV->getOperand(i);
4892       // If the vector element type is not legal, the BUILD_VECTOR operands
4893       // are promoted and implicitly truncated.  Make that explicit here.
4894       if (Op.getValueType() != SrcEltVT)
4895         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4896       Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4897                                 DstEltVT, Op));
4898       AddToWorkList(Ops.back().getNode());
4899     }
4900     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4901                        &Ops[0], Ops.size());
4902   }
4903
4904   // Otherwise, we're growing or shrinking the elements.  To avoid having to
4905   // handle annoying details of growing/shrinking FP values, we convert them to
4906   // int first.
4907   if (SrcEltVT.isFloatingPoint()) {
4908     // Convert the input float vector to a int vector where the elements are the
4909     // same sizes.
4910     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4911     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4912     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
4913     SrcEltVT = IntVT;
4914   }
4915
4916   // Now we know the input is an integer vector.  If the output is a FP type,
4917   // convert to integer first, then to FP of the right size.
4918   if (DstEltVT.isFloatingPoint()) {
4919     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4920     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4921     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
4922
4923     // Next, convert to FP elements of the same size.
4924     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
4925   }
4926
4927   // Okay, we know the src/dst types are both integers of differing types.
4928   // Handling growing first.
4929   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4930   if (SrcBitSize < DstBitSize) {
4931     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4932
4933     SmallVector<SDValue, 8> Ops;
4934     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4935          i += NumInputsPerOutput) {
4936       bool isLE = TLI.isLittleEndian();
4937       APInt NewBits = APInt(DstBitSize, 0);
4938       bool EltIsUndef = true;
4939       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4940         // Shift the previously computed bits over.
4941         NewBits <<= SrcBitSize;
4942         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4943         if (Op.getOpcode() == ISD::UNDEF) continue;
4944         EltIsUndef = false;
4945
4946         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
4947                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
4948       }
4949
4950       if (EltIsUndef)
4951         Ops.push_back(DAG.getUNDEF(DstEltVT));
4952       else
4953         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4954     }
4955
4956     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4957     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4958                        &Ops[0], Ops.size());
4959   }
4960
4961   // Finally, this must be the case where we are shrinking elements: each input
4962   // turns into multiple outputs.
4963   bool isS2V = ISD::isScalarToVector(BV);
4964   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4965   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4966                             NumOutputsPerInput*BV->getNumOperands());
4967   SmallVector<SDValue, 8> Ops;
4968
4969   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4970     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4971       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4972         Ops.push_back(DAG.getUNDEF(DstEltVT));
4973       continue;
4974     }
4975
4976     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
4977                   getAPIntValue().zextOrTrunc(SrcBitSize);
4978
4979     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4980       APInt ThisVal = OpVal.trunc(DstBitSize);
4981       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4982       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
4983         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4984         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4985                            Ops[0]);
4986       OpVal = OpVal.lshr(DstBitSize);
4987     }
4988
4989     // For big endian targets, swap the order of the pieces of each element.
4990     if (TLI.isBigEndian())
4991       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4992   }
4993
4994   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4995                      &Ops[0], Ops.size());
4996 }
4997
4998 SDValue DAGCombiner::visitFADD(SDNode *N) {
4999   SDValue N0 = N->getOperand(0);
5000   SDValue N1 = N->getOperand(1);
5001   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5002   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5003   EVT VT = N->getValueType(0);
5004
5005   // fold vector ops
5006   if (VT.isVector()) {
5007     SDValue FoldedVOp = SimplifyVBinOp(N);
5008     if (FoldedVOp.getNode()) return FoldedVOp;
5009   }
5010
5011   // fold (fadd c1, c2) -> (fadd c1, c2)
5012   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5013     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5014   // canonicalize constant to RHS
5015   if (N0CFP && !N1CFP)
5016     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5017   // fold (fadd A, 0) -> A
5018   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
5019     return N0;
5020   // fold (fadd A, (fneg B)) -> (fsub A, B)
5021   if (isNegatibleForFree(N1, LegalOperations) == 2)
5022     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5023                        GetNegatedExpression(N1, DAG, LegalOperations));
5024   // fold (fadd (fneg A), B) -> (fsub B, A)
5025   if (isNegatibleForFree(N0, LegalOperations) == 2)
5026     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5027                        GetNegatedExpression(N0, DAG, LegalOperations));
5028
5029   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5030   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
5031       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5032     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5033                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5034                                    N0.getOperand(1), N1));
5035
5036   return SDValue();
5037 }
5038
5039 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5040   SDValue N0 = N->getOperand(0);
5041   SDValue N1 = N->getOperand(1);
5042   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5043   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5044   EVT VT = N->getValueType(0);
5045
5046   // fold vector ops
5047   if (VT.isVector()) {
5048     SDValue FoldedVOp = SimplifyVBinOp(N);
5049     if (FoldedVOp.getNode()) return FoldedVOp;
5050   }
5051
5052   // fold (fsub c1, c2) -> c1-c2
5053   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5054     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5055   // fold (fsub A, 0) -> A
5056   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
5057     return N0;
5058   // fold (fsub 0, B) -> -B
5059   if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
5060     if (isNegatibleForFree(N1, LegalOperations))
5061       return GetNegatedExpression(N1, DAG, LegalOperations);
5062     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5063       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
5064   }
5065   // fold (fsub A, (fneg B)) -> (fadd A, B)
5066   if (isNegatibleForFree(N1, LegalOperations))
5067     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
5068                        GetNegatedExpression(N1, DAG, LegalOperations));
5069
5070   return SDValue();
5071 }
5072
5073 SDValue DAGCombiner::visitFMUL(SDNode *N) {
5074   SDValue N0 = N->getOperand(0);
5075   SDValue N1 = N->getOperand(1);
5076   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5077   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5078   EVT VT = N->getValueType(0);
5079
5080   // fold vector ops
5081   if (VT.isVector()) {
5082     SDValue FoldedVOp = SimplifyVBinOp(N);
5083     if (FoldedVOp.getNode()) return FoldedVOp;
5084   }
5085
5086   // fold (fmul c1, c2) -> c1*c2
5087   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5088     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5089   // canonicalize constant to RHS
5090   if (N0CFP && !N1CFP)
5091     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5092   // fold (fmul A, 0) -> 0
5093   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
5094     return N1;
5095   // fold (fmul A, 0) -> 0, vector edition.
5096   if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
5097     return N1;
5098   // fold (fmul X, 2.0) -> (fadd X, X)
5099   if (N1CFP && N1CFP->isExactlyValue(+2.0))
5100     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5101   // fold (fmul X, -1.0) -> (fneg X)
5102   if (N1CFP && N1CFP->isExactlyValue(-1.0))
5103     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5104       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5105
5106   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5107   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
5108     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
5109       // Both can be negated for free, check to see if at least one is cheaper
5110       // negated.
5111       if (LHSNeg == 2 || RHSNeg == 2)
5112         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5113                            GetNegatedExpression(N0, DAG, LegalOperations),
5114                            GetNegatedExpression(N1, DAG, LegalOperations));
5115     }
5116   }
5117
5118   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5119   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
5120       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5121     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5122                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5123                                    N0.getOperand(1), N1));
5124
5125   return SDValue();
5126 }
5127
5128 SDValue DAGCombiner::visitFDIV(SDNode *N) {
5129   SDValue N0 = N->getOperand(0);
5130   SDValue N1 = N->getOperand(1);
5131   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5132   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5133   EVT VT = N->getValueType(0);
5134
5135   // fold vector ops
5136   if (VT.isVector()) {
5137     SDValue FoldedVOp = SimplifyVBinOp(N);
5138     if (FoldedVOp.getNode()) return FoldedVOp;
5139   }
5140
5141   // fold (fdiv c1, c2) -> c1/c2
5142   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5143     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5144
5145
5146   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5147   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
5148     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
5149       // Both can be negated for free, check to see if at least one is cheaper
5150       // negated.
5151       if (LHSNeg == 2 || RHSNeg == 2)
5152         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5153                            GetNegatedExpression(N0, DAG, LegalOperations),
5154                            GetNegatedExpression(N1, DAG, LegalOperations));
5155     }
5156   }
5157
5158   return SDValue();
5159 }
5160
5161 SDValue DAGCombiner::visitFREM(SDNode *N) {
5162   SDValue N0 = N->getOperand(0);
5163   SDValue N1 = N->getOperand(1);
5164   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5165   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5166   EVT VT = N->getValueType(0);
5167
5168   // fold (frem c1, c2) -> fmod(c1,c2)
5169   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5170     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5171
5172   return SDValue();
5173 }
5174
5175 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5176   SDValue N0 = N->getOperand(0);
5177   SDValue N1 = N->getOperand(1);
5178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5179   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5180   EVT VT = N->getValueType(0);
5181
5182   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
5183     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5184
5185   if (N1CFP) {
5186     const APFloat& V = N1CFP->getValueAPF();
5187     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
5188     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5189     if (!V.isNegative()) {
5190       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5191         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5192     } else {
5193       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5194         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5195                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5196     }
5197   }
5198
5199   // copysign(fabs(x), y) -> copysign(x, y)
5200   // copysign(fneg(x), y) -> copysign(x, y)
5201   // copysign(copysign(x,z), y) -> copysign(x, y)
5202   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5203       N0.getOpcode() == ISD::FCOPYSIGN)
5204     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5205                        N0.getOperand(0), N1);
5206
5207   // copysign(x, abs(y)) -> abs(x)
5208   if (N1.getOpcode() == ISD::FABS)
5209     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5210
5211   // copysign(x, copysign(y,z)) -> copysign(x, z)
5212   if (N1.getOpcode() == ISD::FCOPYSIGN)
5213     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5214                        N0, N1.getOperand(1));
5215
5216   // copysign(x, fp_extend(y)) -> copysign(x, y)
5217   // copysign(x, fp_round(y)) -> copysign(x, y)
5218   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5219     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5220                        N0, N1.getOperand(0));
5221
5222   return SDValue();
5223 }
5224
5225 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5226   SDValue N0 = N->getOperand(0);
5227   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5228   EVT VT = N->getValueType(0);
5229   EVT OpVT = N0.getValueType();
5230
5231   // fold (sint_to_fp c1) -> c1fp
5232   if (N0C && OpVT != MVT::ppcf128 &&
5233       // ...but only if the target supports immediate floating-point values
5234       (Level == llvm::Unrestricted || TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5235     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5236
5237   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5238   // but UINT_TO_FP is legal on this target, try to convert.
5239   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5240       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5241     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5242     if (DAG.SignBitIsZero(N0))
5243       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5244   }
5245
5246   return SDValue();
5247 }
5248
5249 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5250   SDValue N0 = N->getOperand(0);
5251   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5252   EVT VT = N->getValueType(0);
5253   EVT OpVT = N0.getValueType();
5254
5255   // fold (uint_to_fp c1) -> c1fp
5256   if (N0C && OpVT != MVT::ppcf128 &&
5257       // ...but only if the target supports immediate floating-point values
5258       (Level == llvm::Unrestricted || TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5259     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5260
5261   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5262   // but SINT_TO_FP is legal on this target, try to convert.
5263   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5264       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5265     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5266     if (DAG.SignBitIsZero(N0))
5267       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5268   }
5269
5270   return SDValue();
5271 }
5272
5273 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5274   SDValue N0 = N->getOperand(0);
5275   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5276   EVT VT = N->getValueType(0);
5277
5278   // fold (fp_to_sint c1fp) -> c1
5279   if (N0CFP)
5280     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5281
5282   return SDValue();
5283 }
5284
5285 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5286   SDValue N0 = N->getOperand(0);
5287   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5288   EVT VT = N->getValueType(0);
5289
5290   // fold (fp_to_uint c1fp) -> c1
5291   if (N0CFP && VT != MVT::ppcf128)
5292     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5293
5294   return SDValue();
5295 }
5296
5297 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5298   SDValue N0 = N->getOperand(0);
5299   SDValue N1 = N->getOperand(1);
5300   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5301   EVT VT = N->getValueType(0);
5302
5303   // fold (fp_round c1fp) -> c1fp
5304   if (N0CFP && N0.getValueType() != MVT::ppcf128)
5305     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5306
5307   // fold (fp_round (fp_extend x)) -> x
5308   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5309     return N0.getOperand(0);
5310
5311   // fold (fp_round (fp_round x)) -> (fp_round x)
5312   if (N0.getOpcode() == ISD::FP_ROUND) {
5313     // This is a value preserving truncation if both round's are.
5314     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5315                    N0.getNode()->getConstantOperandVal(1) == 1;
5316     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5317                        DAG.getIntPtrConstant(IsTrunc));
5318   }
5319
5320   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5321   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5322     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5323                               N0.getOperand(0), N1);
5324     AddToWorkList(Tmp.getNode());
5325     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5326                        Tmp, N0.getOperand(1));
5327   }
5328
5329   return SDValue();
5330 }
5331
5332 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5333   SDValue N0 = N->getOperand(0);
5334   EVT VT = N->getValueType(0);
5335   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5336   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5337
5338   // fold (fp_round_inreg c1fp) -> c1fp
5339   if (N0CFP && isTypeLegal(EVT)) {
5340     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5341     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5342   }
5343
5344   return SDValue();
5345 }
5346
5347 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5348   SDValue N0 = N->getOperand(0);
5349   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5350   EVT VT = N->getValueType(0);
5351
5352   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5353   if (N->hasOneUse() &&
5354       N->use_begin()->getOpcode() == ISD::FP_ROUND)
5355     return SDValue();
5356
5357   // fold (fp_extend c1fp) -> c1fp
5358   if (N0CFP && VT != MVT::ppcf128)
5359     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5360
5361   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5362   // value of X.
5363   if (N0.getOpcode() == ISD::FP_ROUND
5364       && N0.getNode()->getConstantOperandVal(1) == 1) {
5365     SDValue In = N0.getOperand(0);
5366     if (In.getValueType() == VT) return In;
5367     if (VT.bitsLT(In.getValueType()))
5368       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5369                          In, N0.getOperand(1));
5370     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5371   }
5372
5373   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5374   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5375       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5376        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5377     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5378     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
5379                                      LN0->getChain(),
5380                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5381                                      N0.getValueType(),
5382                                      LN0->isVolatile(), LN0->isNonTemporal(),
5383                                      LN0->getAlignment());
5384     CombineTo(N, ExtLoad);
5385     CombineTo(N0.getNode(),
5386               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5387                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5388               ExtLoad.getValue(1));
5389     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5390   }
5391
5392   return SDValue();
5393 }
5394
5395 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5396   SDValue N0 = N->getOperand(0);
5397   EVT VT = N->getValueType(0);
5398
5399   if (isNegatibleForFree(N0, LegalOperations))
5400     return GetNegatedExpression(N0, DAG, LegalOperations);
5401
5402   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5403   // constant pool values.
5404   if (N0.getOpcode() == ISD::BITCAST &&
5405       !VT.isVector() &&
5406       N0.getNode()->hasOneUse() &&
5407       N0.getOperand(0).getValueType().isInteger()) {
5408     SDValue Int = N0.getOperand(0);
5409     EVT IntVT = Int.getValueType();
5410     if (IntVT.isInteger() && !IntVT.isVector()) {
5411       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5412               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5413       AddToWorkList(Int.getNode());
5414       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5415                          VT, Int);
5416     }
5417   }
5418
5419   return SDValue();
5420 }
5421
5422 SDValue DAGCombiner::visitFABS(SDNode *N) {
5423   SDValue N0 = N->getOperand(0);
5424   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5425   EVT VT = N->getValueType(0);
5426
5427   // fold (fabs c1) -> fabs(c1)
5428   if (N0CFP && VT != MVT::ppcf128)
5429     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5430   // fold (fabs (fabs x)) -> (fabs x)
5431   if (N0.getOpcode() == ISD::FABS)
5432     return N->getOperand(0);
5433   // fold (fabs (fneg x)) -> (fabs x)
5434   // fold (fabs (fcopysign x, y)) -> (fabs x)
5435   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5436     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5437
5438   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5439   // constant pool values.
5440   if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
5441       N0.getOperand(0).getValueType().isInteger() &&
5442       !N0.getOperand(0).getValueType().isVector()) {
5443     SDValue Int = N0.getOperand(0);
5444     EVT IntVT = Int.getValueType();
5445     if (IntVT.isInteger() && !IntVT.isVector()) {
5446       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5447              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5448       AddToWorkList(Int.getNode());
5449       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5450                          N->getValueType(0), Int);
5451     }
5452   }
5453
5454   return SDValue();
5455 }
5456
5457 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5458   SDValue Chain = N->getOperand(0);
5459   SDValue N1 = N->getOperand(1);
5460   SDValue N2 = N->getOperand(2);
5461
5462   // If N is a constant we could fold this into a fallthrough or unconditional
5463   // branch. However that doesn't happen very often in normal code, because
5464   // Instcombine/SimplifyCFG should have handled the available opportunities.
5465   // If we did this folding here, it would be necessary to update the
5466   // MachineBasicBlock CFG, which is awkward.
5467
5468   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5469   // on the target.
5470   if (N1.getOpcode() == ISD::SETCC &&
5471       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5472     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5473                        Chain, N1.getOperand(2),
5474                        N1.getOperand(0), N1.getOperand(1), N2);
5475   }
5476
5477   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5478       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5479        (N1.getOperand(0).hasOneUse() &&
5480         N1.getOperand(0).getOpcode() == ISD::SRL))) {
5481     SDNode *Trunc = 0;
5482     if (N1.getOpcode() == ISD::TRUNCATE) {
5483       // Look pass the truncate.
5484       Trunc = N1.getNode();
5485       N1 = N1.getOperand(0);
5486     }
5487
5488     // Match this pattern so that we can generate simpler code:
5489     //
5490     //   %a = ...
5491     //   %b = and i32 %a, 2
5492     //   %c = srl i32 %b, 1
5493     //   brcond i32 %c ...
5494     //
5495     // into
5496     //
5497     //   %a = ...
5498     //   %b = and i32 %a, 2
5499     //   %c = setcc eq %b, 0
5500     //   brcond %c ...
5501     //
5502     // This applies only when the AND constant value has one bit set and the
5503     // SRL constant is equal to the log2 of the AND constant. The back-end is
5504     // smart enough to convert the result into a TEST/JMP sequence.
5505     SDValue Op0 = N1.getOperand(0);
5506     SDValue Op1 = N1.getOperand(1);
5507
5508     if (Op0.getOpcode() == ISD::AND &&
5509         Op1.getOpcode() == ISD::Constant) {
5510       SDValue AndOp1 = Op0.getOperand(1);
5511
5512       if (AndOp1.getOpcode() == ISD::Constant) {
5513         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5514
5515         if (AndConst.isPowerOf2() &&
5516             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5517           SDValue SetCC =
5518             DAG.getSetCC(N->getDebugLoc(),
5519                          TLI.getSetCCResultType(Op0.getValueType()),
5520                          Op0, DAG.getConstant(0, Op0.getValueType()),
5521                          ISD::SETNE);
5522
5523           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5524                                           MVT::Other, Chain, SetCC, N2);
5525           // Don't add the new BRCond into the worklist or else SimplifySelectCC
5526           // will convert it back to (X & C1) >> C2.
5527           CombineTo(N, NewBRCond, false);
5528           // Truncate is dead.
5529           if (Trunc) {
5530             removeFromWorkList(Trunc);
5531             DAG.DeleteNode(Trunc);
5532           }
5533           // Replace the uses of SRL with SETCC
5534           WorkListRemover DeadNodes(*this);
5535           DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5536           removeFromWorkList(N1.getNode());
5537           DAG.DeleteNode(N1.getNode());
5538           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5539         }
5540       }
5541     }
5542
5543     if (Trunc)
5544       // Restore N1 if the above transformation doesn't match.
5545       N1 = N->getOperand(1);
5546   }
5547
5548   // Transform br(xor(x, y)) -> br(x != y)
5549   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5550   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5551     SDNode *TheXor = N1.getNode();
5552     SDValue Op0 = TheXor->getOperand(0);
5553     SDValue Op1 = TheXor->getOperand(1);
5554     if (Op0.getOpcode() == Op1.getOpcode()) {
5555       // Avoid missing important xor optimizations.
5556       SDValue Tmp = visitXOR(TheXor);
5557       if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5558         DEBUG(dbgs() << "\nReplacing.8 ";
5559               TheXor->dump(&DAG);
5560               dbgs() << "\nWith: ";
5561               Tmp.getNode()->dump(&DAG);
5562               dbgs() << '\n');
5563         WorkListRemover DeadNodes(*this);
5564         DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5565         removeFromWorkList(TheXor);
5566         DAG.DeleteNode(TheXor);
5567         return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5568                            MVT::Other, Chain, Tmp, N2);
5569       }
5570     }
5571
5572     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5573       bool Equal = false;
5574       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5575         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5576             Op0.getOpcode() == ISD::XOR) {
5577           TheXor = Op0.getNode();
5578           Equal = true;
5579         }
5580
5581       EVT SetCCVT = N1.getValueType();
5582       if (LegalTypes)
5583         SetCCVT = TLI.getSetCCResultType(SetCCVT);
5584       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5585                                    SetCCVT,
5586                                    Op0, Op1,
5587                                    Equal ? ISD::SETEQ : ISD::SETNE);
5588       // Replace the uses of XOR with SETCC
5589       WorkListRemover DeadNodes(*this);
5590       DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5591       removeFromWorkList(N1.getNode());
5592       DAG.DeleteNode(N1.getNode());
5593       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5594                          MVT::Other, Chain, SetCC, N2);
5595     }
5596   }
5597
5598   return SDValue();
5599 }
5600
5601 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5602 //
5603 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5604   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5605   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5606
5607   // If N is a constant we could fold this into a fallthrough or unconditional
5608   // branch. However that doesn't happen very often in normal code, because
5609   // Instcombine/SimplifyCFG should have handled the available opportunities.
5610   // If we did this folding here, it would be necessary to update the
5611   // MachineBasicBlock CFG, which is awkward.
5612
5613   // Use SimplifySetCC to simplify SETCC's.
5614   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5615                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5616                                false);
5617   if (Simp.getNode()) AddToWorkList(Simp.getNode());
5618
5619   // fold to a simpler setcc
5620   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5621     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5622                        N->getOperand(0), Simp.getOperand(2),
5623                        Simp.getOperand(0), Simp.getOperand(1),
5624                        N->getOperand(4));
5625
5626   return SDValue();
5627 }
5628
5629 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5630 /// pre-indexed load / store when the base pointer is an add or subtract
5631 /// and it has other uses besides the load / store. After the
5632 /// transformation, the new indexed load / store has effectively folded
5633 /// the add / subtract in and all of its other uses are redirected to the
5634 /// new load / store.
5635 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5636   if (!LegalOperations)
5637     return false;
5638
5639   bool isLoad = true;
5640   SDValue Ptr;
5641   EVT VT;
5642   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5643     if (LD->isIndexed())
5644       return false;
5645     VT = LD->getMemoryVT();
5646     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5647         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5648       return false;
5649     Ptr = LD->getBasePtr();
5650   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5651     if (ST->isIndexed())
5652       return false;
5653     VT = ST->getMemoryVT();
5654     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5655         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5656       return false;
5657     Ptr = ST->getBasePtr();
5658     isLoad = false;
5659   } else {
5660     return false;
5661   }
5662
5663   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5664   // out.  There is no reason to make this a preinc/predec.
5665   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5666       Ptr.getNode()->hasOneUse())
5667     return false;
5668
5669   // Ask the target to do addressing mode selection.
5670   SDValue BasePtr;
5671   SDValue Offset;
5672   ISD::MemIndexedMode AM = ISD::UNINDEXED;
5673   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5674     return false;
5675   // Don't create a indexed load / store with zero offset.
5676   if (isa<ConstantSDNode>(Offset) &&
5677       cast<ConstantSDNode>(Offset)->isNullValue())
5678     return false;
5679
5680   // Try turning it into a pre-indexed load / store except when:
5681   // 1) The new base ptr is a frame index.
5682   // 2) If N is a store and the new base ptr is either the same as or is a
5683   //    predecessor of the value being stored.
5684   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5685   //    that would create a cycle.
5686   // 4) All uses are load / store ops that use it as old base ptr.
5687
5688   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
5689   // (plus the implicit offset) to a register to preinc anyway.
5690   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5691     return false;
5692
5693   // Check #2.
5694   if (!isLoad) {
5695     SDValue Val = cast<StoreSDNode>(N)->getValue();
5696     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5697       return false;
5698   }
5699
5700   // Now check for #3 and #4.
5701   bool RealUse = false;
5702   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5703          E = Ptr.getNode()->use_end(); I != E; ++I) {
5704     SDNode *Use = *I;
5705     if (Use == N)
5706       continue;
5707     if (Use->isPredecessorOf(N))
5708       return false;
5709
5710     if (!((Use->getOpcode() == ISD::LOAD &&
5711            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5712           (Use->getOpcode() == ISD::STORE &&
5713            cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5714       RealUse = true;
5715   }
5716
5717   if (!RealUse)
5718     return false;
5719
5720   SDValue Result;
5721   if (isLoad)
5722     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5723                                 BasePtr, Offset, AM);
5724   else
5725     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5726                                  BasePtr, Offset, AM);
5727   ++PreIndexedNodes;
5728   ++NodesCombined;
5729   DEBUG(dbgs() << "\nReplacing.4 ";
5730         N->dump(&DAG);
5731         dbgs() << "\nWith: ";
5732         Result.getNode()->dump(&DAG);
5733         dbgs() << '\n');
5734   WorkListRemover DeadNodes(*this);
5735   if (isLoad) {
5736     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5737                                   &DeadNodes);
5738     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5739                                   &DeadNodes);
5740   } else {
5741     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5742                                   &DeadNodes);
5743   }
5744
5745   // Finally, since the node is now dead, remove it from the graph.
5746   DAG.DeleteNode(N);
5747
5748   // Replace the uses of Ptr with uses of the updated base value.
5749   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5750                                 &DeadNodes);
5751   removeFromWorkList(Ptr.getNode());
5752   DAG.DeleteNode(Ptr.getNode());
5753
5754   return true;
5755 }
5756
5757 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5758 /// add / sub of the base pointer node into a post-indexed load / store.
5759 /// The transformation folded the add / subtract into the new indexed
5760 /// load / store effectively and all of its uses are redirected to the
5761 /// new load / store.
5762 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5763   if (!LegalOperations)
5764     return false;
5765
5766   bool isLoad = true;
5767   SDValue Ptr;
5768   EVT VT;
5769   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5770     if (LD->isIndexed())
5771       return false;
5772     VT = LD->getMemoryVT();
5773     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5774         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5775       return false;
5776     Ptr = LD->getBasePtr();
5777   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5778     if (ST->isIndexed())
5779       return false;
5780     VT = ST->getMemoryVT();
5781     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5782         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5783       return false;
5784     Ptr = ST->getBasePtr();
5785     isLoad = false;
5786   } else {
5787     return false;
5788   }
5789
5790   if (Ptr.getNode()->hasOneUse())
5791     return false;
5792
5793   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5794          E = Ptr.getNode()->use_end(); I != E; ++I) {
5795     SDNode *Op = *I;
5796     if (Op == N ||
5797         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5798       continue;
5799
5800     SDValue BasePtr;
5801     SDValue Offset;
5802     ISD::MemIndexedMode AM = ISD::UNINDEXED;
5803     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5804       // Don't create a indexed load / store with zero offset.
5805       if (isa<ConstantSDNode>(Offset) &&
5806           cast<ConstantSDNode>(Offset)->isNullValue())
5807         continue;
5808
5809       // Try turning it into a post-indexed load / store except when
5810       // 1) All uses are load / store ops that use it as base ptr.
5811       // 2) Op must be independent of N, i.e. Op is neither a predecessor
5812       //    nor a successor of N. Otherwise, if Op is folded that would
5813       //    create a cycle.
5814
5815       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5816         continue;
5817
5818       // Check for #1.
5819       bool TryNext = false;
5820       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5821              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5822         SDNode *Use = *II;
5823         if (Use == Ptr.getNode())
5824           continue;
5825
5826         // If all the uses are load / store addresses, then don't do the
5827         // transformation.
5828         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5829           bool RealUse = false;
5830           for (SDNode::use_iterator III = Use->use_begin(),
5831                  EEE = Use->use_end(); III != EEE; ++III) {
5832             SDNode *UseUse = *III;
5833             if (!((UseUse->getOpcode() == ISD::LOAD &&
5834                    cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5835                   (UseUse->getOpcode() == ISD::STORE &&
5836                    cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5837               RealUse = true;
5838           }
5839
5840           if (!RealUse) {
5841             TryNext = true;
5842             break;
5843           }
5844         }
5845       }
5846
5847       if (TryNext)
5848         continue;
5849
5850       // Check for #2
5851       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5852         SDValue Result = isLoad
5853           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5854                                BasePtr, Offset, AM)
5855           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5856                                 BasePtr, Offset, AM);
5857         ++PostIndexedNodes;
5858         ++NodesCombined;
5859         DEBUG(dbgs() << "\nReplacing.5 ";
5860               N->dump(&DAG);
5861               dbgs() << "\nWith: ";
5862               Result.getNode()->dump(&DAG);
5863               dbgs() << '\n');
5864         WorkListRemover DeadNodes(*this);
5865         if (isLoad) {
5866           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5867                                         &DeadNodes);
5868           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5869                                         &DeadNodes);
5870         } else {
5871           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5872                                         &DeadNodes);
5873         }
5874
5875         // Finally, since the node is now dead, remove it from the graph.
5876         DAG.DeleteNode(N);
5877
5878         // Replace the uses of Use with uses of the updated base value.
5879         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5880                                       Result.getValue(isLoad ? 1 : 0),
5881                                       &DeadNodes);
5882         removeFromWorkList(Op);
5883         DAG.DeleteNode(Op);
5884         return true;
5885       }
5886     }
5887   }
5888
5889   return false;
5890 }
5891
5892 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5893   LoadSDNode *LD  = cast<LoadSDNode>(N);
5894   SDValue Chain = LD->getChain();
5895   SDValue Ptr   = LD->getBasePtr();
5896
5897   // If load is not volatile and there are no uses of the loaded value (and
5898   // the updated indexed value in case of indexed loads), change uses of the
5899   // chain value into uses of the chain input (i.e. delete the dead load).
5900   if (!LD->isVolatile()) {
5901     if (N->getValueType(1) == MVT::Other) {
5902       // Unindexed loads.
5903       if (N->hasNUsesOfValue(0, 0)) {
5904         // It's not safe to use the two value CombineTo variant here. e.g.
5905         // v1, chain2 = load chain1, loc
5906         // v2, chain3 = load chain2, loc
5907         // v3         = add v2, c
5908         // Now we replace use of chain2 with chain1.  This makes the second load
5909         // isomorphic to the one we are deleting, and thus makes this load live.
5910         DEBUG(dbgs() << "\nReplacing.6 ";
5911               N->dump(&DAG);
5912               dbgs() << "\nWith chain: ";
5913               Chain.getNode()->dump(&DAG);
5914               dbgs() << "\n");
5915         WorkListRemover DeadNodes(*this);
5916         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5917
5918         if (N->use_empty()) {
5919           removeFromWorkList(N);
5920           DAG.DeleteNode(N);
5921         }
5922
5923         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5924       }
5925     } else {
5926       // Indexed loads.
5927       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5928       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5929         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5930         DEBUG(dbgs() << "\nReplacing.7 ";
5931               N->dump(&DAG);
5932               dbgs() << "\nWith: ";
5933               Undef.getNode()->dump(&DAG);
5934               dbgs() << " and 2 other values\n");
5935         WorkListRemover DeadNodes(*this);
5936         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5937         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5938                                       DAG.getUNDEF(N->getValueType(1)),
5939                                       &DeadNodes);
5940         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5941         removeFromWorkList(N);
5942         DAG.DeleteNode(N);
5943         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5944       }
5945     }
5946   }
5947
5948   // If this load is directly stored, replace the load value with the stored
5949   // value.
5950   // TODO: Handle store large -> read small portion.
5951   // TODO: Handle TRUNCSTORE/LOADEXT
5952   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
5953     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5954       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5955       if (PrevST->getBasePtr() == Ptr &&
5956           PrevST->getValue().getValueType() == N->getValueType(0))
5957       return CombineTo(N, Chain.getOperand(1), Chain);
5958     }
5959   }
5960
5961   // Try to infer better alignment information than the load already has.
5962   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5963     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5964       if (Align > LD->getAlignment())
5965         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
5966                               LD->getValueType(0),
5967                               Chain, Ptr, LD->getPointerInfo(),
5968                               LD->getMemoryVT(),
5969                               LD->isVolatile(), LD->isNonTemporal(), Align);
5970     }
5971   }
5972
5973   if (CombinerAA) {
5974     // Walk up chain skipping non-aliasing memory nodes.
5975     SDValue BetterChain = FindBetterChain(N, Chain);
5976
5977     // If there is a better chain.
5978     if (Chain != BetterChain) {
5979       SDValue ReplLoad;
5980
5981       // Replace the chain to void dependency.
5982       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5983         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5984                                BetterChain, Ptr, LD->getPointerInfo(),
5985                                LD->isVolatile(), LD->isNonTemporal(),
5986                                LD->getAlignment());
5987       } else {
5988         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5989                                   LD->getValueType(0),
5990                                   BetterChain, Ptr, LD->getPointerInfo(),
5991                                   LD->getMemoryVT(),
5992                                   LD->isVolatile(),
5993                                   LD->isNonTemporal(),
5994                                   LD->getAlignment());
5995       }
5996
5997       // Create token factor to keep old chain connected.
5998       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5999                                   MVT::Other, Chain, ReplLoad.getValue(1));
6000
6001       // Make sure the new and old chains are cleaned up.
6002       AddToWorkList(Token.getNode());
6003
6004       // Replace uses with load result and token factor. Don't add users
6005       // to work list.
6006       return CombineTo(N, ReplLoad.getValue(0), Token, false);
6007     }
6008   }
6009
6010   // Try transforming N to an indexed load.
6011   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6012     return SDValue(N, 0);
6013
6014   return SDValue();
6015 }
6016
6017 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
6018 /// load is having specific bytes cleared out.  If so, return the byte size
6019 /// being masked out and the shift amount.
6020 static std::pair<unsigned, unsigned>
6021 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
6022   std::pair<unsigned, unsigned> Result(0, 0);
6023
6024   // Check for the structure we're looking for.
6025   if (V->getOpcode() != ISD::AND ||
6026       !isa<ConstantSDNode>(V->getOperand(1)) ||
6027       !ISD::isNormalLoad(V->getOperand(0).getNode()))
6028     return Result;
6029
6030   // Check the chain and pointer.
6031   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
6032   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
6033
6034   // The store should be chained directly to the load or be an operand of a
6035   // tokenfactor.
6036   if (LD == Chain.getNode())
6037     ; // ok.
6038   else if (Chain->getOpcode() != ISD::TokenFactor)
6039     return Result; // Fail.
6040   else {
6041     bool isOk = false;
6042     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
6043       if (Chain->getOperand(i).getNode() == LD) {
6044         isOk = true;
6045         break;
6046       }
6047     if (!isOk) return Result;
6048   }
6049
6050   // This only handles simple types.
6051   if (V.getValueType() != MVT::i16 &&
6052       V.getValueType() != MVT::i32 &&
6053       V.getValueType() != MVT::i64)
6054     return Result;
6055
6056   // Check the constant mask.  Invert it so that the bits being masked out are
6057   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
6058   // follow the sign bit for uniformity.
6059   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
6060   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
6061   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
6062   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
6063   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
6064   if (NotMaskLZ == 64) return Result;  // All zero mask.
6065
6066   // See if we have a continuous run of bits.  If so, we have 0*1+0*
6067   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
6068     return Result;
6069
6070   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
6071   if (V.getValueType() != MVT::i64 && NotMaskLZ)
6072     NotMaskLZ -= 64-V.getValueSizeInBits();
6073
6074   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
6075   switch (MaskedBytes) {
6076   case 1:
6077   case 2:
6078   case 4: break;
6079   default: return Result; // All one mask, or 5-byte mask.
6080   }
6081
6082   // Verify that the first bit starts at a multiple of mask so that the access
6083   // is aligned the same as the access width.
6084   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
6085
6086   Result.first = MaskedBytes;
6087   Result.second = NotMaskTZ/8;
6088   return Result;
6089 }
6090
6091
6092 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6093 /// provides a value as specified by MaskInfo.  If so, replace the specified
6094 /// store with a narrower store of truncated IVal.
6095 static SDNode *
6096 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6097                                 SDValue IVal, StoreSDNode *St,
6098                                 DAGCombiner *DC) {
6099   unsigned NumBytes = MaskInfo.first;
6100   unsigned ByteShift = MaskInfo.second;
6101   SelectionDAG &DAG = DC->getDAG();
6102
6103   // Check to see if IVal is all zeros in the part being masked in by the 'or'
6104   // that uses this.  If not, this is not a replacement.
6105   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
6106                                   ByteShift*8, (ByteShift+NumBytes)*8);
6107   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
6108
6109   // Check that it is legal on the target to do this.  It is legal if the new
6110   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
6111   // legalization.
6112   MVT VT = MVT::getIntegerVT(NumBytes*8);
6113   if (!DC->isTypeLegal(VT))
6114     return 0;
6115
6116   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
6117   // shifted by ByteShift and truncated down to NumBytes.
6118   if (ByteShift)
6119     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
6120                        DAG.getConstant(ByteShift*8,
6121                                     DC->getShiftAmountTy(IVal.getValueType())));
6122
6123   // Figure out the offset for the store and the alignment of the access.
6124   unsigned StOffset;
6125   unsigned NewAlign = St->getAlignment();
6126
6127   if (DAG.getTargetLoweringInfo().isLittleEndian())
6128     StOffset = ByteShift;
6129   else
6130     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
6131
6132   SDValue Ptr = St->getBasePtr();
6133   if (StOffset) {
6134     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
6135                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
6136     NewAlign = MinAlign(NewAlign, StOffset);
6137   }
6138
6139   // Truncate down to the new size.
6140   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
6141
6142   ++OpsNarrowed;
6143   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
6144                       St->getPointerInfo().getWithOffset(StOffset),
6145                       false, false, NewAlign).getNode();
6146 }
6147
6148
6149 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
6150 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
6151 /// of the loaded bits, try narrowing the load and store if it would end up
6152 /// being a win for performance or code size.
6153 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
6154   StoreSDNode *ST  = cast<StoreSDNode>(N);
6155   if (ST->isVolatile())
6156     return SDValue();
6157
6158   SDValue Chain = ST->getChain();
6159   SDValue Value = ST->getValue();
6160   SDValue Ptr   = ST->getBasePtr();
6161   EVT VT = Value.getValueType();
6162
6163   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6164     return SDValue();
6165
6166   unsigned Opc = Value.getOpcode();
6167
6168   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6169   // is a byte mask indicating a consecutive number of bytes, check to see if
6170   // Y is known to provide just those bytes.  If so, we try to replace the
6171   // load + replace + store sequence with a single (narrower) store, which makes
6172   // the load dead.
6173   if (Opc == ISD::OR) {
6174     std::pair<unsigned, unsigned> MaskedLoad;
6175     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6176     if (MaskedLoad.first)
6177       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6178                                                   Value.getOperand(1), ST,this))
6179         return SDValue(NewST, 0);
6180
6181     // Or is commutative, so try swapping X and Y.
6182     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6183     if (MaskedLoad.first)
6184       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6185                                                   Value.getOperand(0), ST,this))
6186         return SDValue(NewST, 0);
6187   }
6188
6189   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6190       Value.getOperand(1).getOpcode() != ISD::Constant)
6191     return SDValue();
6192
6193   SDValue N0 = Value.getOperand(0);
6194   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6195       Chain == SDValue(N0.getNode(), 1)) {
6196     LoadSDNode *LD = cast<LoadSDNode>(N0);
6197     if (LD->getBasePtr() != Ptr ||
6198         LD->getPointerInfo().getAddrSpace() !=
6199         ST->getPointerInfo().getAddrSpace())
6200       return SDValue();
6201
6202     // Find the type to narrow it the load / op / store to.
6203     SDValue N1 = Value.getOperand(1);
6204     unsigned BitWidth = N1.getValueSizeInBits();
6205     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6206     if (Opc == ISD::AND)
6207       Imm ^= APInt::getAllOnesValue(BitWidth);
6208     if (Imm == 0 || Imm.isAllOnesValue())
6209       return SDValue();
6210     unsigned ShAmt = Imm.countTrailingZeros();
6211     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6212     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6213     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6214     while (NewBW < BitWidth &&
6215            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6216              TLI.isNarrowingProfitable(VT, NewVT))) {
6217       NewBW = NextPowerOf2(NewBW);
6218       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6219     }
6220     if (NewBW >= BitWidth)
6221       return SDValue();
6222
6223     // If the lsb changed does not start at the type bitwidth boundary,
6224     // start at the previous one.
6225     if (ShAmt % NewBW)
6226       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6227     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6228     if ((Imm & Mask) == Imm) {
6229       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6230       if (Opc == ISD::AND)
6231         NewImm ^= APInt::getAllOnesValue(NewBW);
6232       uint64_t PtrOff = ShAmt / 8;
6233       // For big endian targets, we need to adjust the offset to the pointer to
6234       // load the correct bytes.
6235       if (TLI.isBigEndian())
6236         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6237
6238       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6239       const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6240       if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6241         return SDValue();
6242
6243       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6244                                    Ptr.getValueType(), Ptr,
6245                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
6246       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6247                                   LD->getChain(), NewPtr,
6248                                   LD->getPointerInfo().getWithOffset(PtrOff),
6249                                   LD->isVolatile(), LD->isNonTemporal(),
6250                                   NewAlign);
6251       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6252                                    DAG.getConstant(NewImm, NewVT));
6253       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6254                                    NewVal, NewPtr,
6255                                    ST->getPointerInfo().getWithOffset(PtrOff),
6256                                    false, false, NewAlign);
6257
6258       AddToWorkList(NewPtr.getNode());
6259       AddToWorkList(NewLD.getNode());
6260       AddToWorkList(NewVal.getNode());
6261       WorkListRemover DeadNodes(*this);
6262       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
6263                                     &DeadNodes);
6264       ++OpsNarrowed;
6265       return NewST;
6266     }
6267   }
6268
6269   return SDValue();
6270 }
6271
6272 /// TransformFPLoadStorePair - For a given floating point load / store pair,
6273 /// if the load value isn't used by any other operations, then consider
6274 /// transforming the pair to integer load / store operations if the target
6275 /// deems the transformation profitable.
6276 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
6277   StoreSDNode *ST  = cast<StoreSDNode>(N);
6278   SDValue Chain = ST->getChain();
6279   SDValue Value = ST->getValue();
6280   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
6281       Value.hasOneUse() &&
6282       Chain == SDValue(Value.getNode(), 1)) {
6283     LoadSDNode *LD = cast<LoadSDNode>(Value);
6284     EVT VT = LD->getMemoryVT();
6285     if (!VT.isFloatingPoint() ||
6286         VT != ST->getMemoryVT() ||
6287         LD->isNonTemporal() ||
6288         ST->isNonTemporal() ||
6289         LD->getPointerInfo().getAddrSpace() != 0 ||
6290         ST->getPointerInfo().getAddrSpace() != 0)
6291       return SDValue();
6292
6293     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6294     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
6295         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
6296         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
6297         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
6298       return SDValue();
6299
6300     unsigned LDAlign = LD->getAlignment();
6301     unsigned STAlign = ST->getAlignment();
6302     const Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
6303     unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
6304     if (LDAlign < ABIAlign || STAlign < ABIAlign)
6305       return SDValue();
6306
6307     SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
6308                                 LD->getChain(), LD->getBasePtr(),
6309                                 LD->getPointerInfo(),
6310                                 false, false, LDAlign);
6311
6312     SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
6313                                  NewLD, ST->getBasePtr(),
6314                                  ST->getPointerInfo(),
6315                                  false, false, STAlign);
6316
6317     AddToWorkList(NewLD.getNode());
6318     AddToWorkList(NewST.getNode());
6319     WorkListRemover DeadNodes(*this);
6320     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1),
6321                                   &DeadNodes);
6322     ++LdStFP2Int;
6323     return NewST;
6324   }
6325
6326   return SDValue();
6327 }
6328
6329 SDValue DAGCombiner::visitSTORE(SDNode *N) {
6330   StoreSDNode *ST  = cast<StoreSDNode>(N);
6331   SDValue Chain = ST->getChain();
6332   SDValue Value = ST->getValue();
6333   SDValue Ptr   = ST->getBasePtr();
6334
6335   // If this is a store of a bit convert, store the input value if the
6336   // resultant store does not need a higher alignment than the original.
6337   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
6338       ST->isUnindexed()) {
6339     unsigned OrigAlign = ST->getAlignment();
6340     EVT SVT = Value.getOperand(0).getValueType();
6341     unsigned Align = TLI.getTargetData()->
6342       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
6343     if (Align <= OrigAlign &&
6344         ((!LegalOperations && !ST->isVolatile()) ||
6345          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
6346       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6347                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
6348                           ST->isNonTemporal(), OrigAlign);
6349   }
6350
6351   // Turn 'store undef, Ptr' -> nothing.
6352   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
6353     return Chain;
6354
6355   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
6356   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
6357     // NOTE: If the original store is volatile, this transform must not increase
6358     // the number of stores.  For example, on x86-32 an f64 can be stored in one
6359     // processor operation but an i64 (which is not legal) requires two.  So the
6360     // transform should not be done in this case.
6361     if (Value.getOpcode() != ISD::TargetConstantFP) {
6362       SDValue Tmp;
6363       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
6364       default: llvm_unreachable("Unknown FP type");
6365       case MVT::f80:    // We don't do this for these yet.
6366       case MVT::f128:
6367       case MVT::ppcf128:
6368         break;
6369       case MVT::f32:
6370         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
6371             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6372           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
6373                               bitcastToAPInt().getZExtValue(), MVT::i32);
6374           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6375                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
6376                               ST->isNonTemporal(), ST->getAlignment());
6377         }
6378         break;
6379       case MVT::f64:
6380         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
6381              !ST->isVolatile()) ||
6382             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
6383           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6384                                 getZExtValue(), MVT::i64);
6385           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6386                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
6387                               ST->isNonTemporal(), ST->getAlignment());
6388         }
6389
6390         if (!ST->isVolatile() &&
6391             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6392           // Many FP stores are not made apparent until after legalize, e.g. for
6393           // argument passing.  Since this is so common, custom legalize the
6394           // 64-bit integer store into two 32-bit stores.
6395           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
6396           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6397           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6398           if (TLI.isBigEndian()) std::swap(Lo, Hi);
6399
6400           unsigned Alignment = ST->getAlignment();
6401           bool isVolatile = ST->isVolatile();
6402           bool isNonTemporal = ST->isNonTemporal();
6403
6404           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6405                                      Ptr, ST->getPointerInfo(),
6406                                      isVolatile, isNonTemporal,
6407                                      ST->getAlignment());
6408           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6409                             DAG.getConstant(4, Ptr.getValueType()));
6410           Alignment = MinAlign(Alignment, 4U);
6411           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6412                                      Ptr, ST->getPointerInfo().getWithOffset(4),
6413                                      isVolatile, isNonTemporal,
6414                                      Alignment);
6415           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6416                              St0, St1);
6417         }
6418
6419         break;
6420       }
6421     }
6422   }
6423
6424   // Try to infer better alignment information than the store already has.
6425   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6426     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6427       if (Align > ST->getAlignment())
6428         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6429                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6430                                  ST->isVolatile(), ST->isNonTemporal(), Align);
6431     }
6432   }
6433
6434   // Try transforming a pair floating point load / store ops to integer
6435   // load / store ops.
6436   SDValue NewST = TransformFPLoadStorePair(N);
6437   if (NewST.getNode())
6438     return NewST;
6439
6440   if (CombinerAA) {
6441     // Walk up chain skipping non-aliasing memory nodes.
6442     SDValue BetterChain = FindBetterChain(N, Chain);
6443
6444     // If there is a better chain.
6445     if (Chain != BetterChain) {
6446       SDValue ReplStore;
6447
6448       // Replace the chain to avoid dependency.
6449       if (ST->isTruncatingStore()) {
6450         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6451                                       ST->getPointerInfo(),
6452                                       ST->getMemoryVT(), ST->isVolatile(),
6453                                       ST->isNonTemporal(), ST->getAlignment());
6454       } else {
6455         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6456                                  ST->getPointerInfo(),
6457                                  ST->isVolatile(), ST->isNonTemporal(),
6458                                  ST->getAlignment());
6459       }
6460
6461       // Create token to keep both nodes around.
6462       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6463                                   MVT::Other, Chain, ReplStore);
6464
6465       // Make sure the new and old chains are cleaned up.
6466       AddToWorkList(Token.getNode());
6467
6468       // Don't add users to work list.
6469       return CombineTo(N, Token, false);
6470     }
6471   }
6472
6473   // Try transforming N to an indexed store.
6474   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6475     return SDValue(N, 0);
6476
6477   // FIXME: is there such a thing as a truncating indexed store?
6478   if (ST->isTruncatingStore() && ST->isUnindexed() &&
6479       Value.getValueType().isInteger()) {
6480     // See if we can simplify the input to this truncstore with knowledge that
6481     // only the low bits are being used.  For example:
6482     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
6483     SDValue Shorter =
6484       GetDemandedBits(Value,
6485                       APInt::getLowBitsSet(
6486                         Value.getValueType().getScalarType().getSizeInBits(),
6487                         ST->getMemoryVT().getScalarType().getSizeInBits()));
6488     AddToWorkList(Value.getNode());
6489     if (Shorter.getNode())
6490       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6491                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6492                                ST->isVolatile(), ST->isNonTemporal(),
6493                                ST->getAlignment());
6494
6495     // Otherwise, see if we can simplify the operation with
6496     // SimplifyDemandedBits, which only works if the value has a single use.
6497     if (SimplifyDemandedBits(Value,
6498                         APInt::getLowBitsSet(
6499                           Value.getValueType().getScalarType().getSizeInBits(),
6500                           ST->getMemoryVT().getScalarType().getSizeInBits())))
6501       return SDValue(N, 0);
6502   }
6503
6504   // If this is a load followed by a store to the same location, then the store
6505   // is dead/noop.
6506   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6507     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6508         ST->isUnindexed() && !ST->isVolatile() &&
6509         // There can't be any side effects between the load and store, such as
6510         // a call or store.
6511         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6512       // The store is dead, remove it.
6513       return Chain;
6514     }
6515   }
6516
6517   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6518   // truncating store.  We can do this even if this is already a truncstore.
6519   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6520       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6521       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6522                             ST->getMemoryVT())) {
6523     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6524                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6525                              ST->isVolatile(), ST->isNonTemporal(),
6526                              ST->getAlignment());
6527   }
6528
6529   return ReduceLoadOpStoreWidth(N);
6530 }
6531
6532 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6533   SDValue InVec = N->getOperand(0);
6534   SDValue InVal = N->getOperand(1);
6535   SDValue EltNo = N->getOperand(2);
6536
6537   // If the inserted element is an UNDEF, just use the input vector.
6538   if (InVal.getOpcode() == ISD::UNDEF)
6539     return InVec;
6540
6541   EVT VT = InVec.getValueType();
6542
6543   // If we can't generate a legal BUILD_VECTOR, exit
6544   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
6545     return SDValue();
6546
6547   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
6548   // vector with the inserted element.
6549   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
6550     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6551     SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
6552                                 InVec.getNode()->op_end());
6553     if (Elt < Ops.size())
6554       Ops[Elt] = InVal;
6555     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6556                        VT, &Ops[0], Ops.size());
6557   }
6558   // If the invec is an UNDEF and if EltNo is a constant, create a new
6559   // BUILD_VECTOR with undef elements and the inserted element.
6560   if (InVec.getOpcode() == ISD::UNDEF &&
6561       isa<ConstantSDNode>(EltNo)) {
6562     EVT EltVT = VT.getVectorElementType();
6563     unsigned NElts = VT.getVectorNumElements();
6564     SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
6565
6566     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6567     if (Elt < Ops.size())
6568       Ops[Elt] = InVal;
6569     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6570                        VT, &Ops[0], Ops.size());
6571   }
6572   return SDValue();
6573 }
6574
6575 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6576   // (vextract (scalar_to_vector val, 0) -> val
6577   SDValue InVec = N->getOperand(0);
6578
6579   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6580     // Check if the result type doesn't match the inserted element type. A
6581     // SCALAR_TO_VECTOR may truncate the inserted element and the
6582     // EXTRACT_VECTOR_ELT may widen the extracted vector.
6583     SDValue InOp = InVec.getOperand(0);
6584     EVT NVT = N->getValueType(0);
6585     if (InOp.getValueType() != NVT) {
6586       assert(InOp.getValueType().isInteger() && NVT.isInteger());
6587       return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6588     }
6589     return InOp;
6590   }
6591
6592   // Perform only after legalization to ensure build_vector / vector_shuffle
6593   // optimizations have already been done.
6594   if (!LegalOperations) return SDValue();
6595
6596   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6597   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6598   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6599   SDValue EltNo = N->getOperand(1);
6600
6601   if (isa<ConstantSDNode>(EltNo)) {
6602     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6603     bool NewLoad = false;
6604     bool BCNumEltsChanged = false;
6605     EVT VT = InVec.getValueType();
6606     EVT ExtVT = VT.getVectorElementType();
6607     EVT LVT = ExtVT;
6608
6609     if (InVec.getOpcode() == ISD::BITCAST) {
6610       EVT BCVT = InVec.getOperand(0).getValueType();
6611       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6612         return SDValue();
6613       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6614         BCNumEltsChanged = true;
6615       InVec = InVec.getOperand(0);
6616       ExtVT = BCVT.getVectorElementType();
6617       NewLoad = true;
6618     }
6619
6620     LoadSDNode *LN0 = NULL;
6621     const ShuffleVectorSDNode *SVN = NULL;
6622     if (ISD::isNormalLoad(InVec.getNode())) {
6623       LN0 = cast<LoadSDNode>(InVec);
6624     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6625                InVec.getOperand(0).getValueType() == ExtVT &&
6626                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6627       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6628     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6629       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6630       // =>
6631       // (load $addr+1*size)
6632
6633       // If the bit convert changed the number of elements, it is unsafe
6634       // to examine the mask.
6635       if (BCNumEltsChanged)
6636         return SDValue();
6637
6638       // Select the input vector, guarding against out of range extract vector.
6639       unsigned NumElems = VT.getVectorNumElements();
6640       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6641       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6642
6643       if (InVec.getOpcode() == ISD::BITCAST)
6644         InVec = InVec.getOperand(0);
6645       if (ISD::isNormalLoad(InVec.getNode())) {
6646         LN0 = cast<LoadSDNode>(InVec);
6647         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6648       }
6649     }
6650
6651     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
6652       return SDValue();
6653
6654     // If Idx was -1 above, Elt is going to be -1, so just return undef.
6655     if (Elt == -1)
6656       return DAG.getUNDEF(LN0->getBasePtr().getValueType());
6657
6658     unsigned Align = LN0->getAlignment();
6659     if (NewLoad) {
6660       // Check the resultant load doesn't need a higher alignment than the
6661       // original load.
6662       unsigned NewAlign =
6663         TLI.getTargetData()
6664             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6665
6666       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6667         return SDValue();
6668
6669       Align = NewAlign;
6670     }
6671
6672     SDValue NewPtr = LN0->getBasePtr();
6673     unsigned PtrOff = 0;
6674
6675     if (Elt) {
6676       PtrOff = LVT.getSizeInBits() * Elt / 8;
6677       EVT PtrType = NewPtr.getValueType();
6678       if (TLI.isBigEndian())
6679         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6680       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6681                            DAG.getConstant(PtrOff, PtrType));
6682     }
6683
6684     return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6685                        LN0->getPointerInfo().getWithOffset(PtrOff),
6686                        LN0->isVolatile(), LN0->isNonTemporal(), Align);
6687   }
6688
6689   return SDValue();
6690 }
6691
6692 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6693   unsigned NumInScalars = N->getNumOperands();
6694   EVT VT = N->getValueType(0);
6695
6696   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6697   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6698   // at most two distinct vectors, turn this into a shuffle node.
6699   SDValue VecIn1, VecIn2;
6700   for (unsigned i = 0; i != NumInScalars; ++i) {
6701     // Ignore undef inputs.
6702     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6703
6704     // If this input is something other than a EXTRACT_VECTOR_ELT with a
6705     // constant index, bail out.
6706     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6707         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6708       VecIn1 = VecIn2 = SDValue(0, 0);
6709       break;
6710     }
6711
6712     // If the input vector type disagrees with the result of the build_vector,
6713     // we can't make a shuffle.
6714     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6715     if (ExtractedFromVec.getValueType() != VT) {
6716       VecIn1 = VecIn2 = SDValue(0, 0);
6717       break;
6718     }
6719
6720     // Otherwise, remember this.  We allow up to two distinct input vectors.
6721     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6722       continue;
6723
6724     if (VecIn1.getNode() == 0) {
6725       VecIn1 = ExtractedFromVec;
6726     } else if (VecIn2.getNode() == 0) {
6727       VecIn2 = ExtractedFromVec;
6728     } else {
6729       // Too many inputs.
6730       VecIn1 = VecIn2 = SDValue(0, 0);
6731       break;
6732     }
6733   }
6734
6735   // If everything is good, we can make a shuffle operation.
6736   if (VecIn1.getNode()) {
6737     SmallVector<int, 8> Mask;
6738     for (unsigned i = 0; i != NumInScalars; ++i) {
6739       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6740         Mask.push_back(-1);
6741         continue;
6742       }
6743
6744       // If extracting from the first vector, just use the index directly.
6745       SDValue Extract = N->getOperand(i);
6746       SDValue ExtVal = Extract.getOperand(1);
6747       if (Extract.getOperand(0) == VecIn1) {
6748         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6749         if (ExtIndex > VT.getVectorNumElements())
6750           return SDValue();
6751
6752         Mask.push_back(ExtIndex);
6753         continue;
6754       }
6755
6756       // Otherwise, use InIdx + VecSize
6757       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6758       Mask.push_back(Idx+NumInScalars);
6759     }
6760
6761     // Add count and size info.
6762     if (!isTypeLegal(VT))
6763       return SDValue();
6764
6765     // Return the new VECTOR_SHUFFLE node.
6766     SDValue Ops[2];
6767     Ops[0] = VecIn1;
6768     Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6769     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6770   }
6771
6772   return SDValue();
6773 }
6774
6775 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6776   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6777   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
6778   // inputs come from at most two distinct vectors, turn this into a shuffle
6779   // node.
6780
6781   // If we only have one input vector, we don't need to do any concatenation.
6782   if (N->getNumOperands() == 1)
6783     return N->getOperand(0);
6784
6785   return SDValue();
6786 }
6787
6788 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6789   EVT VT = N->getValueType(0);
6790   unsigned NumElts = VT.getVectorNumElements();
6791
6792   SDValue N0 = N->getOperand(0);
6793
6794   assert(N0.getValueType().getVectorNumElements() == NumElts &&
6795         "Vector shuffle must be normalized in DAG");
6796
6797   // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6798
6799   // If it is a splat, check if the argument vector is another splat or a
6800   // build_vector with all scalar elements the same.
6801   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6802   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
6803     SDNode *V = N0.getNode();
6804
6805     // If this is a bit convert that changes the element type of the vector but
6806     // not the number of vector elements, look through it.  Be careful not to
6807     // look though conversions that change things like v4f32 to v2f64.
6808     if (V->getOpcode() == ISD::BITCAST) {
6809       SDValue ConvInput = V->getOperand(0);
6810       if (ConvInput.getValueType().isVector() &&
6811           ConvInput.getValueType().getVectorNumElements() == NumElts)
6812         V = ConvInput.getNode();
6813     }
6814
6815     if (V->getOpcode() == ISD::BUILD_VECTOR) {
6816       assert(V->getNumOperands() == NumElts &&
6817              "BUILD_VECTOR has wrong number of operands");
6818       SDValue Base;
6819       bool AllSame = true;
6820       for (unsigned i = 0; i != NumElts; ++i) {
6821         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6822           Base = V->getOperand(i);
6823           break;
6824         }
6825       }
6826       // Splat of <u, u, u, u>, return <u, u, u, u>
6827       if (!Base.getNode())
6828         return N0;
6829       for (unsigned i = 0; i != NumElts; ++i) {
6830         if (V->getOperand(i) != Base) {
6831           AllSame = false;
6832           break;
6833         }
6834       }
6835       // Splat of <x, x, x, x>, return <x, x, x, x>
6836       if (AllSame)
6837         return N0;
6838     }
6839   }
6840   return SDValue();
6841 }
6842
6843 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
6844   if (!TLI.getShouldFoldAtomicFences())
6845     return SDValue();
6846
6847   SDValue atomic = N->getOperand(0);
6848   switch (atomic.getOpcode()) {
6849     case ISD::ATOMIC_CMP_SWAP:
6850     case ISD::ATOMIC_SWAP:
6851     case ISD::ATOMIC_LOAD_ADD:
6852     case ISD::ATOMIC_LOAD_SUB:
6853     case ISD::ATOMIC_LOAD_AND:
6854     case ISD::ATOMIC_LOAD_OR:
6855     case ISD::ATOMIC_LOAD_XOR:
6856     case ISD::ATOMIC_LOAD_NAND:
6857     case ISD::ATOMIC_LOAD_MIN:
6858     case ISD::ATOMIC_LOAD_MAX:
6859     case ISD::ATOMIC_LOAD_UMIN:
6860     case ISD::ATOMIC_LOAD_UMAX:
6861       break;
6862     default:
6863       return SDValue();
6864   }
6865
6866   SDValue fence = atomic.getOperand(0);
6867   if (fence.getOpcode() != ISD::MEMBARRIER)
6868     return SDValue();
6869
6870   switch (atomic.getOpcode()) {
6871     case ISD::ATOMIC_CMP_SWAP:
6872       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6873                                     fence.getOperand(0),
6874                                     atomic.getOperand(1), atomic.getOperand(2),
6875                                     atomic.getOperand(3)), atomic.getResNo());
6876     case ISD::ATOMIC_SWAP:
6877     case ISD::ATOMIC_LOAD_ADD:
6878     case ISD::ATOMIC_LOAD_SUB:
6879     case ISD::ATOMIC_LOAD_AND:
6880     case ISD::ATOMIC_LOAD_OR:
6881     case ISD::ATOMIC_LOAD_XOR:
6882     case ISD::ATOMIC_LOAD_NAND:
6883     case ISD::ATOMIC_LOAD_MIN:
6884     case ISD::ATOMIC_LOAD_MAX:
6885     case ISD::ATOMIC_LOAD_UMIN:
6886     case ISD::ATOMIC_LOAD_UMAX:
6887       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6888                                     fence.getOperand(0),
6889                                     atomic.getOperand(1), atomic.getOperand(2)),
6890                      atomic.getResNo());
6891     default:
6892       return SDValue();
6893   }
6894 }
6895
6896 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6897 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6898 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6899 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
6900 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6901   EVT VT = N->getValueType(0);
6902   DebugLoc dl = N->getDebugLoc();
6903   SDValue LHS = N->getOperand(0);
6904   SDValue RHS = N->getOperand(1);
6905   if (N->getOpcode() == ISD::AND) {
6906     if (RHS.getOpcode() == ISD::BITCAST)
6907       RHS = RHS.getOperand(0);
6908     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6909       SmallVector<int, 8> Indices;
6910       unsigned NumElts = RHS.getNumOperands();
6911       for (unsigned i = 0; i != NumElts; ++i) {
6912         SDValue Elt = RHS.getOperand(i);
6913         if (!isa<ConstantSDNode>(Elt))
6914           return SDValue();
6915         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6916           Indices.push_back(i);
6917         else if (cast<ConstantSDNode>(Elt)->isNullValue())
6918           Indices.push_back(NumElts);
6919         else
6920           return SDValue();
6921       }
6922
6923       // Let's see if the target supports this vector_shuffle.
6924       EVT RVT = RHS.getValueType();
6925       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6926         return SDValue();
6927
6928       // Return the new VECTOR_SHUFFLE node.
6929       EVT EltVT = RVT.getVectorElementType();
6930       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6931                                      DAG.getConstant(0, EltVT));
6932       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6933                                  RVT, &ZeroOps[0], ZeroOps.size());
6934       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
6935       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6936       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
6937     }
6938   }
6939
6940   return SDValue();
6941 }
6942
6943 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6944 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6945   // After legalize, the target may be depending on adds and other
6946   // binary ops to provide legal ways to construct constants or other
6947   // things. Simplifying them may result in a loss of legality.
6948   if (LegalOperations) return SDValue();
6949
6950   assert(N->getValueType(0).isVector() &&
6951          "SimplifyVBinOp only works on vectors!");
6952
6953   SDValue LHS = N->getOperand(0);
6954   SDValue RHS = N->getOperand(1);
6955   SDValue Shuffle = XformToShuffleWithZero(N);
6956   if (Shuffle.getNode()) return Shuffle;
6957
6958   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6959   // this operation.
6960   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6961       RHS.getOpcode() == ISD::BUILD_VECTOR) {
6962     SmallVector<SDValue, 8> Ops;
6963     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6964       SDValue LHSOp = LHS.getOperand(i);
6965       SDValue RHSOp = RHS.getOperand(i);
6966       // If these two elements can't be folded, bail out.
6967       if ((LHSOp.getOpcode() != ISD::UNDEF &&
6968            LHSOp.getOpcode() != ISD::Constant &&
6969            LHSOp.getOpcode() != ISD::ConstantFP) ||
6970           (RHSOp.getOpcode() != ISD::UNDEF &&
6971            RHSOp.getOpcode() != ISD::Constant &&
6972            RHSOp.getOpcode() != ISD::ConstantFP))
6973         break;
6974
6975       // Can't fold divide by zero.
6976       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6977           N->getOpcode() == ISD::FDIV) {
6978         if ((RHSOp.getOpcode() == ISD::Constant &&
6979              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6980             (RHSOp.getOpcode() == ISD::ConstantFP &&
6981              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6982           break;
6983       }
6984
6985       EVT VT = LHSOp.getValueType();
6986       assert(RHSOp.getValueType() == VT &&
6987              "SimplifyVBinOp with different BUILD_VECTOR element types");
6988       SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
6989                                    LHSOp, RHSOp);
6990       if (FoldOp.getOpcode() != ISD::UNDEF &&
6991           FoldOp.getOpcode() != ISD::Constant &&
6992           FoldOp.getOpcode() != ISD::ConstantFP)
6993         break;
6994       Ops.push_back(FoldOp);
6995       AddToWorkList(FoldOp.getNode());
6996     }
6997
6998     if (Ops.size() == LHS.getNumOperands())
6999       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7000                          LHS.getValueType(), &Ops[0], Ops.size());
7001   }
7002
7003   return SDValue();
7004 }
7005
7006 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
7007                                     SDValue N1, SDValue N2){
7008   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
7009
7010   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
7011                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
7012
7013   // If we got a simplified select_cc node back from SimplifySelectCC, then
7014   // break it down into a new SETCC node, and a new SELECT node, and then return
7015   // the SELECT node, since we were called with a SELECT node.
7016   if (SCC.getNode()) {
7017     // Check to see if we got a select_cc back (to turn into setcc/select).
7018     // Otherwise, just return whatever node we got back, like fabs.
7019     if (SCC.getOpcode() == ISD::SELECT_CC) {
7020       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
7021                                   N0.getValueType(),
7022                                   SCC.getOperand(0), SCC.getOperand(1),
7023                                   SCC.getOperand(4));
7024       AddToWorkList(SETCC.getNode());
7025       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
7026                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
7027     }
7028
7029     return SCC;
7030   }
7031   return SDValue();
7032 }
7033
7034 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
7035 /// are the two values being selected between, see if we can simplify the
7036 /// select.  Callers of this should assume that TheSelect is deleted if this
7037 /// returns true.  As such, they should return the appropriate thing (e.g. the
7038 /// node) back to the top-level of the DAG combiner loop to avoid it being
7039 /// looked at.
7040 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
7041                                     SDValue RHS) {
7042
7043   // Cannot simplify select with vector condition
7044   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
7045
7046   // If this is a select from two identical things, try to pull the operation
7047   // through the select.
7048   if (LHS.getOpcode() != RHS.getOpcode() ||
7049       !LHS.hasOneUse() || !RHS.hasOneUse())
7050     return false;
7051
7052   // If this is a load and the token chain is identical, replace the select
7053   // of two loads with a load through a select of the address to load from.
7054   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
7055   // constants have been dropped into the constant pool.
7056   if (LHS.getOpcode() == ISD::LOAD) {
7057     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
7058     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
7059
7060     // Token chains must be identical.
7061     if (LHS.getOperand(0) != RHS.getOperand(0) ||
7062         // Do not let this transformation reduce the number of volatile loads.
7063         LLD->isVolatile() || RLD->isVolatile() ||
7064         // If this is an EXTLOAD, the VT's must match.
7065         LLD->getMemoryVT() != RLD->getMemoryVT() ||
7066         // If this is an EXTLOAD, the kind of extension must match.
7067         (LLD->getExtensionType() != RLD->getExtensionType() &&
7068          // The only exception is if one of the extensions is anyext.
7069          LLD->getExtensionType() != ISD::EXTLOAD &&
7070          RLD->getExtensionType() != ISD::EXTLOAD) ||
7071         // FIXME: this discards src value information.  This is
7072         // over-conservative. It would be beneficial to be able to remember
7073         // both potential memory locations.  Since we are discarding
7074         // src value info, don't do the transformation if the memory
7075         // locations are not in the default address space.
7076         LLD->getPointerInfo().getAddrSpace() != 0 ||
7077         RLD->getPointerInfo().getAddrSpace() != 0)
7078       return false;
7079
7080     // Check that the select condition doesn't reach either load.  If so,
7081     // folding this will induce a cycle into the DAG.  If not, this is safe to
7082     // xform, so create a select of the addresses.
7083     SDValue Addr;
7084     if (TheSelect->getOpcode() == ISD::SELECT) {
7085       SDNode *CondNode = TheSelect->getOperand(0).getNode();
7086       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
7087           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
7088         return false;
7089       Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
7090                          LLD->getBasePtr().getValueType(),
7091                          TheSelect->getOperand(0), LLD->getBasePtr(),
7092                          RLD->getBasePtr());
7093     } else {  // Otherwise SELECT_CC
7094       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
7095       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
7096
7097       if ((LLD->hasAnyUseOfValue(1) &&
7098            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
7099           (LLD->hasAnyUseOfValue(1) &&
7100            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
7101         return false;
7102
7103       Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
7104                          LLD->getBasePtr().getValueType(),
7105                          TheSelect->getOperand(0),
7106                          TheSelect->getOperand(1),
7107                          LLD->getBasePtr(), RLD->getBasePtr(),
7108                          TheSelect->getOperand(4));
7109     }
7110
7111     SDValue Load;
7112     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
7113       Load = DAG.getLoad(TheSelect->getValueType(0),
7114                          TheSelect->getDebugLoc(),
7115                          // FIXME: Discards pointer info.
7116                          LLD->getChain(), Addr, MachinePointerInfo(),
7117                          LLD->isVolatile(), LLD->isNonTemporal(),
7118                          LLD->getAlignment());
7119     } else {
7120       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
7121                             RLD->getExtensionType() : LLD->getExtensionType(),
7122                             TheSelect->getDebugLoc(),
7123                             TheSelect->getValueType(0),
7124                             // FIXME: Discards pointer info.
7125                             LLD->getChain(), Addr, MachinePointerInfo(),
7126                             LLD->getMemoryVT(), LLD->isVolatile(),
7127                             LLD->isNonTemporal(), LLD->getAlignment());
7128     }
7129
7130     // Users of the select now use the result of the load.
7131     CombineTo(TheSelect, Load);
7132
7133     // Users of the old loads now use the new load's chain.  We know the
7134     // old-load value is dead now.
7135     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
7136     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
7137     return true;
7138   }
7139
7140   return false;
7141 }
7142
7143 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
7144 /// where 'cond' is the comparison specified by CC.
7145 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
7146                                       SDValue N2, SDValue N3,
7147                                       ISD::CondCode CC, bool NotExtCompare) {
7148   // (x ? y : y) -> y.
7149   if (N2 == N3) return N2;
7150
7151   EVT VT = N2.getValueType();
7152   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
7153   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
7154   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
7155
7156   // Determine if the condition we're dealing with is constant
7157   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
7158                               N0, N1, CC, DL, false);
7159   if (SCC.getNode()) AddToWorkList(SCC.getNode());
7160   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
7161
7162   // fold select_cc true, x, y -> x
7163   if (SCCC && !SCCC->isNullValue())
7164     return N2;
7165   // fold select_cc false, x, y -> y
7166   if (SCCC && SCCC->isNullValue())
7167     return N3;
7168
7169   // Check to see if we can simplify the select into an fabs node
7170   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
7171     // Allow either -0.0 or 0.0
7172     if (CFP->getValueAPF().isZero()) {
7173       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
7174       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
7175           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
7176           N2 == N3.getOperand(0))
7177         return DAG.getNode(ISD::FABS, DL, VT, N0);
7178
7179       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
7180       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
7181           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
7182           N2.getOperand(0) == N3)
7183         return DAG.getNode(ISD::FABS, DL, VT, N3);
7184     }
7185   }
7186
7187   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
7188   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
7189   // in it.  This is a win when the constant is not otherwise available because
7190   // it replaces two constant pool loads with one.  We only do this if the FP
7191   // type is known to be legal, because if it isn't, then we are before legalize
7192   // types an we want the other legalization to happen first (e.g. to avoid
7193   // messing with soft float) and if the ConstantFP is not legal, because if
7194   // it is legal, we may not need to store the FP constant in a constant pool.
7195   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
7196     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
7197       if (TLI.isTypeLegal(N2.getValueType()) &&
7198           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
7199            TargetLowering::Legal) &&
7200           // If both constants have multiple uses, then we won't need to do an
7201           // extra load, they are likely around in registers for other users.
7202           (TV->hasOneUse() || FV->hasOneUse())) {
7203         Constant *Elts[] = {
7204           const_cast<ConstantFP*>(FV->getConstantFPValue()),
7205           const_cast<ConstantFP*>(TV->getConstantFPValue())
7206         };
7207         const Type *FPTy = Elts[0]->getType();
7208         const TargetData &TD = *TLI.getTargetData();
7209
7210         // Create a ConstantArray of the two constants.
7211         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
7212         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
7213                                             TD.getPrefTypeAlignment(FPTy));
7214         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
7215
7216         // Get the offsets to the 0 and 1 element of the array so that we can
7217         // select between them.
7218         SDValue Zero = DAG.getIntPtrConstant(0);
7219         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
7220         SDValue One = DAG.getIntPtrConstant(EltSize);
7221
7222         SDValue Cond = DAG.getSetCC(DL,
7223                                     TLI.getSetCCResultType(N0.getValueType()),
7224                                     N0, N1, CC);
7225         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
7226                                         Cond, One, Zero);
7227         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
7228                             CstOffset);
7229         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
7230                            MachinePointerInfo::getConstantPool(), false,
7231                            false, Alignment);
7232
7233       }
7234     }
7235
7236   // Check to see if we can perform the "gzip trick", transforming
7237   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
7238   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
7239       N0.getValueType().isInteger() &&
7240       N2.getValueType().isInteger() &&
7241       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
7242        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
7243     EVT XType = N0.getValueType();
7244     EVT AType = N2.getValueType();
7245     if (XType.bitsGE(AType)) {
7246       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
7247       // single-bit constant.
7248       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
7249         unsigned ShCtV = N2C->getAPIntValue().logBase2();
7250         ShCtV = XType.getSizeInBits()-ShCtV-1;
7251         SDValue ShCt = DAG.getConstant(ShCtV,
7252                                        getShiftAmountTy(N0.getValueType()));
7253         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
7254                                     XType, N0, ShCt);
7255         AddToWorkList(Shift.getNode());
7256
7257         if (XType.bitsGT(AType)) {
7258           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7259           AddToWorkList(Shift.getNode());
7260         }
7261
7262         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7263       }
7264
7265       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
7266                                   XType, N0,
7267                                   DAG.getConstant(XType.getSizeInBits()-1,
7268                                          getShiftAmountTy(N0.getValueType())));
7269       AddToWorkList(Shift.getNode());
7270
7271       if (XType.bitsGT(AType)) {
7272         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7273         AddToWorkList(Shift.getNode());
7274       }
7275
7276       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7277     }
7278   }
7279
7280   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
7281   // where y is has a single bit set.
7282   // A plaintext description would be, we can turn the SELECT_CC into an AND
7283   // when the condition can be materialized as an all-ones register.  Any
7284   // single bit-test can be materialized as an all-ones register with
7285   // shift-left and shift-right-arith.
7286   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
7287       N0->getValueType(0) == VT &&
7288       N1C && N1C->isNullValue() &&
7289       N2C && N2C->isNullValue()) {
7290     SDValue AndLHS = N0->getOperand(0);
7291     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7292     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
7293       // Shift the tested bit over the sign bit.
7294       APInt AndMask = ConstAndRHS->getAPIntValue();
7295       SDValue ShlAmt =
7296         DAG.getConstant(AndMask.countLeadingZeros(),
7297                         getShiftAmountTy(AndLHS.getValueType()));
7298       SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
7299
7300       // Now arithmetic right shift it all the way over, so the result is either
7301       // all-ones, or zero.
7302       SDValue ShrAmt =
7303         DAG.getConstant(AndMask.getBitWidth()-1,
7304                         getShiftAmountTy(Shl.getValueType()));
7305       SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
7306
7307       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
7308     }
7309   }
7310
7311   // fold select C, 16, 0 -> shl C, 4
7312   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
7313       TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
7314
7315     // If the caller doesn't want us to simplify this into a zext of a compare,
7316     // don't do it.
7317     if (NotExtCompare && N2C->getAPIntValue() == 1)
7318       return SDValue();
7319
7320     // Get a SetCC of the condition
7321     // FIXME: Should probably make sure that setcc is legal if we ever have a
7322     // target where it isn't.
7323     SDValue Temp, SCC;
7324     // cast from setcc result type to select result type
7325     if (LegalTypes) {
7326       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
7327                           N0, N1, CC);
7328       if (N2.getValueType().bitsLT(SCC.getValueType()))
7329         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
7330       else
7331         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7332                            N2.getValueType(), SCC);
7333     } else {
7334       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
7335       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7336                          N2.getValueType(), SCC);
7337     }
7338
7339     AddToWorkList(SCC.getNode());
7340     AddToWorkList(Temp.getNode());
7341
7342     if (N2C->getAPIntValue() == 1)
7343       return Temp;
7344
7345     // shl setcc result by log2 n2c
7346     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
7347                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
7348                                        getShiftAmountTy(Temp.getValueType())));
7349   }
7350
7351   // Check to see if this is the equivalent of setcc
7352   // FIXME: Turn all of these into setcc if setcc if setcc is legal
7353   // otherwise, go ahead with the folds.
7354   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
7355     EVT XType = N0.getValueType();
7356     if (!LegalOperations ||
7357         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
7358       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
7359       if (Res.getValueType() != VT)
7360         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
7361       return Res;
7362     }
7363
7364     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
7365     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
7366         (!LegalOperations ||
7367          TLI.isOperationLegal(ISD::CTLZ, XType))) {
7368       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
7369       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
7370                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
7371                                        getShiftAmountTy(Ctlz.getValueType())));
7372     }
7373     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
7374     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
7375       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
7376                                   XType, DAG.getConstant(0, XType), N0);
7377       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
7378       return DAG.getNode(ISD::SRL, DL, XType,
7379                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
7380                          DAG.getConstant(XType.getSizeInBits()-1,
7381                                          getShiftAmountTy(XType)));
7382     }
7383     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
7384     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
7385       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
7386                                  DAG.getConstant(XType.getSizeInBits()-1,
7387                                          getShiftAmountTy(N0.getValueType())));
7388       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
7389     }
7390   }
7391
7392   // Check to see if this is an integer abs.
7393   // select_cc setg[te] X,  0,  X, -X ->
7394   // select_cc setgt    X, -1,  X, -X ->
7395   // select_cc setl[te] X,  0, -X,  X ->
7396   // select_cc setlt    X,  1, -X,  X ->
7397   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7398   if (N1C) {
7399     ConstantSDNode *SubC = NULL;
7400     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7401          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
7402         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
7403       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
7404     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
7405               (N1C->isOne() && CC == ISD::SETLT)) &&
7406              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
7407       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
7408
7409     EVT XType = N0.getValueType();
7410     if (SubC && SubC->isNullValue() && XType.isInteger()) {
7411       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
7412                                   N0,
7413                                   DAG.getConstant(XType.getSizeInBits()-1,
7414                                          getShiftAmountTy(N0.getValueType())));
7415       SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7416                                 XType, N0, Shift);
7417       AddToWorkList(Shift.getNode());
7418       AddToWorkList(Add.getNode());
7419       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7420     }
7421   }
7422
7423   return SDValue();
7424 }
7425
7426 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7427 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7428                                    SDValue N1, ISD::CondCode Cond,
7429                                    DebugLoc DL, bool foldBooleans) {
7430   TargetLowering::DAGCombinerInfo
7431     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7432   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7433 }
7434
7435 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7436 /// return a DAG expression to select that will generate the same value by
7437 /// multiplying by a magic number.  See:
7438 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7439 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7440   std::vector<SDNode*> Built;
7441   SDValue S = TLI.BuildSDIV(N, DAG, &Built);
7442
7443   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7444        ii != ee; ++ii)
7445     AddToWorkList(*ii);
7446   return S;
7447 }
7448
7449 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7450 /// return a DAG expression to select that will generate the same value by
7451 /// multiplying by a magic number.  See:
7452 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7453 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7454   std::vector<SDNode*> Built;
7455   SDValue S = TLI.BuildUDIV(N, DAG, &Built);
7456
7457   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7458        ii != ee; ++ii)
7459     AddToWorkList(*ii);
7460   return S;
7461 }
7462
7463 /// FindBaseOffset - Return true if base is a frame index, which is known not
7464 // to alias with anything but itself.  Provides base object and offset as
7465 // results.
7466 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7467                            const GlobalValue *&GV, void *&CV) {
7468   // Assume it is a primitive operation.
7469   Base = Ptr; Offset = 0; GV = 0; CV = 0;
7470
7471   // If it's an adding a simple constant then integrate the offset.
7472   if (Base.getOpcode() == ISD::ADD) {
7473     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7474       Base = Base.getOperand(0);
7475       Offset += C->getZExtValue();
7476     }
7477   }
7478
7479   // Return the underlying GlobalValue, and update the Offset.  Return false
7480   // for GlobalAddressSDNode since the same GlobalAddress may be represented
7481   // by multiple nodes with different offsets.
7482   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7483     GV = G->getGlobal();
7484     Offset += G->getOffset();
7485     return false;
7486   }
7487
7488   // Return the underlying Constant value, and update the Offset.  Return false
7489   // for ConstantSDNodes since the same constant pool entry may be represented
7490   // by multiple nodes with different offsets.
7491   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7492     CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7493                                          : (void *)C->getConstVal();
7494     Offset += C->getOffset();
7495     return false;
7496   }
7497   // If it's any of the following then it can't alias with anything but itself.
7498   return isa<FrameIndexSDNode>(Base);
7499 }
7500
7501 /// isAlias - Return true if there is any possibility that the two addresses
7502 /// overlap.
7503 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7504                           const Value *SrcValue1, int SrcValueOffset1,
7505                           unsigned SrcValueAlign1,
7506                           const MDNode *TBAAInfo1,
7507                           SDValue Ptr2, int64_t Size2,
7508                           const Value *SrcValue2, int SrcValueOffset2,
7509                           unsigned SrcValueAlign2,
7510                           const MDNode *TBAAInfo2) const {
7511   // If they are the same then they must be aliases.
7512   if (Ptr1 == Ptr2) return true;
7513
7514   // Gather base node and offset information.
7515   SDValue Base1, Base2;
7516   int64_t Offset1, Offset2;
7517   const GlobalValue *GV1, *GV2;
7518   void *CV1, *CV2;
7519   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7520   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7521
7522   // If they have a same base address then check to see if they overlap.
7523   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7524     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7525
7526   // It is possible for different frame indices to alias each other, mostly
7527   // when tail call optimization reuses return address slots for arguments.
7528   // To catch this case, look up the actual index of frame indices to compute
7529   // the real alias relationship.
7530   if (isFrameIndex1 && isFrameIndex2) {
7531     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7532     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7533     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7534     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7535   }
7536
7537   // Otherwise, if we know what the bases are, and they aren't identical, then
7538   // we know they cannot alias.
7539   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7540     return false;
7541
7542   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7543   // compared to the size and offset of the access, we may be able to prove they
7544   // do not alias.  This check is conservative for now to catch cases created by
7545   // splitting vector types.
7546   if ((SrcValueAlign1 == SrcValueAlign2) &&
7547       (SrcValueOffset1 != SrcValueOffset2) &&
7548       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7549     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7550     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7551
7552     // There is no overlap between these relatively aligned accesses of similar
7553     // size, return no alias.
7554     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7555       return false;
7556   }
7557
7558   if (CombinerGlobalAA) {
7559     // Use alias analysis information.
7560     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7561     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7562     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7563     AliasAnalysis::AliasResult AAResult =
7564       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7565                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7566     if (AAResult == AliasAnalysis::NoAlias)
7567       return false;
7568   }
7569
7570   // Otherwise we have to assume they alias.
7571   return true;
7572 }
7573
7574 /// FindAliasInfo - Extracts the relevant alias information from the memory
7575 /// node.  Returns true if the operand was a load.
7576 bool DAGCombiner::FindAliasInfo(SDNode *N,
7577                         SDValue &Ptr, int64_t &Size,
7578                         const Value *&SrcValue,
7579                         int &SrcValueOffset,
7580                         unsigned &SrcValueAlign,
7581                         const MDNode *&TBAAInfo) const {
7582   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7583     Ptr = LD->getBasePtr();
7584     Size = LD->getMemoryVT().getSizeInBits() >> 3;
7585     SrcValue = LD->getSrcValue();
7586     SrcValueOffset = LD->getSrcValueOffset();
7587     SrcValueAlign = LD->getOriginalAlignment();
7588     TBAAInfo = LD->getTBAAInfo();
7589     return true;
7590   }
7591   if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7592     Ptr = ST->getBasePtr();
7593     Size = ST->getMemoryVT().getSizeInBits() >> 3;
7594     SrcValue = ST->getSrcValue();
7595     SrcValueOffset = ST->getSrcValueOffset();
7596     SrcValueAlign = ST->getOriginalAlignment();
7597     TBAAInfo = ST->getTBAAInfo();
7598     return false;
7599   }
7600   llvm_unreachable("FindAliasInfo expected a memory operand");
7601 }
7602
7603 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
7604 /// looking for aliasing nodes and adding them to the Aliases vector.
7605 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
7606                                    SmallVector<SDValue, 8> &Aliases) {
7607   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
7608   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
7609
7610   // Get alias information for node.
7611   SDValue Ptr;
7612   int64_t Size;
7613   const Value *SrcValue;
7614   int SrcValueOffset;
7615   unsigned SrcValueAlign;
7616   const MDNode *SrcTBAAInfo;
7617   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
7618                               SrcValueAlign, SrcTBAAInfo);
7619
7620   // Starting off.
7621   Chains.push_back(OriginalChain);
7622   unsigned Depth = 0;
7623
7624   // Look at each chain and determine if it is an alias.  If so, add it to the
7625   // aliases list.  If not, then continue up the chain looking for the next
7626   // candidate.
7627   while (!Chains.empty()) {
7628     SDValue Chain = Chains.back();
7629     Chains.pop_back();
7630
7631     // For TokenFactor nodes, look at each operand and only continue up the
7632     // chain until we find two aliases.  If we've seen two aliases, assume we'll
7633     // find more and revert to original chain since the xform is unlikely to be
7634     // profitable.
7635     //
7636     // FIXME: The depth check could be made to return the last non-aliasing
7637     // chain we found before we hit a tokenfactor rather than the original
7638     // chain.
7639     if (Depth > 6 || Aliases.size() == 2) {
7640       Aliases.clear();
7641       Aliases.push_back(OriginalChain);
7642       break;
7643     }
7644
7645     // Don't bother if we've been before.
7646     if (!Visited.insert(Chain.getNode()))
7647       continue;
7648
7649     switch (Chain.getOpcode()) {
7650     case ISD::EntryToken:
7651       // Entry token is ideal chain operand, but handled in FindBetterChain.
7652       break;
7653
7654     case ISD::LOAD:
7655     case ISD::STORE: {
7656       // Get alias information for Chain.
7657       SDValue OpPtr;
7658       int64_t OpSize;
7659       const Value *OpSrcValue;
7660       int OpSrcValueOffset;
7661       unsigned OpSrcValueAlign;
7662       const MDNode *OpSrcTBAAInfo;
7663       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
7664                                     OpSrcValue, OpSrcValueOffset,
7665                                     OpSrcValueAlign,
7666                                     OpSrcTBAAInfo);
7667
7668       // If chain is alias then stop here.
7669       if (!(IsLoad && IsOpLoad) &&
7670           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
7671                   SrcTBAAInfo,
7672                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
7673                   OpSrcValueAlign, OpSrcTBAAInfo)) {
7674         Aliases.push_back(Chain);
7675       } else {
7676         // Look further up the chain.
7677         Chains.push_back(Chain.getOperand(0));
7678         ++Depth;
7679       }
7680       break;
7681     }
7682
7683     case ISD::TokenFactor:
7684       // We have to check each of the operands of the token factor for "small"
7685       // token factors, so we queue them up.  Adding the operands to the queue
7686       // (stack) in reverse order maintains the original order and increases the
7687       // likelihood that getNode will find a matching token factor (CSE.)
7688       if (Chain.getNumOperands() > 16) {
7689         Aliases.push_back(Chain);
7690         break;
7691       }
7692       for (unsigned n = Chain.getNumOperands(); n;)
7693         Chains.push_back(Chain.getOperand(--n));
7694       ++Depth;
7695       break;
7696
7697     default:
7698       // For all other instructions we will just have to take what we can get.
7699       Aliases.push_back(Chain);
7700       break;
7701     }
7702   }
7703 }
7704
7705 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
7706 /// for a better chain (aliasing node.)
7707 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7708   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
7709
7710   // Accumulate all the aliases to this node.
7711   GatherAllAliases(N, OldChain, Aliases);
7712
7713   // If no operands then chain to entry token.
7714   if (Aliases.size() == 0)
7715     return DAG.getEntryNode();
7716
7717   // If a single operand then chain to it.  We don't need to revisit it.
7718   if (Aliases.size() == 1)
7719     return Aliases[0];
7720
7721   // Construct a custom tailored token factor.
7722   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7723                      &Aliases[0], Aliases.size());
7724 }
7725
7726 // SelectionDAG::Combine - This is the entry point for the file.
7727 //
7728 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7729                            CodeGenOpt::Level OptLevel) {
7730   /// run - This is the main entry point to this class.
7731   ///
7732   DAGCombiner(*this, AA, OptLevel).Run(Level);
7733 }