TargetLowering.cpp revision 85509802eba15c82ff486f512a0b559699dc6999
1//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
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 implements the TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Target/TargetLowering.h"
15#include "llvm/ADT/BitVector.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/CodeGen/Analysis.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineJumpTableInfo.h"
21#include "llvm/CodeGen/SelectionDAG.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalVariable.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCExpr.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Target/TargetLoweringObjectFile.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetRegisterInfo.h"
33#include <cctype>
34using namespace llvm;
35
36/// NOTE: The constructor takes ownership of TLOF.
37TargetLowering::TargetLowering(const TargetMachine &tm,
38                               const TargetLoweringObjectFile *tlof)
39  : TargetLoweringBase(tm, tlof) {}
40
41const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
42  return NULL;
43}
44
45/// Check whether a given call node is in tail position within its function. If
46/// so, it sets Chain to the input chain of the tail call.
47bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
48                                          SDValue &Chain) const {
49  const Function *F = DAG.getMachineFunction().getFunction();
50
51  // Conservatively require the attributes of the call to match those of
52  // the return. Ignore noalias because it doesn't affect the call sequence.
53  AttributeSet CallerAttrs = F->getAttributes();
54  if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
55      .removeAttribute(Attribute::NoAlias).hasAttributes())
56    return false;
57
58  // It's not safe to eliminate the sign / zero extension of the return value.
59  if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
60      CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
61    return false;
62
63  // Check if the only use is a function return node.
64  return isUsedByReturnOnly(Node, Chain);
65}
66
67
68/// Generate a libcall taking the given operands as arguments and returning a
69/// result of type RetVT.
70std::pair<SDValue, SDValue>
71TargetLowering::makeLibCall(SelectionDAG &DAG,
72                            RTLIB::Libcall LC, EVT RetVT,
73                            const SDValue *Ops, unsigned NumOps,
74                            bool isSigned, SDLoc dl,
75                            bool doesNotReturn,
76                            bool isReturnValueUsed) const {
77  TargetLowering::ArgListTy Args;
78  Args.reserve(NumOps);
79
80  TargetLowering::ArgListEntry Entry;
81  for (unsigned i = 0; i != NumOps; ++i) {
82    Entry.Node = Ops[i];
83    Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
84    Entry.isSExt = isSigned;
85    Entry.isZExt = !isSigned;
86    Args.push_back(Entry);
87  }
88  SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy());
89
90  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
91  TargetLowering::
92  CallLoweringInfo CLI(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
93                    false, 0, getLibcallCallingConv(LC),
94                    /*isTailCall=*/false,
95                    doesNotReturn, isReturnValueUsed, Callee, Args,
96                    DAG, dl);
97  return LowerCallTo(CLI);
98}
99
100
101/// SoftenSetCCOperands - Soften the operands of a comparison.  This code is
102/// shared among BR_CC, SELECT_CC, and SETCC handlers.
103void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
104                                         SDValue &NewLHS, SDValue &NewRHS,
105                                         ISD::CondCode &CCCode,
106                                         SDLoc dl) const {
107  assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
108         && "Unsupported setcc type!");
109
110  // Expand into one or more soft-fp libcall(s).
111  RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
112  switch (CCCode) {
113  case ISD::SETEQ:
114  case ISD::SETOEQ:
115    LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
116          (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
117    break;
118  case ISD::SETNE:
119  case ISD::SETUNE:
120    LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
121          (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
122    break;
123  case ISD::SETGE:
124  case ISD::SETOGE:
125    LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
126          (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
127    break;
128  case ISD::SETLT:
129  case ISD::SETOLT:
130    LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
131          (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
132    break;
133  case ISD::SETLE:
134  case ISD::SETOLE:
135    LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
136          (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
137    break;
138  case ISD::SETGT:
139  case ISD::SETOGT:
140    LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
141          (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
142    break;
143  case ISD::SETUO:
144    LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
145          (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
146    break;
147  case ISD::SETO:
148    LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
149          (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
150    break;
151  default:
152    LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
153          (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
154    switch (CCCode) {
155    case ISD::SETONE:
156      // SETONE = SETOLT | SETOGT
157      LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
158            (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
159      // Fallthrough
160    case ISD::SETUGT:
161      LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
162            (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
163      break;
164    case ISD::SETUGE:
165      LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
166            (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
167      break;
168    case ISD::SETULT:
169      LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
170            (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
171      break;
172    case ISD::SETULE:
173      LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
174            (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
175      break;
176    case ISD::SETUEQ:
177      LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
178            (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
179      break;
180    default: llvm_unreachable("Do not know how to soften this setcc!");
181    }
182  }
183
184  // Use the target specific return value for comparions lib calls.
185  EVT RetVT = getCmpLibcallReturnType();
186  SDValue Ops[2] = { NewLHS, NewRHS };
187  NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/,
188                       dl).first;
189  NewRHS = DAG.getConstant(0, RetVT);
190  CCCode = getCmpLibcallCC(LC1);
191  if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
192    SDValue Tmp = DAG.getNode(ISD::SETCC, dl,
193                              getSetCCResultType(*DAG.getContext(), RetVT),
194                              NewLHS, NewRHS, DAG.getCondCode(CCCode));
195    NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/,
196                         dl).first;
197    NewLHS = DAG.getNode(ISD::SETCC, dl,
198                         getSetCCResultType(*DAG.getContext(), RetVT), NewLHS,
199                         NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
200    NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
201    NewRHS = SDValue();
202  }
203}
204
205/// getJumpTableEncoding - Return the entry encoding for a jump table in the
206/// current function.  The returned value is a member of the
207/// MachineJumpTableInfo::JTEntryKind enum.
208unsigned TargetLowering::getJumpTableEncoding() const {
209  // In non-pic modes, just use the address of a block.
210  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
211    return MachineJumpTableInfo::EK_BlockAddress;
212
213  // In PIC mode, if the target supports a GPRel32 directive, use it.
214  if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != 0)
215    return MachineJumpTableInfo::EK_GPRel32BlockAddress;
216
217  // Otherwise, use a label difference.
218  return MachineJumpTableInfo::EK_LabelDifference32;
219}
220
221SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
222                                                 SelectionDAG &DAG) const {
223  // If our PIC model is GP relative, use the global offset table as the base.
224  unsigned JTEncoding = getJumpTableEncoding();
225
226  if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
227      (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
228    return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0));
229
230  return Table;
231}
232
233/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
234/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
235/// MCExpr.
236const MCExpr *
237TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
238                                             unsigned JTI,MCContext &Ctx) const{
239  // The normal PIC reloc base is the label at the start of the jump table.
240  return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
241}
242
243bool
244TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
245  // Assume that everything is safe in static mode.
246  if (getTargetMachine().getRelocationModel() == Reloc::Static)
247    return true;
248
249  // In dynamic-no-pic mode, assume that known defined values are safe.
250  if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
251      GA &&
252      !GA->getGlobal()->isDeclaration() &&
253      !GA->getGlobal()->isWeakForLinker())
254    return true;
255
256  // Otherwise assume nothing is safe.
257  return false;
258}
259
260//===----------------------------------------------------------------------===//
261//  Optimization Methods
262//===----------------------------------------------------------------------===//
263
264/// ShrinkDemandedConstant - Check to see if the specified operand of the
265/// specified instruction is a constant integer.  If so, check to see if there
266/// are any bits set in the constant that are not demanded.  If so, shrink the
267/// constant and return true.
268bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
269                                                        const APInt &Demanded) {
270  SDLoc dl(Op);
271
272  // FIXME: ISD::SELECT, ISD::SELECT_CC
273  switch (Op.getOpcode()) {
274  default: break;
275  case ISD::XOR:
276  case ISD::AND:
277  case ISD::OR: {
278    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
279    if (!C) return false;
280
281    if (Op.getOpcode() == ISD::XOR &&
282        (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
283      return false;
284
285    // if we can expand it to have all bits set, do it
286    if (C->getAPIntValue().intersects(~Demanded)) {
287      EVT VT = Op.getValueType();
288      SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
289                                DAG.getConstant(Demanded &
290                                                C->getAPIntValue(),
291                                                VT));
292      return CombineTo(Op, New);
293    }
294
295    break;
296  }
297  }
298
299  return false;
300}
301
302/// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
303/// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
304/// cast, but it could be generalized for targets with other types of
305/// implicit widening casts.
306bool
307TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
308                                                    unsigned BitWidth,
309                                                    const APInt &Demanded,
310                                                    SDLoc dl) {
311  assert(Op.getNumOperands() == 2 &&
312         "ShrinkDemandedOp only supports binary operators!");
313  assert(Op.getNode()->getNumValues() == 1 &&
314         "ShrinkDemandedOp only supports nodes with one result!");
315
316  // Don't do this if the node has another user, which may require the
317  // full value.
318  if (!Op.getNode()->hasOneUse())
319    return false;
320
321  // Search for the smallest integer type with free casts to and from
322  // Op's type. For expedience, just check power-of-2 integer types.
323  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
324  unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
325  unsigned SmallVTBits = DemandedSize;
326  if (!isPowerOf2_32(SmallVTBits))
327    SmallVTBits = NextPowerOf2(SmallVTBits);
328  for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
329    EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
330    if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
331        TLI.isZExtFree(SmallVT, Op.getValueType())) {
332      // We found a type with free casts.
333      SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
334                              DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
335                                          Op.getNode()->getOperand(0)),
336                              DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
337                                          Op.getNode()->getOperand(1)));
338      bool NeedZext = DemandedSize > SmallVTBits;
339      SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
340                              dl, Op.getValueType(), X);
341      return CombineTo(Op, Z);
342    }
343  }
344  return false;
345}
346
347/// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
348/// DemandedMask bits of the result of Op are ever used downstream.  If we can
349/// use this information to simplify Op, create a new simplified DAG node and
350/// return true, returning the original and new nodes in Old and New. Otherwise,
351/// analyze the expression and return a mask of KnownOne and KnownZero bits for
352/// the expression (used to simplify the caller).  The KnownZero/One bits may
353/// only be accurate for those bits in the DemandedMask.
354bool TargetLowering::SimplifyDemandedBits(SDValue Op,
355                                          const APInt &DemandedMask,
356                                          APInt &KnownZero,
357                                          APInt &KnownOne,
358                                          TargetLoweringOpt &TLO,
359                                          unsigned Depth) const {
360  unsigned BitWidth = DemandedMask.getBitWidth();
361  assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
362         "Mask size mismatches value type size!");
363  APInt NewMask = DemandedMask;
364  SDLoc dl(Op);
365
366  // Don't know anything.
367  KnownZero = KnownOne = APInt(BitWidth, 0);
368
369  // Other users may use these bits.
370  if (!Op.getNode()->hasOneUse()) {
371    if (Depth != 0) {
372      // If not at the root, Just compute the KnownZero/KnownOne bits to
373      // simplify things downstream.
374      TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
375      return false;
376    }
377    // If this is the root being simplified, allow it to have multiple uses,
378    // just set the NewMask to all bits.
379    NewMask = APInt::getAllOnesValue(BitWidth);
380  } else if (DemandedMask == 0) {
381    // Not demanding any bits from Op.
382    if (Op.getOpcode() != ISD::UNDEF)
383      return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
384    return false;
385  } else if (Depth == 6) {        // Limit search depth.
386    return false;
387  }
388
389  APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
390  switch (Op.getOpcode()) {
391  case ISD::Constant:
392    // We know all of the bits for a constant!
393    KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
394    KnownZero = ~KnownOne;
395    return false;   // Don't fall through, will infinitely loop.
396  case ISD::AND:
397    // If the RHS is a constant, check to see if the LHS would be zero without
398    // using the bits from the RHS.  Below, we use knowledge about the RHS to
399    // simplify the LHS, here we're using information from the LHS to simplify
400    // the RHS.
401    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
402      APInt LHSZero, LHSOne;
403      // Do not increment Depth here; that can cause an infinite loop.
404      TLO.DAG.ComputeMaskedBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
405      // If the LHS already has zeros where RHSC does, this and is dead.
406      if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
407        return TLO.CombineTo(Op, Op.getOperand(0));
408      // If any of the set bits in the RHS are known zero on the LHS, shrink
409      // the constant.
410      if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
411        return true;
412    }
413
414    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
415                             KnownOne, TLO, Depth+1))
416      return true;
417    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
418    if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
419                             KnownZero2, KnownOne2, TLO, Depth+1))
420      return true;
421    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
422
423    // If all of the demanded bits are known one on one side, return the other.
424    // These bits cannot contribute to the result of the 'and'.
425    if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
426      return TLO.CombineTo(Op, Op.getOperand(0));
427    if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
428      return TLO.CombineTo(Op, Op.getOperand(1));
429    // If all of the demanded bits in the inputs are known zeros, return zero.
430    if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
431      return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
432    // If the RHS is a constant, see if we can simplify it.
433    if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
434      return true;
435    // If the operation can be done in a smaller type, do so.
436    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
437      return true;
438
439    // Output known-1 bits are only known if set in both the LHS & RHS.
440    KnownOne &= KnownOne2;
441    // Output known-0 are known to be clear if zero in either the LHS | RHS.
442    KnownZero |= KnownZero2;
443    break;
444  case ISD::OR:
445    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
446                             KnownOne, TLO, Depth+1))
447      return true;
448    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
449    if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
450                             KnownZero2, KnownOne2, TLO, Depth+1))
451      return true;
452    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
453
454    // If all of the demanded bits are known zero on one side, return the other.
455    // These bits cannot contribute to the result of the 'or'.
456    if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
457      return TLO.CombineTo(Op, Op.getOperand(0));
458    if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
459      return TLO.CombineTo(Op, Op.getOperand(1));
460    // If all of the potentially set bits on one side are known to be set on
461    // the other side, just use the 'other' side.
462    if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
463      return TLO.CombineTo(Op, Op.getOperand(0));
464    if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
465      return TLO.CombineTo(Op, Op.getOperand(1));
466    // If the RHS is a constant, see if we can simplify it.
467    if (TLO.ShrinkDemandedConstant(Op, NewMask))
468      return true;
469    // If the operation can be done in a smaller type, do so.
470    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
471      return true;
472
473    // Output known-0 bits are only known if clear in both the LHS & RHS.
474    KnownZero &= KnownZero2;
475    // Output known-1 are known to be set if set in either the LHS | RHS.
476    KnownOne |= KnownOne2;
477    break;
478  case ISD::XOR:
479    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
480                             KnownOne, TLO, Depth+1))
481      return true;
482    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
483    if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
484                             KnownOne2, TLO, Depth+1))
485      return true;
486    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
487
488    // If all of the demanded bits are known zero on one side, return the other.
489    // These bits cannot contribute to the result of the 'xor'.
490    if ((KnownZero & NewMask) == NewMask)
491      return TLO.CombineTo(Op, Op.getOperand(0));
492    if ((KnownZero2 & NewMask) == NewMask)
493      return TLO.CombineTo(Op, Op.getOperand(1));
494    // If the operation can be done in a smaller type, do so.
495    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
496      return true;
497
498    // If all of the unknown bits are known to be zero on one side or the other
499    // (but not both) turn this into an *inclusive* or.
500    //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
501    if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
502      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
503                                               Op.getOperand(0),
504                                               Op.getOperand(1)));
505
506    // Output known-0 bits are known if clear or set in both the LHS & RHS.
507    KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
508    // Output known-1 are known to be set if set in only one of the LHS, RHS.
509    KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
510
511    // If all of the demanded bits on one side are known, and all of the set
512    // bits on that side are also known to be set on the other side, turn this
513    // into an AND, as we know the bits will be cleared.
514    //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
515    // NB: it is okay if more bits are known than are requested
516    if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
517      if (KnownOne == KnownOne2) { // set bits are the same on both sides
518        EVT VT = Op.getValueType();
519        SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
520        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
521                                                 Op.getOperand(0), ANDC));
522      }
523    }
524
525    // If the RHS is a constant, see if we can simplify it.
526    // for XOR, we prefer to force bits to 1 if they will make a -1.
527    // if we can't force bits, try to shrink constant
528    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
529      APInt Expanded = C->getAPIntValue() | (~NewMask);
530      // if we can expand it to have all bits set, do it
531      if (Expanded.isAllOnesValue()) {
532        if (Expanded != C->getAPIntValue()) {
533          EVT VT = Op.getValueType();
534          SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
535                                          TLO.DAG.getConstant(Expanded, VT));
536          return TLO.CombineTo(Op, New);
537        }
538        // if it already has all the bits set, nothing to change
539        // but don't shrink either!
540      } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
541        return true;
542      }
543    }
544
545    KnownZero = KnownZeroOut;
546    KnownOne  = KnownOneOut;
547    break;
548  case ISD::SELECT:
549    if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
550                             KnownOne, TLO, Depth+1))
551      return true;
552    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
553                             KnownOne2, TLO, Depth+1))
554      return true;
555    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
556    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
557
558    // If the operands are constants, see if we can simplify them.
559    if (TLO.ShrinkDemandedConstant(Op, NewMask))
560      return true;
561
562    // Only known if known in both the LHS and RHS.
563    KnownOne &= KnownOne2;
564    KnownZero &= KnownZero2;
565    break;
566  case ISD::SELECT_CC:
567    if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
568                             KnownOne, TLO, Depth+1))
569      return true;
570    if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
571                             KnownOne2, TLO, Depth+1))
572      return true;
573    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
574    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
575
576    // If the operands are constants, see if we can simplify them.
577    if (TLO.ShrinkDemandedConstant(Op, NewMask))
578      return true;
579
580    // Only known if known in both the LHS and RHS.
581    KnownOne &= KnownOne2;
582    KnownZero &= KnownZero2;
583    break;
584  case ISD::SHL:
585    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
586      unsigned ShAmt = SA->getZExtValue();
587      SDValue InOp = Op.getOperand(0);
588
589      // If the shift count is an invalid immediate, don't do anything.
590      if (ShAmt >= BitWidth)
591        break;
592
593      // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
594      // single shift.  We can do this if the bottom bits (which are shifted
595      // out) are never demanded.
596      if (InOp.getOpcode() == ISD::SRL &&
597          isa<ConstantSDNode>(InOp.getOperand(1))) {
598        if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
599          unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
600          unsigned Opc = ISD::SHL;
601          int Diff = ShAmt-C1;
602          if (Diff < 0) {
603            Diff = -Diff;
604            Opc = ISD::SRL;
605          }
606
607          SDValue NewSA =
608            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
609          EVT VT = Op.getValueType();
610          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
611                                                   InOp.getOperand(0), NewSA));
612        }
613      }
614
615      if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
616                               KnownZero, KnownOne, TLO, Depth+1))
617        return true;
618
619      // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
620      // are not demanded. This will likely allow the anyext to be folded away.
621      if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
622        SDValue InnerOp = InOp.getNode()->getOperand(0);
623        EVT InnerVT = InnerOp.getValueType();
624        unsigned InnerBits = InnerVT.getSizeInBits();
625        if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
626            isTypeDesirableForOp(ISD::SHL, InnerVT)) {
627          EVT ShTy = getShiftAmountTy(InnerVT);
628          if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
629            ShTy = InnerVT;
630          SDValue NarrowShl =
631            TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
632                            TLO.DAG.getConstant(ShAmt, ShTy));
633          return
634            TLO.CombineTo(Op,
635                          TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
636                                          NarrowShl));
637        }
638      }
639
640      KnownZero <<= SA->getZExtValue();
641      KnownOne  <<= SA->getZExtValue();
642      // low bits known zero.
643      KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
644    }
645    break;
646  case ISD::SRL:
647    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
648      EVT VT = Op.getValueType();
649      unsigned ShAmt = SA->getZExtValue();
650      unsigned VTSize = VT.getSizeInBits();
651      SDValue InOp = Op.getOperand(0);
652
653      // If the shift count is an invalid immediate, don't do anything.
654      if (ShAmt >= BitWidth)
655        break;
656
657      // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
658      // single shift.  We can do this if the top bits (which are shifted out)
659      // are never demanded.
660      if (InOp.getOpcode() == ISD::SHL &&
661          isa<ConstantSDNode>(InOp.getOperand(1))) {
662        if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
663          unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
664          unsigned Opc = ISD::SRL;
665          int Diff = ShAmt-C1;
666          if (Diff < 0) {
667            Diff = -Diff;
668            Opc = ISD::SHL;
669          }
670
671          SDValue NewSA =
672            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
673          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
674                                                   InOp.getOperand(0), NewSA));
675        }
676      }
677
678      // Compute the new bits that are at the top now.
679      if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
680                               KnownZero, KnownOne, TLO, Depth+1))
681        return true;
682      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
683      KnownZero = KnownZero.lshr(ShAmt);
684      KnownOne  = KnownOne.lshr(ShAmt);
685
686      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
687      KnownZero |= HighBits;  // High bits known zero.
688    }
689    break;
690  case ISD::SRA:
691    // If this is an arithmetic shift right and only the low-bit is set, we can
692    // always convert this into a logical shr, even if the shift amount is
693    // variable.  The low bit of the shift cannot be an input sign bit unless
694    // the shift amount is >= the size of the datatype, which is undefined.
695    if (NewMask == 1)
696      return TLO.CombineTo(Op,
697                           TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
698                                           Op.getOperand(0), Op.getOperand(1)));
699
700    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
701      EVT VT = Op.getValueType();
702      unsigned ShAmt = SA->getZExtValue();
703
704      // If the shift count is an invalid immediate, don't do anything.
705      if (ShAmt >= BitWidth)
706        break;
707
708      APInt InDemandedMask = (NewMask << ShAmt);
709
710      // If any of the demanded bits are produced by the sign extension, we also
711      // demand the input sign bit.
712      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
713      if (HighBits.intersects(NewMask))
714        InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
715
716      if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
717                               KnownZero, KnownOne, TLO, Depth+1))
718        return true;
719      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
720      KnownZero = KnownZero.lshr(ShAmt);
721      KnownOne  = KnownOne.lshr(ShAmt);
722
723      // Handle the sign bit, adjusted to where it is now in the mask.
724      APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
725
726      // If the input sign bit is known to be zero, or if none of the top bits
727      // are demanded, turn this into an unsigned shift right.
728      if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
729        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
730                                                 Op.getOperand(0),
731                                                 Op.getOperand(1)));
732      } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
733        KnownOne |= HighBits;
734      }
735    }
736    break;
737  case ISD::SIGN_EXTEND_INREG: {
738    EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
739
740    APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
741    // If we only care about the highest bit, don't bother shifting right.
742    if (MsbMask == DemandedMask) {
743      unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
744      SDValue InOp = Op.getOperand(0);
745
746      // Compute the correct shift amount type, which must be getShiftAmountTy
747      // for scalar types after legalization.
748      EVT ShiftAmtTy = Op.getValueType();
749      if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
750        ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
751
752      SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
753      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
754                                            Op.getValueType(), InOp, ShiftAmt));
755    }
756
757    // Sign extension.  Compute the demanded bits in the result that are not
758    // present in the input.
759    APInt NewBits =
760      APInt::getHighBitsSet(BitWidth,
761                            BitWidth - ExVT.getScalarType().getSizeInBits());
762
763    // If none of the extended bits are demanded, eliminate the sextinreg.
764    if ((NewBits & NewMask) == 0)
765      return TLO.CombineTo(Op, Op.getOperand(0));
766
767    APInt InSignBit =
768      APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
769    APInt InputDemandedBits =
770      APInt::getLowBitsSet(BitWidth,
771                           ExVT.getScalarType().getSizeInBits()) &
772      NewMask;
773
774    // Since the sign extended bits are demanded, we know that the sign
775    // bit is demanded.
776    InputDemandedBits |= InSignBit;
777
778    if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
779                             KnownZero, KnownOne, TLO, Depth+1))
780      return true;
781    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
782
783    // If the sign bit of the input is known set or clear, then we know the
784    // top bits of the result.
785
786    // If the input sign bit is known zero, convert this into a zero extension.
787    if (KnownZero.intersects(InSignBit))
788      return TLO.CombineTo(Op,
789                          TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
790
791    if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
792      KnownOne |= NewBits;
793      KnownZero &= ~NewBits;
794    } else {                       // Input sign bit unknown
795      KnownZero &= ~NewBits;
796      KnownOne &= ~NewBits;
797    }
798    break;
799  }
800  case ISD::ZERO_EXTEND: {
801    unsigned OperandBitWidth =
802      Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
803    APInt InMask = NewMask.trunc(OperandBitWidth);
804
805    // If none of the top bits are demanded, convert this into an any_extend.
806    APInt NewBits =
807      APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
808    if (!NewBits.intersects(NewMask))
809      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
810                                               Op.getValueType(),
811                                               Op.getOperand(0)));
812
813    if (SimplifyDemandedBits(Op.getOperand(0), InMask,
814                             KnownZero, KnownOne, TLO, Depth+1))
815      return true;
816    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
817    KnownZero = KnownZero.zext(BitWidth);
818    KnownOne = KnownOne.zext(BitWidth);
819    KnownZero |= NewBits;
820    break;
821  }
822  case ISD::SIGN_EXTEND: {
823    EVT InVT = Op.getOperand(0).getValueType();
824    unsigned InBits = InVT.getScalarType().getSizeInBits();
825    APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
826    APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
827    APInt NewBits   = ~InMask & NewMask;
828
829    // If none of the top bits are demanded, convert this into an any_extend.
830    if (NewBits == 0)
831      return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
832                                              Op.getValueType(),
833                                              Op.getOperand(0)));
834
835    // Since some of the sign extended bits are demanded, we know that the sign
836    // bit is demanded.
837    APInt InDemandedBits = InMask & NewMask;
838    InDemandedBits |= InSignBit;
839    InDemandedBits = InDemandedBits.trunc(InBits);
840
841    if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
842                             KnownOne, TLO, Depth+1))
843      return true;
844    KnownZero = KnownZero.zext(BitWidth);
845    KnownOne = KnownOne.zext(BitWidth);
846
847    // If the sign bit is known zero, convert this to a zero extend.
848    if (KnownZero.intersects(InSignBit))
849      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
850                                               Op.getValueType(),
851                                               Op.getOperand(0)));
852
853    // If the sign bit is known one, the top bits match.
854    if (KnownOne.intersects(InSignBit)) {
855      KnownOne |= NewBits;
856      assert((KnownZero & NewBits) == 0);
857    } else {   // Otherwise, top bits aren't known.
858      assert((KnownOne & NewBits) == 0);
859      assert((KnownZero & NewBits) == 0);
860    }
861    break;
862  }
863  case ISD::ANY_EXTEND: {
864    unsigned OperandBitWidth =
865      Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
866    APInt InMask = NewMask.trunc(OperandBitWidth);
867    if (SimplifyDemandedBits(Op.getOperand(0), InMask,
868                             KnownZero, KnownOne, TLO, Depth+1))
869      return true;
870    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
871    KnownZero = KnownZero.zext(BitWidth);
872    KnownOne = KnownOne.zext(BitWidth);
873    break;
874  }
875  case ISD::TRUNCATE: {
876    // Simplify the input, using demanded bit information, and compute the known
877    // zero/one bits live out.
878    unsigned OperandBitWidth =
879      Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
880    APInt TruncMask = NewMask.zext(OperandBitWidth);
881    if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
882                             KnownZero, KnownOne, TLO, Depth+1))
883      return true;
884    KnownZero = KnownZero.trunc(BitWidth);
885    KnownOne = KnownOne.trunc(BitWidth);
886
887    // If the input is only used by this truncate, see if we can shrink it based
888    // on the known demanded bits.
889    if (Op.getOperand(0).getNode()->hasOneUse()) {
890      SDValue In = Op.getOperand(0);
891      switch (In.getOpcode()) {
892      default: break;
893      case ISD::SRL:
894        // Shrink SRL by a constant if none of the high bits shifted in are
895        // demanded.
896        if (TLO.LegalTypes() &&
897            !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
898          // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
899          // undesirable.
900          break;
901        ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
902        if (!ShAmt)
903          break;
904        SDValue Shift = In.getOperand(1);
905        if (TLO.LegalTypes()) {
906          uint64_t ShVal = ShAmt->getZExtValue();
907          Shift =
908            TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
909        }
910
911        APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
912                                               OperandBitWidth - BitWidth);
913        HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
914
915        if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
916          // None of the shifted in bits are needed.  Add a truncate of the
917          // shift input, then shift it.
918          SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
919                                             Op.getValueType(),
920                                             In.getOperand(0));
921          return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
922                                                   Op.getValueType(),
923                                                   NewTrunc,
924                                                   Shift));
925        }
926        break;
927      }
928    }
929
930    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
931    break;
932  }
933  case ISD::AssertZext: {
934    // AssertZext demands all of the high bits, plus any of the low bits
935    // demanded by its users.
936    EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
937    APInt InMask = APInt::getLowBitsSet(BitWidth,
938                                        VT.getSizeInBits());
939    if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
940                             KnownZero, KnownOne, TLO, Depth+1))
941      return true;
942    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
943
944    KnownZero |= ~InMask & NewMask;
945    break;
946  }
947  case ISD::BITCAST:
948    // If this is an FP->Int bitcast and if the sign bit is the only
949    // thing demanded, turn this into a FGETSIGN.
950    if (!TLO.LegalOperations() &&
951        !Op.getValueType().isVector() &&
952        !Op.getOperand(0).getValueType().isVector() &&
953        NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
954        Op.getOperand(0).getValueType().isFloatingPoint()) {
955      bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
956      bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
957      if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
958        EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
959        // Make a FGETSIGN + SHL to move the sign bit into the appropriate
960        // place.  We expect the SHL to be eliminated by other optimizations.
961        SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
962        unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
963        if (!OpVTLegal && OpVTSizeInBits > 32)
964          Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
965        unsigned ShVal = Op.getValueType().getSizeInBits()-1;
966        SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
967        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
968                                                 Op.getValueType(),
969                                                 Sign, ShAmt));
970      }
971    }
972    break;
973  case ISD::ADD:
974  case ISD::MUL:
975  case ISD::SUB: {
976    // Add, Sub, and Mul don't demand any bits in positions beyond that
977    // of the highest bit demanded of them.
978    APInt LoMask = APInt::getLowBitsSet(BitWidth,
979                                        BitWidth - NewMask.countLeadingZeros());
980    if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
981                             KnownOne2, TLO, Depth+1))
982      return true;
983    if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
984                             KnownOne2, TLO, Depth+1))
985      return true;
986    // See if the operation should be performed at a smaller bit width.
987    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
988      return true;
989  }
990  // FALL THROUGH
991  default:
992    // Just use ComputeMaskedBits to compute output bits.
993    TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
994    break;
995  }
996
997  // If we know the value of all of the demanded bits, return this as a
998  // constant.
999  if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1000    return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1001
1002  return false;
1003}
1004
1005/// computeMaskedBitsForTargetNode - Determine which of the bits specified
1006/// in Mask are known to be either zero or one and return them in the
1007/// KnownZero/KnownOne bitsets.
1008void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1009                                                    APInt &KnownZero,
1010                                                    APInt &KnownOne,
1011                                                    const SelectionDAG &DAG,
1012                                                    unsigned Depth) const {
1013  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1014          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1015          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1016          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1017         "Should use MaskedValueIsZero if you don't know whether Op"
1018         " is a target node!");
1019  KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1020}
1021
1022/// ComputeNumSignBitsForTargetNode - This method can be implemented by
1023/// targets that want to expose additional information about sign bits to the
1024/// DAG Combiner.
1025unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1026                                                         unsigned Depth) const {
1027  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1028          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1029          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1030          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1031         "Should use ComputeNumSignBits if you don't know whether Op"
1032         " is a target node!");
1033  return 1;
1034}
1035
1036/// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1037/// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
1038/// determine which bit is set.
1039///
1040static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1041  // A left-shift of a constant one will have exactly one bit set, because
1042  // shifting the bit off the end is undefined.
1043  if (Val.getOpcode() == ISD::SHL)
1044    if (ConstantSDNode *C =
1045         dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1046      if (C->getAPIntValue() == 1)
1047        return true;
1048
1049  // Similarly, a right-shift of a constant sign-bit will have exactly
1050  // one bit set.
1051  if (Val.getOpcode() == ISD::SRL)
1052    if (ConstantSDNode *C =
1053         dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1054      if (C->getAPIntValue().isSignBit())
1055        return true;
1056
1057  // More could be done here, though the above checks are enough
1058  // to handle some common cases.
1059
1060  // Fall back to ComputeMaskedBits to catch other known cases.
1061  EVT OpVT = Val.getValueType();
1062  unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
1063  APInt KnownZero, KnownOne;
1064  DAG.ComputeMaskedBits(Val, KnownZero, KnownOne);
1065  return (KnownZero.countPopulation() == BitWidth - 1) &&
1066         (KnownOne.countPopulation() == 1);
1067}
1068
1069/// SimplifySetCC - Try to simplify a setcc built with the specified operands
1070/// and cc. If it is unable to simplify it, return a null SDValue.
1071SDValue
1072TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1073                              ISD::CondCode Cond, bool foldBooleans,
1074                              DAGCombinerInfo &DCI, SDLoc dl) const {
1075  SelectionDAG &DAG = DCI.DAG;
1076
1077  // These setcc operations always fold.
1078  switch (Cond) {
1079  default: break;
1080  case ISD::SETFALSE:
1081  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1082  case ISD::SETTRUE:
1083  case ISD::SETTRUE2: {
1084    TargetLowering::BooleanContent Cnt = getBooleanContents(VT.isVector());
1085    return DAG.getConstant(
1086        Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
1087  }
1088  }
1089
1090  // Ensure that the constant occurs on the RHS, and fold constant
1091  // comparisons.
1092  if (isa<ConstantSDNode>(N0.getNode()))
1093    return DAG.getSetCC(dl, VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1094
1095  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1096    const APInt &C1 = N1C->getAPIntValue();
1097
1098    // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1099    // equality comparison, then we're just comparing whether X itself is
1100    // zero.
1101    if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1102        N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1103        N0.getOperand(1).getOpcode() == ISD::Constant) {
1104      const APInt &ShAmt
1105        = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1106      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1107          ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1108        if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1109          // (srl (ctlz x), 5) == 0  -> X != 0
1110          // (srl (ctlz x), 5) != 1  -> X != 0
1111          Cond = ISD::SETNE;
1112        } else {
1113          // (srl (ctlz x), 5) != 0  -> X == 0
1114          // (srl (ctlz x), 5) == 1  -> X == 0
1115          Cond = ISD::SETEQ;
1116        }
1117        SDValue Zero = DAG.getConstant(0, N0.getValueType());
1118        return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1119                            Zero, Cond);
1120      }
1121    }
1122
1123    SDValue CTPOP = N0;
1124    // Look through truncs that don't change the value of a ctpop.
1125    if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1126      CTPOP = N0.getOperand(0);
1127
1128    if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1129        (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1130                        Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1131      EVT CTVT = CTPOP.getValueType();
1132      SDValue CTOp = CTPOP.getOperand(0);
1133
1134      // (ctpop x) u< 2 -> (x & x-1) == 0
1135      // (ctpop x) u> 1 -> (x & x-1) != 0
1136      if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1137        SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1138                                  DAG.getConstant(1, CTVT));
1139        SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1140        ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1141        return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
1142      }
1143
1144      // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1145    }
1146
1147    // (zext x) == C --> x == (trunc C)
1148    if (DCI.isBeforeLegalize() && N0->hasOneUse() &&
1149        (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1150      unsigned MinBits = N0.getValueSizeInBits();
1151      SDValue PreZExt;
1152      if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1153        // ZExt
1154        MinBits = N0->getOperand(0).getValueSizeInBits();
1155        PreZExt = N0->getOperand(0);
1156      } else if (N0->getOpcode() == ISD::AND) {
1157        // DAGCombine turns costly ZExts into ANDs
1158        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1159          if ((C->getAPIntValue()+1).isPowerOf2()) {
1160            MinBits = C->getAPIntValue().countTrailingOnes();
1161            PreZExt = N0->getOperand(0);
1162          }
1163      } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
1164        // ZEXTLOAD
1165        if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1166          MinBits = LN0->getMemoryVT().getSizeInBits();
1167          PreZExt = N0;
1168        }
1169      }
1170
1171      // Make sure we're not losing bits from the constant.
1172      if (MinBits > 0 &&
1173          MinBits < C1.getBitWidth() && MinBits >= C1.getActiveBits()) {
1174        EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1175        if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1176          // Will get folded away.
1177          SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt);
1178          SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
1179          return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1180        }
1181      }
1182    }
1183
1184    // If the LHS is '(and load, const)', the RHS is 0,
1185    // the test is for equality or unsigned, and all 1 bits of the const are
1186    // in the same partial word, see if we can shorten the load.
1187    if (DCI.isBeforeLegalize() &&
1188        !ISD::isSignedIntSetCC(Cond) &&
1189        N0.getOpcode() == ISD::AND && C1 == 0 &&
1190        N0.getNode()->hasOneUse() &&
1191        isa<LoadSDNode>(N0.getOperand(0)) &&
1192        N0.getOperand(0).getNode()->hasOneUse() &&
1193        isa<ConstantSDNode>(N0.getOperand(1))) {
1194      LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1195      APInt bestMask;
1196      unsigned bestWidth = 0, bestOffset = 0;
1197      if (!Lod->isVolatile() && Lod->isUnindexed()) {
1198        unsigned origWidth = N0.getValueType().getSizeInBits();
1199        unsigned maskWidth = origWidth;
1200        // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1201        // 8 bits, but have to be careful...
1202        if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1203          origWidth = Lod->getMemoryVT().getSizeInBits();
1204        const APInt &Mask =
1205          cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1206        for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1207          APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1208          for (unsigned offset=0; offset<origWidth/width; offset++) {
1209            if ((newMask & Mask) == Mask) {
1210              if (!getDataLayout()->isLittleEndian())
1211                bestOffset = (origWidth/width - offset - 1) * (width/8);
1212              else
1213                bestOffset = (uint64_t)offset * (width/8);
1214              bestMask = Mask.lshr(offset * (width/8) * 8);
1215              bestWidth = width;
1216              break;
1217            }
1218            newMask = newMask << width;
1219          }
1220        }
1221      }
1222      if (bestWidth) {
1223        EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1224        if (newVT.isRound()) {
1225          EVT PtrType = Lod->getOperand(1).getValueType();
1226          SDValue Ptr = Lod->getBasePtr();
1227          if (bestOffset != 0)
1228            Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1229                              DAG.getConstant(bestOffset, PtrType));
1230          unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1231          SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
1232                                Lod->getPointerInfo().getWithOffset(bestOffset),
1233                                        false, false, false, NewAlign);
1234          return DAG.getSetCC(dl, VT,
1235                              DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1236                                      DAG.getConstant(bestMask.trunc(bestWidth),
1237                                                      newVT)),
1238                              DAG.getConstant(0LL, newVT), Cond);
1239        }
1240      }
1241    }
1242
1243    // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1244    if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1245      unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1246
1247      // If the comparison constant has bits in the upper part, the
1248      // zero-extended value could never match.
1249      if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1250                                              C1.getBitWidth() - InSize))) {
1251        switch (Cond) {
1252        case ISD::SETUGT:
1253        case ISD::SETUGE:
1254        case ISD::SETEQ: return DAG.getConstant(0, VT);
1255        case ISD::SETULT:
1256        case ISD::SETULE:
1257        case ISD::SETNE: return DAG.getConstant(1, VT);
1258        case ISD::SETGT:
1259        case ISD::SETGE:
1260          // True if the sign bit of C1 is set.
1261          return DAG.getConstant(C1.isNegative(), VT);
1262        case ISD::SETLT:
1263        case ISD::SETLE:
1264          // True if the sign bit of C1 isn't set.
1265          return DAG.getConstant(C1.isNonNegative(), VT);
1266        default:
1267          break;
1268        }
1269      }
1270
1271      // Otherwise, we can perform the comparison with the low bits.
1272      switch (Cond) {
1273      case ISD::SETEQ:
1274      case ISD::SETNE:
1275      case ISD::SETUGT:
1276      case ISD::SETUGE:
1277      case ISD::SETULT:
1278      case ISD::SETULE: {
1279        EVT newVT = N0.getOperand(0).getValueType();
1280        if (DCI.isBeforeLegalizeOps() ||
1281            (isOperationLegal(ISD::SETCC, newVT) &&
1282             getCondCodeAction(Cond, newVT.getSimpleVT())==Legal))
1283          return DAG.getSetCC(dl, VT, N0.getOperand(0),
1284                              DAG.getConstant(C1.trunc(InSize), newVT),
1285                              Cond);
1286        break;
1287      }
1288      default:
1289        break;   // todo, be more careful with signed comparisons
1290      }
1291    } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1292               (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1293      EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1294      unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1295      EVT ExtDstTy = N0.getValueType();
1296      unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1297
1298      // If the constant doesn't fit into the number of bits for the source of
1299      // the sign extension, it is impossible for both sides to be equal.
1300      if (C1.getMinSignedBits() > ExtSrcTyBits)
1301        return DAG.getConstant(Cond == ISD::SETNE, VT);
1302
1303      SDValue ZextOp;
1304      EVT Op0Ty = N0.getOperand(0).getValueType();
1305      if (Op0Ty == ExtSrcTy) {
1306        ZextOp = N0.getOperand(0);
1307      } else {
1308        APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1309        ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1310                              DAG.getConstant(Imm, Op0Ty));
1311      }
1312      if (!DCI.isCalledByLegalizer())
1313        DCI.AddToWorklist(ZextOp.getNode());
1314      // Otherwise, make this a use of a zext.
1315      return DAG.getSetCC(dl, VT, ZextOp,
1316                          DAG.getConstant(C1 & APInt::getLowBitsSet(
1317                                                              ExtDstTyBits,
1318                                                              ExtSrcTyBits),
1319                                          ExtDstTy),
1320                          Cond);
1321    } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1322                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1323      // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1324      if (N0.getOpcode() == ISD::SETCC &&
1325          isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1326        bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1327        if (TrueWhenTrue)
1328          return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1329        // Invert the condition.
1330        ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1331        CC = ISD::getSetCCInverse(CC,
1332                                  N0.getOperand(0).getValueType().isInteger());
1333        return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1334      }
1335
1336      if ((N0.getOpcode() == ISD::XOR ||
1337           (N0.getOpcode() == ISD::AND &&
1338            N0.getOperand(0).getOpcode() == ISD::XOR &&
1339            N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1340          isa<ConstantSDNode>(N0.getOperand(1)) &&
1341          cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1342        // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1343        // can only do this if the top bits are known zero.
1344        unsigned BitWidth = N0.getValueSizeInBits();
1345        if (DAG.MaskedValueIsZero(N0,
1346                                  APInt::getHighBitsSet(BitWidth,
1347                                                        BitWidth-1))) {
1348          // Okay, get the un-inverted input value.
1349          SDValue Val;
1350          if (N0.getOpcode() == ISD::XOR)
1351            Val = N0.getOperand(0);
1352          else {
1353            assert(N0.getOpcode() == ISD::AND &&
1354                    N0.getOperand(0).getOpcode() == ISD::XOR);
1355            // ((X^1)&1)^1 -> X & 1
1356            Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1357                              N0.getOperand(0).getOperand(0),
1358                              N0.getOperand(1));
1359          }
1360
1361          return DAG.getSetCC(dl, VT, Val, N1,
1362                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1363        }
1364      } else if (N1C->getAPIntValue() == 1 &&
1365                 (VT == MVT::i1 ||
1366                  getBooleanContents(false) == ZeroOrOneBooleanContent)) {
1367        SDValue Op0 = N0;
1368        if (Op0.getOpcode() == ISD::TRUNCATE)
1369          Op0 = Op0.getOperand(0);
1370
1371        if ((Op0.getOpcode() == ISD::XOR) &&
1372            Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1373            Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1374          // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1375          Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1376          return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1377                              Cond);
1378        }
1379        if (Op0.getOpcode() == ISD::AND &&
1380            isa<ConstantSDNode>(Op0.getOperand(1)) &&
1381            cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1382          // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1383          if (Op0.getValueType().bitsGT(VT))
1384            Op0 = DAG.getNode(ISD::AND, dl, VT,
1385                          DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1386                          DAG.getConstant(1, VT));
1387          else if (Op0.getValueType().bitsLT(VT))
1388            Op0 = DAG.getNode(ISD::AND, dl, VT,
1389                        DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1390                        DAG.getConstant(1, VT));
1391
1392          return DAG.getSetCC(dl, VT, Op0,
1393                              DAG.getConstant(0, Op0.getValueType()),
1394                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1395        }
1396        if (Op0.getOpcode() == ISD::AssertZext &&
1397            cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1398          return DAG.getSetCC(dl, VT, Op0,
1399                              DAG.getConstant(0, Op0.getValueType()),
1400                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1401      }
1402    }
1403
1404    APInt MinVal, MaxVal;
1405    unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1406    if (ISD::isSignedIntSetCC(Cond)) {
1407      MinVal = APInt::getSignedMinValue(OperandBitSize);
1408      MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1409    } else {
1410      MinVal = APInt::getMinValue(OperandBitSize);
1411      MaxVal = APInt::getMaxValue(OperandBitSize);
1412    }
1413
1414    // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1415    if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1416      if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
1417      // X >= C0 --> X > (C0-1)
1418      return DAG.getSetCC(dl, VT, N0,
1419                          DAG.getConstant(C1-1, N1.getValueType()),
1420                          (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1421    }
1422
1423    if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1424      if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
1425      // X <= C0 --> X < (C0+1)
1426      return DAG.getSetCC(dl, VT, N0,
1427                          DAG.getConstant(C1+1, N1.getValueType()),
1428                          (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1429    }
1430
1431    if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1432      return DAG.getConstant(0, VT);      // X < MIN --> false
1433    if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1434      return DAG.getConstant(1, VT);      // X >= MIN --> true
1435    if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1436      return DAG.getConstant(0, VT);      // X > MAX --> false
1437    if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1438      return DAG.getConstant(1, VT);      // X <= MAX --> true
1439
1440    // Canonicalize setgt X, Min --> setne X, Min
1441    if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1442      return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1443    // Canonicalize setlt X, Max --> setne X, Max
1444    if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1445      return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1446
1447    // If we have setult X, 1, turn it into seteq X, 0
1448    if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1449      return DAG.getSetCC(dl, VT, N0,
1450                          DAG.getConstant(MinVal, N0.getValueType()),
1451                          ISD::SETEQ);
1452    // If we have setugt X, Max-1, turn it into seteq X, Max
1453    if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1454      return DAG.getSetCC(dl, VT, N0,
1455                          DAG.getConstant(MaxVal, N0.getValueType()),
1456                          ISD::SETEQ);
1457
1458    // If we have "setcc X, C0", check to see if we can shrink the immediate
1459    // by changing cc.
1460
1461    // SETUGT X, SINTMAX  -> SETLT X, 0
1462    if (Cond == ISD::SETUGT &&
1463        C1 == APInt::getSignedMaxValue(OperandBitSize))
1464      return DAG.getSetCC(dl, VT, N0,
1465                          DAG.getConstant(0, N1.getValueType()),
1466                          ISD::SETLT);
1467
1468    // SETULT X, SINTMIN  -> SETGT X, -1
1469    if (Cond == ISD::SETULT &&
1470        C1 == APInt::getSignedMinValue(OperandBitSize)) {
1471      SDValue ConstMinusOne =
1472          DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
1473                          N1.getValueType());
1474      return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1475    }
1476
1477    // Fold bit comparisons when we can.
1478    if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1479        (VT == N0.getValueType() ||
1480         (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1481        N0.getOpcode() == ISD::AND)
1482      if (ConstantSDNode *AndRHS =
1483                  dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1484        EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
1485          getPointerTy() : getShiftAmountTy(N0.getValueType());
1486        if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1487          // Perform the xform if the AND RHS is a single bit.
1488          if (AndRHS->getAPIntValue().isPowerOf2()) {
1489            return DAG.getNode(ISD::TRUNCATE, dl, VT,
1490                              DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1491                   DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
1492          }
1493        } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1494          // (X & 8) == 8  -->  (X & 8) >> 3
1495          // Perform the xform if C1 is a single bit.
1496          if (C1.isPowerOf2()) {
1497            return DAG.getNode(ISD::TRUNCATE, dl, VT,
1498                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1499                                      DAG.getConstant(C1.logBase2(), ShiftTy)));
1500          }
1501        }
1502      }
1503
1504    if (C1.getMinSignedBits() <= 64 &&
1505        !isLegalICmpImmediate(C1.getSExtValue())) {
1506      // (X & -256) == 256 -> (X >> 8) == 1
1507      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1508          N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
1509        if (ConstantSDNode *AndRHS =
1510            dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1511          const APInt &AndRHSC = AndRHS->getAPIntValue();
1512          if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1513            unsigned ShiftBits = AndRHSC.countTrailingZeros();
1514            EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
1515              getPointerTy() : getShiftAmountTy(N0.getValueType());
1516            EVT CmpTy = N0.getValueType();
1517            SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
1518                                        DAG.getConstant(ShiftBits, ShiftTy));
1519            SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
1520            return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1521          }
1522        }
1523      } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1524                 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1525        bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1526        // X <  0x100000000 -> (X >> 32) <  1
1527        // X >= 0x100000000 -> (X >> 32) >= 1
1528        // X <= 0x0ffffffff -> (X >> 32) <  1
1529        // X >  0x0ffffffff -> (X >> 32) >= 1
1530        unsigned ShiftBits;
1531        APInt NewC = C1;
1532        ISD::CondCode NewCond = Cond;
1533        if (AdjOne) {
1534          ShiftBits = C1.countTrailingOnes();
1535          NewC = NewC + 1;
1536          NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1537        } else {
1538          ShiftBits = C1.countTrailingZeros();
1539        }
1540        NewC = NewC.lshr(ShiftBits);
1541        if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
1542          EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
1543            getPointerTy() : getShiftAmountTy(N0.getValueType());
1544          EVT CmpTy = N0.getValueType();
1545          SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
1546                                      DAG.getConstant(ShiftBits, ShiftTy));
1547          SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
1548          return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1549        }
1550      }
1551    }
1552  }
1553
1554  if (isa<ConstantFPSDNode>(N0.getNode())) {
1555    // Constant fold or commute setcc.
1556    SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
1557    if (O.getNode()) return O;
1558  } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1559    // If the RHS of an FP comparison is a constant, simplify it away in
1560    // some cases.
1561    if (CFP->getValueAPF().isNaN()) {
1562      // If an operand is known to be a nan, we can fold it.
1563      switch (ISD::getUnorderedFlavor(Cond)) {
1564      default: llvm_unreachable("Unknown flavor!");
1565      case 0:  // Known false.
1566        return DAG.getConstant(0, VT);
1567      case 1:  // Known true.
1568        return DAG.getConstant(1, VT);
1569      case 2:  // Undefined.
1570        return DAG.getUNDEF(VT);
1571      }
1572    }
1573
1574    // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
1575    // constant if knowing that the operand is non-nan is enough.  We prefer to
1576    // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1577    // materialize 0.0.
1578    if (Cond == ISD::SETO || Cond == ISD::SETUO)
1579      return DAG.getSetCC(dl, VT, N0, N0, Cond);
1580
1581    // If the condition is not legal, see if we can find an equivalent one
1582    // which is legal.
1583    if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1584      // If the comparison was an awkward floating-point == or != and one of
1585      // the comparison operands is infinity or negative infinity, convert the
1586      // condition to a less-awkward <= or >=.
1587      if (CFP->getValueAPF().isInfinity()) {
1588        if (CFP->getValueAPF().isNegative()) {
1589          if (Cond == ISD::SETOEQ &&
1590              isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1591            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1592          if (Cond == ISD::SETUEQ &&
1593              isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1594            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1595          if (Cond == ISD::SETUNE &&
1596              isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1597            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1598          if (Cond == ISD::SETONE &&
1599              isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1600            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1601        } else {
1602          if (Cond == ISD::SETOEQ &&
1603              isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1604            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1605          if (Cond == ISD::SETUEQ &&
1606              isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1607            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1608          if (Cond == ISD::SETUNE &&
1609              isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1610            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1611          if (Cond == ISD::SETONE &&
1612              isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1613            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1614        }
1615      }
1616    }
1617  }
1618
1619  if (N0 == N1) {
1620    // The sext(setcc()) => setcc() optimization relies on the appropriate
1621    // constant being emitted.
1622    uint64_t EqVal = 0;
1623    switch (getBooleanContents(N0.getValueType().isVector())) {
1624    case UndefinedBooleanContent:
1625    case ZeroOrOneBooleanContent:
1626      EqVal = ISD::isTrueWhenEqual(Cond);
1627      break;
1628    case ZeroOrNegativeOneBooleanContent:
1629      EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1630      break;
1631    }
1632
1633    // We can always fold X == X for integer setcc's.
1634    if (N0.getValueType().isInteger()) {
1635      return DAG.getConstant(EqVal, VT);
1636    }
1637    unsigned UOF = ISD::getUnorderedFlavor(Cond);
1638    if (UOF == 2)   // FP operators that are undefined on NaNs.
1639      return DAG.getConstant(EqVal, VT);
1640    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1641      return DAG.getConstant(EqVal, VT);
1642    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
1643    // if it is not already.
1644    ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1645    if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
1646          getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
1647      return DAG.getSetCC(dl, VT, N0, N1, NewCond);
1648  }
1649
1650  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1651      N0.getValueType().isInteger()) {
1652    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1653        N0.getOpcode() == ISD::XOR) {
1654      // Simplify (X+Y) == (X+Z) -->  Y == Z
1655      if (N0.getOpcode() == N1.getOpcode()) {
1656        if (N0.getOperand(0) == N1.getOperand(0))
1657          return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
1658        if (N0.getOperand(1) == N1.getOperand(1))
1659          return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
1660        if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1661          // If X op Y == Y op X, try other combinations.
1662          if (N0.getOperand(0) == N1.getOperand(1))
1663            return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
1664                                Cond);
1665          if (N0.getOperand(1) == N1.getOperand(0))
1666            return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
1667                                Cond);
1668        }
1669      }
1670
1671      // If RHS is a legal immediate value for a compare instruction, we need
1672      // to be careful about increasing register pressure needlessly.
1673      bool LegalRHSImm = false;
1674
1675      if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1676        if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1677          // Turn (X+C1) == C2 --> X == C2-C1
1678          if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
1679            return DAG.getSetCC(dl, VT, N0.getOperand(0),
1680                                DAG.getConstant(RHSC->getAPIntValue()-
1681                                                LHSR->getAPIntValue(),
1682                                N0.getValueType()), Cond);
1683          }
1684
1685          // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1686          if (N0.getOpcode() == ISD::XOR)
1687            // If we know that all of the inverted bits are zero, don't bother
1688            // performing the inversion.
1689            if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1690              return
1691                DAG.getSetCC(dl, VT, N0.getOperand(0),
1692                             DAG.getConstant(LHSR->getAPIntValue() ^
1693                                               RHSC->getAPIntValue(),
1694                                             N0.getValueType()),
1695                             Cond);
1696        }
1697
1698        // Turn (C1-X) == C2 --> X == C1-C2
1699        if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1700          if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
1701            return
1702              DAG.getSetCC(dl, VT, N0.getOperand(1),
1703                           DAG.getConstant(SUBC->getAPIntValue() -
1704                                             RHSC->getAPIntValue(),
1705                                           N0.getValueType()),
1706                           Cond);
1707          }
1708        }
1709
1710        // Could RHSC fold directly into a compare?
1711        if (RHSC->getValueType(0).getSizeInBits() <= 64)
1712          LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
1713      }
1714
1715      // Simplify (X+Z) == X -->  Z == 0
1716      // Don't do this if X is an immediate that can fold into a cmp
1717      // instruction and X+Z has other uses. It could be an induction variable
1718      // chain, and the transform would increase register pressure.
1719      if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
1720        if (N0.getOperand(0) == N1)
1721          return DAG.getSetCC(dl, VT, N0.getOperand(1),
1722                              DAG.getConstant(0, N0.getValueType()), Cond);
1723        if (N0.getOperand(1) == N1) {
1724          if (DAG.isCommutativeBinOp(N0.getOpcode()))
1725            return DAG.getSetCC(dl, VT, N0.getOperand(0),
1726                                DAG.getConstant(0, N0.getValueType()), Cond);
1727          if (N0.getNode()->hasOneUse()) {
1728            assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1729            // (Z-X) == X  --> Z == X<<1
1730            SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
1731                       DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
1732            if (!DCI.isCalledByLegalizer())
1733              DCI.AddToWorklist(SH.getNode());
1734            return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
1735          }
1736        }
1737      }
1738    }
1739
1740    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1741        N1.getOpcode() == ISD::XOR) {
1742      // Simplify  X == (X+Z) -->  Z == 0
1743      if (N1.getOperand(0) == N0)
1744        return DAG.getSetCC(dl, VT, N1.getOperand(1),
1745                        DAG.getConstant(0, N1.getValueType()), Cond);
1746      if (N1.getOperand(1) == N0) {
1747        if (DAG.isCommutativeBinOp(N1.getOpcode()))
1748          return DAG.getSetCC(dl, VT, N1.getOperand(0),
1749                          DAG.getConstant(0, N1.getValueType()), Cond);
1750        if (N1.getNode()->hasOneUse()) {
1751          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1752          // X == (Z-X)  --> X<<1 == Z
1753          SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
1754                       DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
1755          if (!DCI.isCalledByLegalizer())
1756            DCI.AddToWorklist(SH.getNode());
1757          return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
1758        }
1759      }
1760    }
1761
1762    // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
1763    // Note that where y is variable and is known to have at most
1764    // one bit set (for example, if it is z&1) we cannot do this;
1765    // the expressions are not equivalent when y==0.
1766    if (N0.getOpcode() == ISD::AND)
1767      if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
1768        if (ValueHasExactlyOneBitSet(N1, DAG)) {
1769          Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1770          SDValue Zero = DAG.getConstant(0, N1.getValueType());
1771          return DAG.getSetCC(dl, VT, N0, Zero, Cond);
1772        }
1773      }
1774    if (N1.getOpcode() == ISD::AND)
1775      if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
1776        if (ValueHasExactlyOneBitSet(N0, DAG)) {
1777          Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1778          SDValue Zero = DAG.getConstant(0, N0.getValueType());
1779          return DAG.getSetCC(dl, VT, N1, Zero, Cond);
1780        }
1781      }
1782  }
1783
1784  // Fold away ALL boolean setcc's.
1785  SDValue Temp;
1786  if (N0.getValueType() == MVT::i1 && foldBooleans) {
1787    switch (Cond) {
1788    default: llvm_unreachable("Unknown integer setcc!");
1789    case ISD::SETEQ:  // X == Y  -> ~(X^Y)
1790      Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
1791      N0 = DAG.getNOT(dl, Temp, MVT::i1);
1792      if (!DCI.isCalledByLegalizer())
1793        DCI.AddToWorklist(Temp.getNode());
1794      break;
1795    case ISD::SETNE:  // X != Y   -->  (X^Y)
1796      N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
1797      break;
1798    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
1799    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
1800      Temp = DAG.getNOT(dl, N0, MVT::i1);
1801      N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
1802      if (!DCI.isCalledByLegalizer())
1803        DCI.AddToWorklist(Temp.getNode());
1804      break;
1805    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
1806    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
1807      Temp = DAG.getNOT(dl, N1, MVT::i1);
1808      N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
1809      if (!DCI.isCalledByLegalizer())
1810        DCI.AddToWorklist(Temp.getNode());
1811      break;
1812    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
1813    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
1814      Temp = DAG.getNOT(dl, N0, MVT::i1);
1815      N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
1816      if (!DCI.isCalledByLegalizer())
1817        DCI.AddToWorklist(Temp.getNode());
1818      break;
1819    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
1820    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
1821      Temp = DAG.getNOT(dl, N1, MVT::i1);
1822      N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
1823      break;
1824    }
1825    if (VT != MVT::i1) {
1826      if (!DCI.isCalledByLegalizer())
1827        DCI.AddToWorklist(N0.getNode());
1828      // FIXME: If running after legalize, we probably can't do this.
1829      N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
1830    }
1831    return N0;
1832  }
1833
1834  // Could not fold it.
1835  return SDValue();
1836}
1837
1838/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
1839/// node is a GlobalAddress + offset.
1840bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
1841                                    int64_t &Offset) const {
1842  if (isa<GlobalAddressSDNode>(N)) {
1843    GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
1844    GA = GASD->getGlobal();
1845    Offset += GASD->getOffset();
1846    return true;
1847  }
1848
1849  if (N->getOpcode() == ISD::ADD) {
1850    SDValue N1 = N->getOperand(0);
1851    SDValue N2 = N->getOperand(1);
1852    if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
1853      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
1854      if (V) {
1855        Offset += V->getSExtValue();
1856        return true;
1857      }
1858    } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
1859      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
1860      if (V) {
1861        Offset += V->getSExtValue();
1862        return true;
1863      }
1864    }
1865  }
1866
1867  return false;
1868}
1869
1870
1871SDValue TargetLowering::
1872PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1873  // Default implementation: no optimization.
1874  return SDValue();
1875}
1876
1877//===----------------------------------------------------------------------===//
1878//  Inline Assembler Implementation Methods
1879//===----------------------------------------------------------------------===//
1880
1881
1882TargetLowering::ConstraintType
1883TargetLowering::getConstraintType(const std::string &Constraint) const {
1884  unsigned S = Constraint.size();
1885
1886  if (S == 1) {
1887    switch (Constraint[0]) {
1888    default: break;
1889    case 'r': return C_RegisterClass;
1890    case 'm':    // memory
1891    case 'o':    // offsetable
1892    case 'V':    // not offsetable
1893      return C_Memory;
1894    case 'i':    // Simple Integer or Relocatable Constant
1895    case 'n':    // Simple Integer
1896    case 'E':    // Floating Point Constant
1897    case 'F':    // Floating Point Constant
1898    case 's':    // Relocatable Constant
1899    case 'p':    // Address.
1900    case 'X':    // Allow ANY value.
1901    case 'I':    // Target registers.
1902    case 'J':
1903    case 'K':
1904    case 'L':
1905    case 'M':
1906    case 'N':
1907    case 'O':
1908    case 'P':
1909    case '<':
1910    case '>':
1911      return C_Other;
1912    }
1913  }
1914
1915  if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
1916    if (S == 8 && !Constraint.compare(1, 6, "memory", 6))  // "{memory}"
1917      return C_Memory;
1918    return C_Register;
1919  }
1920  return C_Unknown;
1921}
1922
1923/// LowerXConstraint - try to replace an X constraint, which matches anything,
1924/// with another that has more specific requirements based on the type of the
1925/// corresponding operand.
1926const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
1927  if (ConstraintVT.isInteger())
1928    return "r";
1929  if (ConstraintVT.isFloatingPoint())
1930    return "f";      // works for many targets
1931  return 0;
1932}
1933
1934/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1935/// vector.  If it is invalid, don't add anything to Ops.
1936void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
1937                                                  std::string &Constraint,
1938                                                  std::vector<SDValue> &Ops,
1939                                                  SelectionDAG &DAG) const {
1940
1941  if (Constraint.length() > 1) return;
1942
1943  char ConstraintLetter = Constraint[0];
1944  switch (ConstraintLetter) {
1945  default: break;
1946  case 'X':     // Allows any operand; labels (basic block) use this.
1947    if (Op.getOpcode() == ISD::BasicBlock) {
1948      Ops.push_back(Op);
1949      return;
1950    }
1951    // fall through
1952  case 'i':    // Simple Integer or Relocatable Constant
1953  case 'n':    // Simple Integer
1954  case 's': {  // Relocatable Constant
1955    // These operands are interested in values of the form (GV+C), where C may
1956    // be folded in as an offset of GV, or it may be explicitly added.  Also, it
1957    // is possible and fine if either GV or C are missing.
1958    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1959    GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1960
1961    // If we have "(add GV, C)", pull out GV/C
1962    if (Op.getOpcode() == ISD::ADD) {
1963      C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1964      GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1965      if (C == 0 || GA == 0) {
1966        C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1967        GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1968      }
1969      if (C == 0 || GA == 0)
1970        C = 0, GA = 0;
1971    }
1972
1973    // If we find a valid operand, map to the TargetXXX version so that the
1974    // value itself doesn't get selected.
1975    if (GA) {   // Either &GV   or   &GV+C
1976      if (ConstraintLetter != 'n') {
1977        int64_t Offs = GA->getOffset();
1978        if (C) Offs += C->getZExtValue();
1979        Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
1980                                                 C ? SDLoc(C) : SDLoc(),
1981                                                 Op.getValueType(), Offs));
1982        return;
1983      }
1984    }
1985    if (C) {   // just C, no GV.
1986      // Simple constants are not allowed for 's'.
1987      if (ConstraintLetter != 's') {
1988        // gcc prints these as sign extended.  Sign extend value to 64 bits
1989        // now; without this it would get ZExt'd later in
1990        // ScheduleDAGSDNodes::EmitNode, which is very generic.
1991        Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
1992                                            MVT::i64));
1993        return;
1994      }
1995    }
1996    break;
1997  }
1998  }
1999}
2000
2001std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
2002getRegForInlineAsmConstraint(const std::string &Constraint,
2003                             MVT VT) const {
2004  if (Constraint[0] != '{')
2005    return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
2006  assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2007
2008  // Remove the braces from around the name.
2009  StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2010
2011  std::pair<unsigned, const TargetRegisterClass*> R =
2012    std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2013
2014  // Figure out which register class contains this reg.
2015  const TargetRegisterInfo *RI = getTargetMachine().getRegisterInfo();
2016  for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2017       E = RI->regclass_end(); RCI != E; ++RCI) {
2018    const TargetRegisterClass *RC = *RCI;
2019
2020    // If none of the value types for this register class are valid, we
2021    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2022    if (!isLegalRC(RC))
2023      continue;
2024
2025    for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2026         I != E; ++I) {
2027      if (RegName.equals_lower(RI->getName(*I))) {
2028        std::pair<unsigned, const TargetRegisterClass*> S =
2029          std::make_pair(*I, RC);
2030
2031        // If this register class has the requested value type, return it,
2032        // otherwise keep searching and return the first class found
2033        // if no other is found which explicitly has the requested type.
2034        if (RC->hasType(VT))
2035          return S;
2036        else if (!R.second)
2037          R = S;
2038      }
2039    }
2040  }
2041
2042  return R;
2043}
2044
2045//===----------------------------------------------------------------------===//
2046// Constraint Selection.
2047
2048/// isMatchingInputConstraint - Return true of this is an input operand that is
2049/// a matching constraint like "4".
2050bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2051  assert(!ConstraintCode.empty() && "No known constraint!");
2052  return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2053}
2054
2055/// getMatchedOperand - If this is an input matching constraint, this method
2056/// returns the output operand it matches.
2057unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2058  assert(!ConstraintCode.empty() && "No known constraint!");
2059  return atoi(ConstraintCode.c_str());
2060}
2061
2062
2063/// ParseConstraints - Split up the constraint string from the inline
2064/// assembly value into the specific constraints and their prefixes,
2065/// and also tie in the associated operand values.
2066/// If this returns an empty vector, and if the constraint string itself
2067/// isn't empty, there was an error parsing.
2068TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints(
2069    ImmutableCallSite CS) const {
2070  /// ConstraintOperands - Information about all of the constraints.
2071  AsmOperandInfoVector ConstraintOperands;
2072  const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2073  unsigned maCount = 0; // Largest number of multiple alternative constraints.
2074
2075  // Do a prepass over the constraints, canonicalizing them, and building up the
2076  // ConstraintOperands list.
2077  InlineAsm::ConstraintInfoVector
2078    ConstraintInfos = IA->ParseConstraints();
2079
2080  unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2081  unsigned ResNo = 0;   // ResNo - The result number of the next output.
2082
2083  for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
2084    ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
2085    AsmOperandInfo &OpInfo = ConstraintOperands.back();
2086
2087    // Update multiple alternative constraint count.
2088    if (OpInfo.multipleAlternatives.size() > maCount)
2089      maCount = OpInfo.multipleAlternatives.size();
2090
2091    OpInfo.ConstraintVT = MVT::Other;
2092
2093    // Compute the value type for each operand.
2094    switch (OpInfo.Type) {
2095    case InlineAsm::isOutput:
2096      // Indirect outputs just consume an argument.
2097      if (OpInfo.isIndirect) {
2098        OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2099        break;
2100      }
2101
2102      // The return value of the call is this value.  As such, there is no
2103      // corresponding argument.
2104      assert(!CS.getType()->isVoidTy() &&
2105             "Bad inline asm!");
2106      if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2107        OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
2108      } else {
2109        assert(ResNo == 0 && "Asm only has one result!");
2110        OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
2111      }
2112      ++ResNo;
2113      break;
2114    case InlineAsm::isInput:
2115      OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2116      break;
2117    case InlineAsm::isClobber:
2118      // Nothing to do.
2119      break;
2120    }
2121
2122    if (OpInfo.CallOperandVal) {
2123      llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2124      if (OpInfo.isIndirect) {
2125        llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2126        if (!PtrTy)
2127          report_fatal_error("Indirect operand for inline asm not a pointer!");
2128        OpTy = PtrTy->getElementType();
2129      }
2130
2131      // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2132      if (StructType *STy = dyn_cast<StructType>(OpTy))
2133        if (STy->getNumElements() == 1)
2134          OpTy = STy->getElementType(0);
2135
2136      // If OpTy is not a single value, it may be a struct/union that we
2137      // can tile with integers.
2138      if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2139        unsigned BitSize = getDataLayout()->getTypeSizeInBits(OpTy);
2140        switch (BitSize) {
2141        default: break;
2142        case 1:
2143        case 8:
2144        case 16:
2145        case 32:
2146        case 64:
2147        case 128:
2148          OpInfo.ConstraintVT =
2149            MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2150          break;
2151        }
2152      } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2153        OpInfo.ConstraintVT = MVT::getIntegerVT(
2154            8*getDataLayout()->getPointerSize(PT->getAddressSpace()));
2155      } else {
2156        OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2157      }
2158    }
2159  }
2160
2161  // If we have multiple alternative constraints, select the best alternative.
2162  if (ConstraintInfos.size()) {
2163    if (maCount) {
2164      unsigned bestMAIndex = 0;
2165      int bestWeight = -1;
2166      // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2167      int weight = -1;
2168      unsigned maIndex;
2169      // Compute the sums of the weights for each alternative, keeping track
2170      // of the best (highest weight) one so far.
2171      for (maIndex = 0; maIndex < maCount; ++maIndex) {
2172        int weightSum = 0;
2173        for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2174            cIndex != eIndex; ++cIndex) {
2175          AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2176          if (OpInfo.Type == InlineAsm::isClobber)
2177            continue;
2178
2179          // If this is an output operand with a matching input operand,
2180          // look up the matching input. If their types mismatch, e.g. one
2181          // is an integer, the other is floating point, or their sizes are
2182          // different, flag it as an maCantMatch.
2183          if (OpInfo.hasMatchingInput()) {
2184            AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2185            if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2186              if ((OpInfo.ConstraintVT.isInteger() !=
2187                   Input.ConstraintVT.isInteger()) ||
2188                  (OpInfo.ConstraintVT.getSizeInBits() !=
2189                   Input.ConstraintVT.getSizeInBits())) {
2190                weightSum = -1;  // Can't match.
2191                break;
2192              }
2193            }
2194          }
2195          weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2196          if (weight == -1) {
2197            weightSum = -1;
2198            break;
2199          }
2200          weightSum += weight;
2201        }
2202        // Update best.
2203        if (weightSum > bestWeight) {
2204          bestWeight = weightSum;
2205          bestMAIndex = maIndex;
2206        }
2207      }
2208
2209      // Now select chosen alternative in each constraint.
2210      for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2211          cIndex != eIndex; ++cIndex) {
2212        AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2213        if (cInfo.Type == InlineAsm::isClobber)
2214          continue;
2215        cInfo.selectAlternative(bestMAIndex);
2216      }
2217    }
2218  }
2219
2220  // Check and hook up tied operands, choose constraint code to use.
2221  for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2222      cIndex != eIndex; ++cIndex) {
2223    AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2224
2225    // If this is an output operand with a matching input operand, look up the
2226    // matching input. If their types mismatch, e.g. one is an integer, the
2227    // other is floating point, or their sizes are different, flag it as an
2228    // error.
2229    if (OpInfo.hasMatchingInput()) {
2230      AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2231
2232      if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2233        std::pair<unsigned, const TargetRegisterClass*> MatchRC =
2234          getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
2235                                       OpInfo.ConstraintVT);
2236        std::pair<unsigned, const TargetRegisterClass*> InputRC =
2237          getRegForInlineAsmConstraint(Input.ConstraintCode,
2238                                       Input.ConstraintVT);
2239        if ((OpInfo.ConstraintVT.isInteger() !=
2240             Input.ConstraintVT.isInteger()) ||
2241            (MatchRC.second != InputRC.second)) {
2242          report_fatal_error("Unsupported asm: input constraint"
2243                             " with a matching output constraint of"
2244                             " incompatible type!");
2245        }
2246      }
2247
2248    }
2249  }
2250
2251  return ConstraintOperands;
2252}
2253
2254
2255/// getConstraintGenerality - Return an integer indicating how general CT
2256/// is.
2257static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2258  switch (CT) {
2259  case TargetLowering::C_Other:
2260  case TargetLowering::C_Unknown:
2261    return 0;
2262  case TargetLowering::C_Register:
2263    return 1;
2264  case TargetLowering::C_RegisterClass:
2265    return 2;
2266  case TargetLowering::C_Memory:
2267    return 3;
2268  }
2269  llvm_unreachable("Invalid constraint type");
2270}
2271
2272/// Examine constraint type and operand type and determine a weight value.
2273/// This object must already have been set up with the operand type
2274/// and the current alternative constraint selected.
2275TargetLowering::ConstraintWeight
2276  TargetLowering::getMultipleConstraintMatchWeight(
2277    AsmOperandInfo &info, int maIndex) const {
2278  InlineAsm::ConstraintCodeVector *rCodes;
2279  if (maIndex >= (int)info.multipleAlternatives.size())
2280    rCodes = &info.Codes;
2281  else
2282    rCodes = &info.multipleAlternatives[maIndex].Codes;
2283  ConstraintWeight BestWeight = CW_Invalid;
2284
2285  // Loop over the options, keeping track of the most general one.
2286  for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2287    ConstraintWeight weight =
2288      getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2289    if (weight > BestWeight)
2290      BestWeight = weight;
2291  }
2292
2293  return BestWeight;
2294}
2295
2296/// Examine constraint type and operand type and determine a weight value.
2297/// This object must already have been set up with the operand type
2298/// and the current alternative constraint selected.
2299TargetLowering::ConstraintWeight
2300  TargetLowering::getSingleConstraintMatchWeight(
2301    AsmOperandInfo &info, const char *constraint) const {
2302  ConstraintWeight weight = CW_Invalid;
2303  Value *CallOperandVal = info.CallOperandVal;
2304    // If we don't have a value, we can't do a match,
2305    // but allow it at the lowest weight.
2306  if (CallOperandVal == NULL)
2307    return CW_Default;
2308  // Look at the constraint type.
2309  switch (*constraint) {
2310    case 'i': // immediate integer.
2311    case 'n': // immediate integer with a known value.
2312      if (isa<ConstantInt>(CallOperandVal))
2313        weight = CW_Constant;
2314      break;
2315    case 's': // non-explicit intregal immediate.
2316      if (isa<GlobalValue>(CallOperandVal))
2317        weight = CW_Constant;
2318      break;
2319    case 'E': // immediate float if host format.
2320    case 'F': // immediate float.
2321      if (isa<ConstantFP>(CallOperandVal))
2322        weight = CW_Constant;
2323      break;
2324    case '<': // memory operand with autodecrement.
2325    case '>': // memory operand with autoincrement.
2326    case 'm': // memory operand.
2327    case 'o': // offsettable memory operand
2328    case 'V': // non-offsettable memory operand
2329      weight = CW_Memory;
2330      break;
2331    case 'r': // general register.
2332    case 'g': // general register, memory operand or immediate integer.
2333              // note: Clang converts "g" to "imr".
2334      if (CallOperandVal->getType()->isIntegerTy())
2335        weight = CW_Register;
2336      break;
2337    case 'X': // any operand.
2338    default:
2339      weight = CW_Default;
2340      break;
2341  }
2342  return weight;
2343}
2344
2345/// ChooseConstraint - If there are multiple different constraints that we
2346/// could pick for this operand (e.g. "imr") try to pick the 'best' one.
2347/// This is somewhat tricky: constraints fall into four classes:
2348///    Other         -> immediates and magic values
2349///    Register      -> one specific register
2350///    RegisterClass -> a group of regs
2351///    Memory        -> memory
2352/// Ideally, we would pick the most specific constraint possible: if we have
2353/// something that fits into a register, we would pick it.  The problem here
2354/// is that if we have something that could either be in a register or in
2355/// memory that use of the register could cause selection of *other*
2356/// operands to fail: they might only succeed if we pick memory.  Because of
2357/// this the heuristic we use is:
2358///
2359///  1) If there is an 'other' constraint, and if the operand is valid for
2360///     that constraint, use it.  This makes us take advantage of 'i'
2361///     constraints when available.
2362///  2) Otherwise, pick the most general constraint present.  This prefers
2363///     'm' over 'r', for example.
2364///
2365static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2366                             const TargetLowering &TLI,
2367                             SDValue Op, SelectionDAG *DAG) {
2368  assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2369  unsigned BestIdx = 0;
2370  TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2371  int BestGenerality = -1;
2372
2373  // Loop over the options, keeping track of the most general one.
2374  for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2375    TargetLowering::ConstraintType CType =
2376      TLI.getConstraintType(OpInfo.Codes[i]);
2377
2378    // If this is an 'other' constraint, see if the operand is valid for it.
2379    // For example, on X86 we might have an 'rI' constraint.  If the operand
2380    // is an integer in the range [0..31] we want to use I (saving a load
2381    // of a register), otherwise we must use 'r'.
2382    if (CType == TargetLowering::C_Other && Op.getNode()) {
2383      assert(OpInfo.Codes[i].size() == 1 &&
2384             "Unhandled multi-letter 'other' constraint");
2385      std::vector<SDValue> ResultOps;
2386      TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2387                                       ResultOps, *DAG);
2388      if (!ResultOps.empty()) {
2389        BestType = CType;
2390        BestIdx = i;
2391        break;
2392      }
2393    }
2394
2395    // Things with matching constraints can only be registers, per gcc
2396    // documentation.  This mainly affects "g" constraints.
2397    if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2398      continue;
2399
2400    // This constraint letter is more general than the previous one, use it.
2401    int Generality = getConstraintGenerality(CType);
2402    if (Generality > BestGenerality) {
2403      BestType = CType;
2404      BestIdx = i;
2405      BestGenerality = Generality;
2406    }
2407  }
2408
2409  OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2410  OpInfo.ConstraintType = BestType;
2411}
2412
2413/// ComputeConstraintToUse - Determines the constraint code and constraint
2414/// type to use for the specific AsmOperandInfo, setting
2415/// OpInfo.ConstraintCode and OpInfo.ConstraintType.
2416void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2417                                            SDValue Op,
2418                                            SelectionDAG *DAG) const {
2419  assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2420
2421  // Single-letter constraints ('r') are very common.
2422  if (OpInfo.Codes.size() == 1) {
2423    OpInfo.ConstraintCode = OpInfo.Codes[0];
2424    OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2425  } else {
2426    ChooseConstraint(OpInfo, *this, Op, DAG);
2427  }
2428
2429  // 'X' matches anything.
2430  if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2431    // Labels and constants are handled elsewhere ('X' is the only thing
2432    // that matches labels).  For Functions, the type here is the type of
2433    // the result, which is not what we want to look at; leave them alone.
2434    Value *v = OpInfo.CallOperandVal;
2435    if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2436      OpInfo.CallOperandVal = v;
2437      return;
2438    }
2439
2440    // Otherwise, try to resolve it to something we know about by looking at
2441    // the actual operand type.
2442    if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2443      OpInfo.ConstraintCode = Repl;
2444      OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2445    }
2446  }
2447}
2448
2449/// \brief Given an exact SDIV by a constant, create a multiplication
2450/// with the multiplicative inverse of the constant.
2451SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2452                                       SelectionDAG &DAG) const {
2453  ConstantSDNode *C = cast<ConstantSDNode>(Op2);
2454  APInt d = C->getAPIntValue();
2455  assert(d != 0 && "Division by zero!");
2456
2457  // Shift the value upfront if it is even, so the LSB is one.
2458  unsigned ShAmt = d.countTrailingZeros();
2459  if (ShAmt) {
2460    // TODO: For UDIV use SRL instead of SRA.
2461    SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
2462    Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt);
2463    d = d.ashr(ShAmt);
2464  }
2465
2466  // Calculate the multiplicative inverse, using Newton's method.
2467  APInt t, xn = d;
2468  while ((t = d*xn) != 1)
2469    xn *= APInt(d.getBitWidth(), 2) - t;
2470
2471  Op2 = DAG.getConstant(xn, Op1.getValueType());
2472  return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2473}
2474
2475/// \brief Given an ISD::SDIV node expressing a divide by constant,
2476/// return a DAG expression to select that will generate the same value by
2477/// multiplying by a magic number.  See:
2478/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2479SDValue TargetLowering::
2480BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2481          std::vector<SDNode*> *Created) const {
2482  EVT VT = N->getValueType(0);
2483  SDLoc dl(N);
2484
2485  // Check to see if we can do this.
2486  // FIXME: We should be more aggressive here.
2487  if (!isTypeLegal(VT))
2488    return SDValue();
2489
2490  APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
2491  APInt::ms magics = d.magic();
2492
2493  // Multiply the numerator (operand 0) by the magic value
2494  // FIXME: We should support doing a MUL in a wider type
2495  SDValue Q;
2496  if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2497                            isOperationLegalOrCustom(ISD::MULHS, VT))
2498    Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2499                    DAG.getConstant(magics.m, VT));
2500  else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2501                                 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2502    Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2503                              N->getOperand(0),
2504                              DAG.getConstant(magics.m, VT)).getNode(), 1);
2505  else
2506    return SDValue();       // No mulhs or equvialent
2507  // If d > 0 and m < 0, add the numerator
2508  if (d.isStrictlyPositive() && magics.m.isNegative()) {
2509    Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2510    if (Created)
2511      Created->push_back(Q.getNode());
2512  }
2513  // If d < 0 and m > 0, subtract the numerator.
2514  if (d.isNegative() && magics.m.isStrictlyPositive()) {
2515    Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2516    if (Created)
2517      Created->push_back(Q.getNode());
2518  }
2519  // Shift right algebraic if shift value is nonzero
2520  if (magics.s > 0) {
2521    Q = DAG.getNode(ISD::SRA, dl, VT, Q,
2522                 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
2523    if (Created)
2524      Created->push_back(Q.getNode());
2525  }
2526  // Extract the sign bit and add it to the quotient
2527  SDValue T =
2528    DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
2529                                           getShiftAmountTy(Q.getValueType())));
2530  if (Created)
2531    Created->push_back(T.getNode());
2532  return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2533}
2534
2535/// \brief Given an ISD::UDIV node expressing a divide by constant,
2536/// return a DAG expression to select that will generate the same value by
2537/// multiplying by a magic number.  See:
2538/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2539SDValue TargetLowering::
2540BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2541          std::vector<SDNode*> *Created) const {
2542  EVT VT = N->getValueType(0);
2543  SDLoc dl(N);
2544
2545  // Check to see if we can do this.
2546  // FIXME: We should be more aggressive here.
2547  if (!isTypeLegal(VT))
2548    return SDValue();
2549
2550  // FIXME: We should use a narrower constant when the upper
2551  // bits are known to be zero.
2552  const APInt &N1C = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
2553  APInt::mu magics = N1C.magicu();
2554
2555  SDValue Q = N->getOperand(0);
2556
2557  // If the divisor is even, we can avoid using the expensive fixup by shifting
2558  // the divided value upfront.
2559  if (magics.a != 0 && !N1C[0]) {
2560    unsigned Shift = N1C.countTrailingZeros();
2561    Q = DAG.getNode(ISD::SRL, dl, VT, Q,
2562                    DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
2563    if (Created)
2564      Created->push_back(Q.getNode());
2565
2566    // Get magic number for the shifted divisor.
2567    magics = N1C.lshr(Shift).magicu(Shift);
2568    assert(magics.a == 0 && "Should use cheap fixup now");
2569  }
2570
2571  // Multiply the numerator (operand 0) by the magic value
2572  // FIXME: We should support doing a MUL in a wider type
2573  if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2574                            isOperationLegalOrCustom(ISD::MULHU, VT))
2575    Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
2576  else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2577                                 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2578    Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
2579                            DAG.getConstant(magics.m, VT)).getNode(), 1);
2580  else
2581    return SDValue();       // No mulhu or equvialent
2582  if (Created)
2583    Created->push_back(Q.getNode());
2584
2585  if (magics.a == 0) {
2586    assert(magics.s < N1C.getBitWidth() &&
2587           "We shouldn't generate an undefined shift!");
2588    return DAG.getNode(ISD::SRL, dl, VT, Q,
2589                 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
2590  } else {
2591    SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2592    if (Created)
2593      Created->push_back(NPQ.getNode());
2594    NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
2595                      DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
2596    if (Created)
2597      Created->push_back(NPQ.getNode());
2598    NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2599    if (Created)
2600      Created->push_back(NPQ.getNode());
2601    return DAG.getNode(ISD::SRL, dl, VT, NPQ,
2602             DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));
2603  }
2604}
2605