LLVM API Documentation

TargetLowering.cpp
Go to the documentation of this file.
00001 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the TargetLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Target/TargetLowering.h"
00015 #include "llvm/ADT/BitVector.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/CodeGen/Analysis.h"
00018 #include "llvm/CodeGen/MachineFrameInfo.h"
00019 #include "llvm/CodeGen/MachineFunction.h"
00020 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00021 #include "llvm/CodeGen/SelectionDAG.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/GlobalVariable.h"
00025 #include "llvm/IR/LLVMContext.h"
00026 #include "llvm/MC/MCAsmInfo.h"
00027 #include "llvm/MC/MCExpr.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include "llvm/Support/MathExtras.h"
00031 #include "llvm/Target/TargetLoweringObjectFile.h"
00032 #include "llvm/Target/TargetMachine.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include <cctype>
00035 using namespace llvm;
00036 
00037 /// NOTE: The constructor takes ownership of TLOF.
00038 TargetLowering::TargetLowering(const TargetMachine &tm,
00039                                const TargetLoweringObjectFile *tlof)
00040   : TargetLoweringBase(tm, tlof) {}
00041 
00042 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
00043   return nullptr;
00044 }
00045 
00046 /// Check whether a given call node is in tail position within its function. If
00047 /// so, it sets Chain to the input chain of the tail call.
00048 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
00049                                           SDValue &Chain) const {
00050   const Function *F = DAG.getMachineFunction().getFunction();
00051 
00052   // Conservatively require the attributes of the call to match those of
00053   // the return. Ignore noalias because it doesn't affect the call sequence.
00054   AttributeSet CallerAttrs = F->getAttributes();
00055   if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
00056       .removeAttribute(Attribute::NoAlias).hasAttributes())
00057     return false;
00058 
00059   // It's not safe to eliminate the sign / zero extension of the return value.
00060   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
00061       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
00062     return false;
00063 
00064   // Check if the only use is a function return node.
00065   return isUsedByReturnOnly(Node, Chain);
00066 }
00067 
00068 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
00069 /// and called function attributes.
00070 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
00071                                                  unsigned AttrIdx) {
00072   isSExt     = CS->paramHasAttr(AttrIdx, Attribute::SExt);
00073   isZExt     = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
00074   isInReg    = CS->paramHasAttr(AttrIdx, Attribute::InReg);
00075   isSRet     = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
00076   isNest     = CS->paramHasAttr(AttrIdx, Attribute::Nest);
00077   isByVal    = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
00078   isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
00079   isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
00080   Alignment  = CS->getParamAlignment(AttrIdx);
00081 }
00082 
00083 /// Generate a libcall taking the given operands as arguments and returning a
00084 /// result of type RetVT.
00085 std::pair<SDValue, SDValue>
00086 TargetLowering::makeLibCall(SelectionDAG &DAG,
00087                             RTLIB::Libcall LC, EVT RetVT,
00088                             const SDValue *Ops, unsigned NumOps,
00089                             bool isSigned, SDLoc dl,
00090                             bool doesNotReturn,
00091                             bool isReturnValueUsed) const {
00092   TargetLowering::ArgListTy Args;
00093   Args.reserve(NumOps);
00094 
00095   TargetLowering::ArgListEntry Entry;
00096   for (unsigned i = 0; i != NumOps; ++i) {
00097     Entry.Node = Ops[i];
00098     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
00099     Entry.isSExt = isSigned;
00100     Entry.isZExt = !isSigned;
00101     Args.push_back(Entry);
00102   }
00103   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy());
00104 
00105   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
00106   TargetLowering::
00107   CallLoweringInfo CLI(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
00108                     false, 0, getLibcallCallingConv(LC),
00109                     /*isTailCall=*/false,
00110                     doesNotReturn, isReturnValueUsed, Callee, Args,
00111                     DAG, dl);
00112   return LowerCallTo(CLI);
00113 }
00114 
00115 
00116 /// SoftenSetCCOperands - Soften the operands of a comparison.  This code is
00117 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
00118 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
00119                                          SDValue &NewLHS, SDValue &NewRHS,
00120                                          ISD::CondCode &CCCode,
00121                                          SDLoc dl) const {
00122   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
00123          && "Unsupported setcc type!");
00124 
00125   // Expand into one or more soft-fp libcall(s).
00126   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
00127   switch (CCCode) {
00128   case ISD::SETEQ:
00129   case ISD::SETOEQ:
00130     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
00131           (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
00132     break;
00133   case ISD::SETNE:
00134   case ISD::SETUNE:
00135     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
00136           (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
00137     break;
00138   case ISD::SETGE:
00139   case ISD::SETOGE:
00140     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
00141           (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
00142     break;
00143   case ISD::SETLT:
00144   case ISD::SETOLT:
00145     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
00146           (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
00147     break;
00148   case ISD::SETLE:
00149   case ISD::SETOLE:
00150     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
00151           (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
00152     break;
00153   case ISD::SETGT:
00154   case ISD::SETOGT:
00155     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
00156           (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
00157     break;
00158   case ISD::SETUO:
00159     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
00160           (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
00161     break;
00162   case ISD::SETO:
00163     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
00164           (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
00165     break;
00166   default:
00167     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
00168           (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
00169     switch (CCCode) {
00170     case ISD::SETONE:
00171       // SETONE = SETOLT | SETOGT
00172       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
00173             (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
00174       // Fallthrough
00175     case ISD::SETUGT:
00176       LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
00177             (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
00178       break;
00179     case ISD::SETUGE:
00180       LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
00181             (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
00182       break;
00183     case ISD::SETULT:
00184       LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
00185             (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
00186       break;
00187     case ISD::SETULE:
00188       LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
00189             (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
00190       break;
00191     case ISD::SETUEQ:
00192       LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
00193             (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
00194       break;
00195     default: llvm_unreachable("Do not know how to soften this setcc!");
00196     }
00197   }
00198 
00199   // Use the target specific return value for comparions lib calls.
00200   EVT RetVT = getCmpLibcallReturnType();
00201   SDValue Ops[2] = { NewLHS, NewRHS };
00202   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/,
00203                        dl).first;
00204   NewRHS = DAG.getConstant(0, RetVT);
00205   CCCode = getCmpLibcallCC(LC1);
00206   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
00207     SDValue Tmp = DAG.getNode(ISD::SETCC, dl,
00208                               getSetCCResultType(*DAG.getContext(), RetVT),
00209                               NewLHS, NewRHS, DAG.getCondCode(CCCode));
00210     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/,
00211                          dl).first;
00212     NewLHS = DAG.getNode(ISD::SETCC, dl,
00213                          getSetCCResultType(*DAG.getContext(), RetVT), NewLHS,
00214                          NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
00215     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
00216     NewRHS = SDValue();
00217   }
00218 }
00219 
00220 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
00221 /// current function.  The returned value is a member of the
00222 /// MachineJumpTableInfo::JTEntryKind enum.
00223 unsigned TargetLowering::getJumpTableEncoding() const {
00224   // In non-pic modes, just use the address of a block.
00225   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
00226     return MachineJumpTableInfo::EK_BlockAddress;
00227 
00228   // In PIC mode, if the target supports a GPRel32 directive, use it.
00229   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
00230     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
00231 
00232   // Otherwise, use a label difference.
00233   return MachineJumpTableInfo::EK_LabelDifference32;
00234 }
00235 
00236 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
00237                                                  SelectionDAG &DAG) const {
00238   // If our PIC model is GP relative, use the global offset table as the base.
00239   unsigned JTEncoding = getJumpTableEncoding();
00240 
00241   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
00242       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
00243     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0));
00244 
00245   return Table;
00246 }
00247 
00248 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
00249 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
00250 /// MCExpr.
00251 const MCExpr *
00252 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
00253                                              unsigned JTI,MCContext &Ctx) const{
00254   // The normal PIC reloc base is the label at the start of the jump table.
00255   return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
00256 }
00257 
00258 bool
00259 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
00260   // Assume that everything is safe in static mode.
00261   if (getTargetMachine().getRelocationModel() == Reloc::Static)
00262     return true;
00263 
00264   // In dynamic-no-pic mode, assume that known defined values are safe.
00265   if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
00266       GA &&
00267       !GA->getGlobal()->isDeclaration() &&
00268       !GA->getGlobal()->isWeakForLinker())
00269     return true;
00270 
00271   // Otherwise assume nothing is safe.
00272   return false;
00273 }
00274 
00275 //===----------------------------------------------------------------------===//
00276 //  Optimization Methods
00277 //===----------------------------------------------------------------------===//
00278 
00279 /// ShrinkDemandedConstant - Check to see if the specified operand of the
00280 /// specified instruction is a constant integer.  If so, check to see if there
00281 /// are any bits set in the constant that are not demanded.  If so, shrink the
00282 /// constant and return true.
00283 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
00284                                                         const APInt &Demanded) {
00285   SDLoc dl(Op);
00286 
00287   // FIXME: ISD::SELECT, ISD::SELECT_CC
00288   switch (Op.getOpcode()) {
00289   default: break;
00290   case ISD::XOR:
00291   case ISD::AND:
00292   case ISD::OR: {
00293     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
00294     if (!C) return false;
00295 
00296     if (Op.getOpcode() == ISD::XOR &&
00297         (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
00298       return false;
00299 
00300     // if we can expand it to have all bits set, do it
00301     if (C->getAPIntValue().intersects(~Demanded)) {
00302       EVT VT = Op.getValueType();
00303       SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
00304                                 DAG.getConstant(Demanded &
00305                                                 C->getAPIntValue(),
00306                                                 VT));
00307       return CombineTo(Op, New);
00308     }
00309 
00310     break;
00311   }
00312   }
00313 
00314   return false;
00315 }
00316 
00317 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
00318 /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
00319 /// cast, but it could be generalized for targets with other types of
00320 /// implicit widening casts.
00321 bool
00322 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
00323                                                     unsigned BitWidth,
00324                                                     const APInt &Demanded,
00325                                                     SDLoc dl) {
00326   assert(Op.getNumOperands() == 2 &&
00327          "ShrinkDemandedOp only supports binary operators!");
00328   assert(Op.getNode()->getNumValues() == 1 &&
00329          "ShrinkDemandedOp only supports nodes with one result!");
00330 
00331   // Don't do this if the node has another user, which may require the
00332   // full value.
00333   if (!Op.getNode()->hasOneUse())
00334     return false;
00335 
00336   // Search for the smallest integer type with free casts to and from
00337   // Op's type. For expedience, just check power-of-2 integer types.
00338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00339   unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
00340   unsigned SmallVTBits = DemandedSize;
00341   if (!isPowerOf2_32(SmallVTBits))
00342     SmallVTBits = NextPowerOf2(SmallVTBits);
00343   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
00344     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
00345     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
00346         TLI.isZExtFree(SmallVT, Op.getValueType())) {
00347       // We found a type with free casts.
00348       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
00349                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
00350                                           Op.getNode()->getOperand(0)),
00351                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
00352                                           Op.getNode()->getOperand(1)));
00353       bool NeedZext = DemandedSize > SmallVTBits;
00354       SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
00355                               dl, Op.getValueType(), X);
00356       return CombineTo(Op, Z);
00357     }
00358   }
00359   return false;
00360 }
00361 
00362 /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
00363 /// DemandedMask bits of the result of Op are ever used downstream.  If we can
00364 /// use this information to simplify Op, create a new simplified DAG node and
00365 /// return true, returning the original and new nodes in Old and New. Otherwise,
00366 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
00367 /// the expression (used to simplify the caller).  The KnownZero/One bits may
00368 /// only be accurate for those bits in the DemandedMask.
00369 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
00370                                           const APInt &DemandedMask,
00371                                           APInt &KnownZero,
00372                                           APInt &KnownOne,
00373                                           TargetLoweringOpt &TLO,
00374                                           unsigned Depth) const {
00375   unsigned BitWidth = DemandedMask.getBitWidth();
00376   assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
00377          "Mask size mismatches value type size!");
00378   APInt NewMask = DemandedMask;
00379   SDLoc dl(Op);
00380 
00381   // Don't know anything.
00382   KnownZero = KnownOne = APInt(BitWidth, 0);
00383 
00384   // Other users may use these bits.
00385   if (!Op.getNode()->hasOneUse()) {
00386     if (Depth != 0) {
00387       // If not at the root, Just compute the KnownZero/KnownOne bits to
00388       // simplify things downstream.
00389       TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
00390       return false;
00391     }
00392     // If this is the root being simplified, allow it to have multiple uses,
00393     // just set the NewMask to all bits.
00394     NewMask = APInt::getAllOnesValue(BitWidth);
00395   } else if (DemandedMask == 0) {
00396     // Not demanding any bits from Op.
00397     if (Op.getOpcode() != ISD::UNDEF)
00398       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
00399     return false;
00400   } else if (Depth == 6) {        // Limit search depth.
00401     return false;
00402   }
00403 
00404   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
00405   switch (Op.getOpcode()) {
00406   case ISD::Constant:
00407     // We know all of the bits for a constant!
00408     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
00409     KnownZero = ~KnownOne;
00410     return false;   // Don't fall through, will infinitely loop.
00411   case ISD::AND:
00412     // If the RHS is a constant, check to see if the LHS would be zero without
00413     // using the bits from the RHS.  Below, we use knowledge about the RHS to
00414     // simplify the LHS, here we're using information from the LHS to simplify
00415     // the RHS.
00416     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00417       APInt LHSZero, LHSOne;
00418       // Do not increment Depth here; that can cause an infinite loop.
00419       TLO.DAG.ComputeMaskedBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
00420       // If the LHS already has zeros where RHSC does, this and is dead.
00421       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
00422         return TLO.CombineTo(Op, Op.getOperand(0));
00423       // If any of the set bits in the RHS are known zero on the LHS, shrink
00424       // the constant.
00425       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
00426         return true;
00427     }
00428 
00429     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
00430                              KnownOne, TLO, Depth+1))
00431       return true;
00432     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00433     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
00434                              KnownZero2, KnownOne2, TLO, Depth+1))
00435       return true;
00436     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00437 
00438     // If all of the demanded bits are known one on one side, return the other.
00439     // These bits cannot contribute to the result of the 'and'.
00440     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
00441       return TLO.CombineTo(Op, Op.getOperand(0));
00442     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
00443       return TLO.CombineTo(Op, Op.getOperand(1));
00444     // If all of the demanded bits in the inputs are known zeros, return zero.
00445     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
00446       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
00447     // If the RHS is a constant, see if we can simplify it.
00448     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
00449       return true;
00450     // If the operation can be done in a smaller type, do so.
00451     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
00452       return true;
00453 
00454     // Output known-1 bits are only known if set in both the LHS & RHS.
00455     KnownOne &= KnownOne2;
00456     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00457     KnownZero |= KnownZero2;
00458     break;
00459   case ISD::OR:
00460     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
00461                              KnownOne, TLO, Depth+1))
00462       return true;
00463     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00464     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
00465                              KnownZero2, KnownOne2, TLO, Depth+1))
00466       return true;
00467     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00468 
00469     // If all of the demanded bits are known zero on one side, return the other.
00470     // These bits cannot contribute to the result of the 'or'.
00471     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
00472       return TLO.CombineTo(Op, Op.getOperand(0));
00473     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
00474       return TLO.CombineTo(Op, Op.getOperand(1));
00475     // If all of the potentially set bits on one side are known to be set on
00476     // the other side, just use the 'other' side.
00477     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
00478       return TLO.CombineTo(Op, Op.getOperand(0));
00479     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
00480       return TLO.CombineTo(Op, Op.getOperand(1));
00481     // If the RHS is a constant, see if we can simplify it.
00482     if (TLO.ShrinkDemandedConstant(Op, NewMask))
00483       return true;
00484     // If the operation can be done in a smaller type, do so.
00485     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
00486       return true;
00487 
00488     // Output known-0 bits are only known if clear in both the LHS & RHS.
00489     KnownZero &= KnownZero2;
00490     // Output known-1 are known to be set if set in either the LHS | RHS.
00491     KnownOne |= KnownOne2;
00492     break;
00493   case ISD::XOR:
00494     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
00495                              KnownOne, TLO, Depth+1))
00496       return true;
00497     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00498     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
00499                              KnownOne2, TLO, Depth+1))
00500       return true;
00501     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00502 
00503     // If all of the demanded bits are known zero on one side, return the other.
00504     // These bits cannot contribute to the result of the 'xor'.
00505     if ((KnownZero & NewMask) == NewMask)
00506       return TLO.CombineTo(Op, Op.getOperand(0));
00507     if ((KnownZero2 & NewMask) == NewMask)
00508       return TLO.CombineTo(Op, Op.getOperand(1));
00509     // If the operation can be done in a smaller type, do so.
00510     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
00511       return true;
00512 
00513     // If all of the unknown bits are known to be zero on one side or the other
00514     // (but not both) turn this into an *inclusive* or.
00515     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
00516     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
00517       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
00518                                                Op.getOperand(0),
00519                                                Op.getOperand(1)));
00520 
00521     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00522     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
00523     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00524     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
00525 
00526     // If all of the demanded bits on one side are known, and all of the set
00527     // bits on that side are also known to be set on the other side, turn this
00528     // into an AND, as we know the bits will be cleared.
00529     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
00530     // NB: it is okay if more bits are known than are requested
00531     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
00532       if (KnownOne == KnownOne2) { // set bits are the same on both sides
00533         EVT VT = Op.getValueType();
00534         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
00535         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
00536                                                  Op.getOperand(0), ANDC));
00537       }
00538     }
00539 
00540     // If the RHS is a constant, see if we can simplify it.
00541     // for XOR, we prefer to force bits to 1 if they will make a -1.
00542     // if we can't force bits, try to shrink constant
00543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00544       APInt Expanded = C->getAPIntValue() | (~NewMask);
00545       // if we can expand it to have all bits set, do it
00546       if (Expanded.isAllOnesValue()) {
00547         if (Expanded != C->getAPIntValue()) {
00548           EVT VT = Op.getValueType();
00549           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
00550                                           TLO.DAG.getConstant(Expanded, VT));
00551           return TLO.CombineTo(Op, New);
00552         }
00553         // if it already has all the bits set, nothing to change
00554         // but don't shrink either!
00555       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
00556         return true;
00557       }
00558     }
00559 
00560     KnownZero = KnownZeroOut;
00561     KnownOne  = KnownOneOut;
00562     break;
00563   case ISD::SELECT:
00564     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
00565                              KnownOne, TLO, Depth+1))
00566       return true;
00567     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
00568                              KnownOne2, TLO, Depth+1))
00569       return true;
00570     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00571     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00572 
00573     // If the operands are constants, see if we can simplify them.
00574     if (TLO.ShrinkDemandedConstant(Op, NewMask))
00575       return true;
00576 
00577     // Only known if known in both the LHS and RHS.
00578     KnownOne &= KnownOne2;
00579     KnownZero &= KnownZero2;
00580     break;
00581   case ISD::SELECT_CC:
00582     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
00583                              KnownOne, TLO, Depth+1))
00584       return true;
00585     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
00586                              KnownOne2, TLO, Depth+1))
00587       return true;
00588     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00589     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00590 
00591     // If the operands are constants, see if we can simplify them.
00592     if (TLO.ShrinkDemandedConstant(Op, NewMask))
00593       return true;
00594 
00595     // Only known if known in both the LHS and RHS.
00596     KnownOne &= KnownOne2;
00597     KnownZero &= KnownZero2;
00598     break;
00599   case ISD::SHL:
00600     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00601       unsigned ShAmt = SA->getZExtValue();
00602       SDValue InOp = Op.getOperand(0);
00603 
00604       // If the shift count is an invalid immediate, don't do anything.
00605       if (ShAmt >= BitWidth)
00606         break;
00607 
00608       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
00609       // single shift.  We can do this if the bottom bits (which are shifted
00610       // out) are never demanded.
00611       if (InOp.getOpcode() == ISD::SRL &&
00612           isa<ConstantSDNode>(InOp.getOperand(1))) {
00613         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
00614           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
00615           unsigned Opc = ISD::SHL;
00616           int Diff = ShAmt-C1;
00617           if (Diff < 0) {
00618             Diff = -Diff;
00619             Opc = ISD::SRL;
00620           }
00621 
00622           SDValue NewSA =
00623             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
00624           EVT VT = Op.getValueType();
00625           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
00626                                                    InOp.getOperand(0), NewSA));
00627         }
00628       }
00629 
00630       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
00631                                KnownZero, KnownOne, TLO, Depth+1))
00632         return true;
00633 
00634       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
00635       // are not demanded. This will likely allow the anyext to be folded away.
00636       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
00637         SDValue InnerOp = InOp.getNode()->getOperand(0);
00638         EVT InnerVT = InnerOp.getValueType();
00639         unsigned InnerBits = InnerVT.getSizeInBits();
00640         if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
00641             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
00642           EVT ShTy = getShiftAmountTy(InnerVT);
00643           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
00644             ShTy = InnerVT;
00645           SDValue NarrowShl =
00646             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
00647                             TLO.DAG.getConstant(ShAmt, ShTy));
00648           return
00649             TLO.CombineTo(Op,
00650                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
00651                                           NarrowShl));
00652         }
00653         // Repeat the SHL optimization above in cases where an extension
00654         // intervenes: (shl (anyext (shr x, c1)), c2) to
00655         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
00656         // aren't demanded (as above) and that the shifted upper c1 bits of
00657         // x aren't demanded.
00658         if (InOp.hasOneUse() &&
00659             InnerOp.getOpcode() == ISD::SRL &&
00660             InnerOp.hasOneUse() &&
00661             isa<ConstantSDNode>(InnerOp.getOperand(1))) {
00662           uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
00663             ->getZExtValue();
00664           if (InnerShAmt < ShAmt &&
00665               InnerShAmt < InnerBits &&
00666               NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
00667               NewMask.trunc(ShAmt) == 0) {
00668             SDValue NewSA =
00669               TLO.DAG.getConstant(ShAmt - InnerShAmt,
00670                                   Op.getOperand(1).getValueType());
00671             EVT VT = Op.getValueType();
00672             SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
00673                                              InnerOp.getOperand(0));
00674             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
00675                                                      NewExt, NewSA));
00676           }
00677         }
00678       }
00679 
00680       KnownZero <<= SA->getZExtValue();
00681       KnownOne  <<= SA->getZExtValue();
00682       // low bits known zero.
00683       KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
00684     }
00685     break;
00686   case ISD::SRL:
00687     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00688       EVT VT = Op.getValueType();
00689       unsigned ShAmt = SA->getZExtValue();
00690       unsigned VTSize = VT.getSizeInBits();
00691       SDValue InOp = Op.getOperand(0);
00692 
00693       // If the shift count is an invalid immediate, don't do anything.
00694       if (ShAmt >= BitWidth)
00695         break;
00696 
00697       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
00698       // single shift.  We can do this if the top bits (which are shifted out)
00699       // are never demanded.
00700       if (InOp.getOpcode() == ISD::SHL &&
00701           isa<ConstantSDNode>(InOp.getOperand(1))) {
00702         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
00703           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
00704           unsigned Opc = ISD::SRL;
00705           int Diff = ShAmt-C1;
00706           if (Diff < 0) {
00707             Diff = -Diff;
00708             Opc = ISD::SHL;
00709           }
00710 
00711           SDValue NewSA =
00712             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
00713           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
00714                                                    InOp.getOperand(0), NewSA));
00715         }
00716       }
00717 
00718       // Compute the new bits that are at the top now.
00719       if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
00720                                KnownZero, KnownOne, TLO, Depth+1))
00721         return true;
00722       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00723       KnownZero = KnownZero.lshr(ShAmt);
00724       KnownOne  = KnownOne.lshr(ShAmt);
00725 
00726       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
00727       KnownZero |= HighBits;  // High bits known zero.
00728     }
00729     break;
00730   case ISD::SRA:
00731     // If this is an arithmetic shift right and only the low-bit is set, we can
00732     // always convert this into a logical shr, even if the shift amount is
00733     // variable.  The low bit of the shift cannot be an input sign bit unless
00734     // the shift amount is >= the size of the datatype, which is undefined.
00735     if (NewMask == 1)
00736       return TLO.CombineTo(Op,
00737                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
00738                                            Op.getOperand(0), Op.getOperand(1)));
00739 
00740     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
00741       EVT VT = Op.getValueType();
00742       unsigned ShAmt = SA->getZExtValue();
00743 
00744       // If the shift count is an invalid immediate, don't do anything.
00745       if (ShAmt >= BitWidth)
00746         break;
00747 
00748       APInt InDemandedMask = (NewMask << ShAmt);
00749 
00750       // If any of the demanded bits are produced by the sign extension, we also
00751       // demand the input sign bit.
00752       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
00753       if (HighBits.intersects(NewMask))
00754         InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
00755 
00756       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
00757                                KnownZero, KnownOne, TLO, Depth+1))
00758         return true;
00759       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00760       KnownZero = KnownZero.lshr(ShAmt);
00761       KnownOne  = KnownOne.lshr(ShAmt);
00762 
00763       // Handle the sign bit, adjusted to where it is now in the mask.
00764       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
00765 
00766       // If the input sign bit is known to be zero, or if none of the top bits
00767       // are demanded, turn this into an unsigned shift right.
00768       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits)
00769         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
00770                                                  Op.getOperand(0),
00771                                                  Op.getOperand(1)));
00772 
00773       int Log2 = NewMask.exactLogBase2();
00774       if (Log2 >= 0) {
00775         // The bit must come from the sign.
00776         SDValue NewSA =
00777           TLO.DAG.getConstant(BitWidth - 1 - Log2,
00778                               Op.getOperand(1).getValueType());
00779         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
00780                                                  Op.getOperand(0), NewSA));
00781       }
00782 
00783       if (KnownOne.intersects(SignBit))
00784         // New bits are known one.
00785         KnownOne |= HighBits;
00786     }
00787     break;
00788   case ISD::SIGN_EXTEND_INREG: {
00789     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
00790 
00791     APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
00792     // If we only care about the highest bit, don't bother shifting right.
00793     if (MsbMask == DemandedMask) {
00794       unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
00795       SDValue InOp = Op.getOperand(0);
00796 
00797       // Compute the correct shift amount type, which must be getShiftAmountTy
00798       // for scalar types after legalization.
00799       EVT ShiftAmtTy = Op.getValueType();
00800       if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
00801         ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
00802 
00803       SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
00804       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
00805                                             Op.getValueType(), InOp, ShiftAmt));
00806     }
00807 
00808     // Sign extension.  Compute the demanded bits in the result that are not
00809     // present in the input.
00810     APInt NewBits =
00811       APInt::getHighBitsSet(BitWidth,
00812                             BitWidth - ExVT.getScalarType().getSizeInBits());
00813 
00814     // If none of the extended bits are demanded, eliminate the sextinreg.
00815     if ((NewBits & NewMask) == 0)
00816       return TLO.CombineTo(Op, Op.getOperand(0));
00817 
00818     APInt InSignBit =
00819       APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
00820     APInt InputDemandedBits =
00821       APInt::getLowBitsSet(BitWidth,
00822                            ExVT.getScalarType().getSizeInBits()) &
00823       NewMask;
00824 
00825     // Since the sign extended bits are demanded, we know that the sign
00826     // bit is demanded.
00827     InputDemandedBits |= InSignBit;
00828 
00829     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
00830                              KnownZero, KnownOne, TLO, Depth+1))
00831       return true;
00832     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00833 
00834     // If the sign bit of the input is known set or clear, then we know the
00835     // top bits of the result.
00836 
00837     // If the input sign bit is known zero, convert this into a zero extension.
00838     if (KnownZero.intersects(InSignBit))
00839       return TLO.CombineTo(Op,
00840                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
00841 
00842     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
00843       KnownOne |= NewBits;
00844       KnownZero &= ~NewBits;
00845     } else {                       // Input sign bit unknown
00846       KnownZero &= ~NewBits;
00847       KnownOne &= ~NewBits;
00848     }
00849     break;
00850   }
00851   case ISD::ZERO_EXTEND: {
00852     unsigned OperandBitWidth =
00853       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00854     APInt InMask = NewMask.trunc(OperandBitWidth);
00855 
00856     // If none of the top bits are demanded, convert this into an any_extend.
00857     APInt NewBits =
00858       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
00859     if (!NewBits.intersects(NewMask))
00860       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
00861                                                Op.getValueType(),
00862                                                Op.getOperand(0)));
00863 
00864     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
00865                              KnownZero, KnownOne, TLO, Depth+1))
00866       return true;
00867     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00868     KnownZero = KnownZero.zext(BitWidth);
00869     KnownOne = KnownOne.zext(BitWidth);
00870     KnownZero |= NewBits;
00871     break;
00872   }
00873   case ISD::SIGN_EXTEND: {
00874     EVT InVT = Op.getOperand(0).getValueType();
00875     unsigned InBits = InVT.getScalarType().getSizeInBits();
00876     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
00877     APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
00878     APInt NewBits   = ~InMask & NewMask;
00879 
00880     // If none of the top bits are demanded, convert this into an any_extend.
00881     if (NewBits == 0)
00882       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
00883                                               Op.getValueType(),
00884                                               Op.getOperand(0)));
00885 
00886     // Since some of the sign extended bits are demanded, we know that the sign
00887     // bit is demanded.
00888     APInt InDemandedBits = InMask & NewMask;
00889     InDemandedBits |= InSignBit;
00890     InDemandedBits = InDemandedBits.trunc(InBits);
00891 
00892     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
00893                              KnownOne, TLO, Depth+1))
00894       return true;
00895     KnownZero = KnownZero.zext(BitWidth);
00896     KnownOne = KnownOne.zext(BitWidth);
00897 
00898     // If the sign bit is known zero, convert this to a zero extend.
00899     if (KnownZero.intersects(InSignBit))
00900       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
00901                                                Op.getValueType(),
00902                                                Op.getOperand(0)));
00903 
00904     // If the sign bit is known one, the top bits match.
00905     if (KnownOne.intersects(InSignBit)) {
00906       KnownOne |= NewBits;
00907       assert((KnownZero & NewBits) == 0);
00908     } else {   // Otherwise, top bits aren't known.
00909       assert((KnownOne & NewBits) == 0);
00910       assert((KnownZero & NewBits) == 0);
00911     }
00912     break;
00913   }
00914   case ISD::ANY_EXTEND: {
00915     unsigned OperandBitWidth =
00916       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00917     APInt InMask = NewMask.trunc(OperandBitWidth);
00918     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
00919                              KnownZero, KnownOne, TLO, Depth+1))
00920       return true;
00921     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00922     KnownZero = KnownZero.zext(BitWidth);
00923     KnownOne = KnownOne.zext(BitWidth);
00924     break;
00925   }
00926   case ISD::TRUNCATE: {
00927     // Simplify the input, using demanded bit information, and compute the known
00928     // zero/one bits live out.
00929     unsigned OperandBitWidth =
00930       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
00931     APInt TruncMask = NewMask.zext(OperandBitWidth);
00932     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
00933                              KnownZero, KnownOne, TLO, Depth+1))
00934       return true;
00935     KnownZero = KnownZero.trunc(BitWidth);
00936     KnownOne = KnownOne.trunc(BitWidth);
00937 
00938     // If the input is only used by this truncate, see if we can shrink it based
00939     // on the known demanded bits.
00940     if (Op.getOperand(0).getNode()->hasOneUse()) {
00941       SDValue In = Op.getOperand(0);
00942       switch (In.getOpcode()) {
00943       default: break;
00944       case ISD::SRL:
00945         // Shrink SRL by a constant if none of the high bits shifted in are
00946         // demanded.
00947         if (TLO.LegalTypes() &&
00948             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
00949           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
00950           // undesirable.
00951           break;
00952         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
00953         if (!ShAmt)
00954           break;
00955         SDValue Shift = In.getOperand(1);
00956         if (TLO.LegalTypes()) {
00957           uint64_t ShVal = ShAmt->getZExtValue();
00958           Shift =
00959             TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
00960         }
00961 
00962         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
00963                                                OperandBitWidth - BitWidth);
00964         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
00965 
00966         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
00967           // None of the shifted in bits are needed.  Add a truncate of the
00968           // shift input, then shift it.
00969           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
00970                                              Op.getValueType(),
00971                                              In.getOperand(0));
00972           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
00973                                                    Op.getValueType(),
00974                                                    NewTrunc,
00975                                                    Shift));
00976         }
00977         break;
00978       }
00979     }
00980 
00981     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00982     break;
00983   }
00984   case ISD::AssertZext: {
00985     // AssertZext demands all of the high bits, plus any of the low bits
00986     // demanded by its users.
00987     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
00988     APInt InMask = APInt::getLowBitsSet(BitWidth,
00989                                         VT.getSizeInBits());
00990     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
00991                              KnownZero, KnownOne, TLO, Depth+1))
00992       return true;
00993     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00994 
00995     KnownZero |= ~InMask & NewMask;
00996     break;
00997   }
00998   case ISD::BITCAST:
00999     // If this is an FP->Int bitcast and if the sign bit is the only
01000     // thing demanded, turn this into a FGETSIGN.
01001     if (!TLO.LegalOperations() &&
01002         !Op.getValueType().isVector() &&
01003         !Op.getOperand(0).getValueType().isVector() &&
01004         NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
01005         Op.getOperand(0).getValueType().isFloatingPoint()) {
01006       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
01007       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
01008       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
01009         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
01010         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
01011         // place.  We expect the SHL to be eliminated by other optimizations.
01012         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
01013         unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
01014         if (!OpVTLegal && OpVTSizeInBits > 32)
01015           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
01016         unsigned ShVal = Op.getValueType().getSizeInBits()-1;
01017         SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
01018         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
01019                                                  Op.getValueType(),
01020                                                  Sign, ShAmt));
01021       }
01022     }
01023     break;
01024   case ISD::ADD:
01025   case ISD::MUL:
01026   case ISD::SUB: {
01027     // Add, Sub, and Mul don't demand any bits in positions beyond that
01028     // of the highest bit demanded of them.
01029     APInt LoMask = APInt::getLowBitsSet(BitWidth,
01030                                         BitWidth - NewMask.countLeadingZeros());
01031     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
01032                              KnownOne2, TLO, Depth+1))
01033       return true;
01034     if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
01035                              KnownOne2, TLO, Depth+1))
01036       return true;
01037     // See if the operation should be performed at a smaller bit width.
01038     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
01039       return true;
01040   }
01041   // FALL THROUGH
01042   default:
01043     // Just use ComputeMaskedBits to compute output bits.
01044     TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
01045     break;
01046   }
01047 
01048   // If we know the value of all of the demanded bits, return this as a
01049   // constant.
01050   if ((NewMask & (KnownZero|KnownOne)) == NewMask)
01051     return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
01052 
01053   return false;
01054 }
01055 
01056 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
01057 /// in Mask are known to be either zero or one and return them in the
01058 /// KnownZero/KnownOne bitsets.
01059 void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
01060                                                     APInt &KnownZero,
01061                                                     APInt &KnownOne,
01062                                                     const SelectionDAG &DAG,
01063                                                     unsigned Depth) const {
01064   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
01065           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
01066           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
01067           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
01068          "Should use MaskedValueIsZero if you don't know whether Op"
01069          " is a target node!");
01070   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
01071 }
01072 
01073 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
01074 /// targets that want to expose additional information about sign bits to the
01075 /// DAG Combiner.
01076 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
01077                                                          const SelectionDAG &,
01078                                                          unsigned Depth) const {
01079   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
01080           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
01081           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
01082           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
01083          "Should use ComputeNumSignBits if you don't know whether Op"
01084          " is a target node!");
01085   return 1;
01086 }
01087 
01088 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
01089 /// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
01090 /// determine which bit is set.
01091 ///
01092 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
01093   // A left-shift of a constant one will have exactly one bit set, because
01094   // shifting the bit off the end is undefined.
01095   if (Val.getOpcode() == ISD::SHL)
01096     if (ConstantSDNode *C =
01097          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
01098       if (C->getAPIntValue() == 1)
01099         return true;
01100 
01101   // Similarly, a right-shift of a constant sign-bit will have exactly
01102   // one bit set.
01103   if (Val.getOpcode() == ISD::SRL)
01104     if (ConstantSDNode *C =
01105          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
01106       if (C->getAPIntValue().isSignBit())
01107         return true;
01108 
01109   // More could be done here, though the above checks are enough
01110   // to handle some common cases.
01111 
01112   // Fall back to ComputeMaskedBits to catch other known cases.
01113   EVT OpVT = Val.getValueType();
01114   unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
01115   APInt KnownZero, KnownOne;
01116   DAG.ComputeMaskedBits(Val, KnownZero, KnownOne);
01117   return (KnownZero.countPopulation() == BitWidth - 1) &&
01118          (KnownOne.countPopulation() == 1);
01119 }
01120 
01121 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
01122   if (!N)
01123     return false;
01124 
01125   bool IsVec = false;
01126   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
01127   if (!CN) {
01128     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
01129     if (!BV)
01130       return false;
01131 
01132     IsVec = true;
01133     CN = BV->getConstantSplatValue();
01134   }
01135 
01136   switch (getBooleanContents(IsVec)) {
01137   case UndefinedBooleanContent:
01138     return CN->getAPIntValue()[0];
01139   case ZeroOrOneBooleanContent:
01140     return CN->isOne();
01141   case ZeroOrNegativeOneBooleanContent:
01142     return CN->isAllOnesValue();
01143   }
01144 
01145   llvm_unreachable("Invalid boolean contents");
01146 }
01147 
01148 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
01149   if (!N)
01150     return false;
01151 
01152   bool IsVec = false;
01153   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
01154   if (!CN) {
01155     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
01156     if (!BV)
01157       return false;
01158 
01159     IsVec = true;
01160     CN = BV->getConstantSplatValue();
01161   }
01162 
01163   if (getBooleanContents(IsVec) == UndefinedBooleanContent)
01164     return !CN->getAPIntValue()[0];
01165 
01166   return CN->isNullValue();
01167 }
01168 
01169 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
01170 /// and cc. If it is unable to simplify it, return a null SDValue.
01171 SDValue
01172 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
01173                               ISD::CondCode Cond, bool foldBooleans,
01174                               DAGCombinerInfo &DCI, SDLoc dl) const {
01175   SelectionDAG &DAG = DCI.DAG;
01176 
01177   // These setcc operations always fold.
01178   switch (Cond) {
01179   default: break;
01180   case ISD::SETFALSE:
01181   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
01182   case ISD::SETTRUE:
01183   case ISD::SETTRUE2: {
01184     TargetLowering::BooleanContent Cnt = getBooleanContents(VT.isVector());
01185     return DAG.getConstant(
01186         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
01187   }
01188   }
01189 
01190   // Ensure that the constant occurs on the RHS, and fold constant
01191   // comparisons.
01192   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
01193   if (isa<ConstantSDNode>(N0.getNode()) &&
01194       (DCI.isBeforeLegalizeOps() ||
01195        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
01196     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
01197 
01198   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
01199     const APInt &C1 = N1C->getAPIntValue();
01200 
01201     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
01202     // equality comparison, then we're just comparing whether X itself is
01203     // zero.
01204     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
01205         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
01206         N0.getOperand(1).getOpcode() == ISD::Constant) {
01207       const APInt &ShAmt
01208         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
01209       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01210           ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
01211         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
01212           // (srl (ctlz x), 5) == 0  -> X != 0
01213           // (srl (ctlz x), 5) != 1  -> X != 0
01214           Cond = ISD::SETNE;
01215         } else {
01216           // (srl (ctlz x), 5) != 0  -> X == 0
01217           // (srl (ctlz x), 5) == 1  -> X == 0
01218           Cond = ISD::SETEQ;
01219         }
01220         SDValue Zero = DAG.getConstant(0, N0.getValueType());
01221         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
01222                             Zero, Cond);
01223       }
01224     }
01225 
01226     SDValue CTPOP = N0;
01227     // Look through truncs that don't change the value of a ctpop.
01228     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
01229       CTPOP = N0.getOperand(0);
01230 
01231     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
01232         (N0 == CTPOP || N0.getValueType().getSizeInBits() >
01233                         Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
01234       EVT CTVT = CTPOP.getValueType();
01235       SDValue CTOp = CTPOP.getOperand(0);
01236 
01237       // (ctpop x) u< 2 -> (x & x-1) == 0
01238       // (ctpop x) u> 1 -> (x & x-1) != 0
01239       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
01240         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
01241                                   DAG.getConstant(1, CTVT));
01242         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
01243         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
01244         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
01245       }
01246 
01247       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
01248     }
01249 
01250     // (zext x) == C --> x == (trunc C)
01251     if (DCI.isBeforeLegalize() && N0->hasOneUse() &&
01252         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
01253       unsigned MinBits = N0.getValueSizeInBits();
01254       SDValue PreZExt;
01255       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
01256         // ZExt
01257         MinBits = N0->getOperand(0).getValueSizeInBits();
01258         PreZExt = N0->getOperand(0);
01259       } else if (N0->getOpcode() == ISD::AND) {
01260         // DAGCombine turns costly ZExts into ANDs
01261         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
01262           if ((C->getAPIntValue()+1).isPowerOf2()) {
01263             MinBits = C->getAPIntValue().countTrailingOnes();
01264             PreZExt = N0->getOperand(0);
01265           }
01266       } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
01267         // ZEXTLOAD
01268         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
01269           MinBits = LN0->getMemoryVT().getSizeInBits();
01270           PreZExt = N0;
01271         }
01272       }
01273 
01274       // Make sure we're not losing bits from the constant.
01275       if (MinBits > 0 &&
01276           MinBits < C1.getBitWidth() && MinBits >= C1.getActiveBits()) {
01277         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
01278         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
01279           // Will get folded away.
01280           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt);
01281           SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
01282           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
01283         }
01284       }
01285     }
01286 
01287     // If the LHS is '(and load, const)', the RHS is 0,
01288     // the test is for equality or unsigned, and all 1 bits of the const are
01289     // in the same partial word, see if we can shorten the load.
01290     if (DCI.isBeforeLegalize() &&
01291         !ISD::isSignedIntSetCC(Cond) &&
01292         N0.getOpcode() == ISD::AND && C1 == 0 &&
01293         N0.getNode()->hasOneUse() &&
01294         isa<LoadSDNode>(N0.getOperand(0)) &&
01295         N0.getOperand(0).getNode()->hasOneUse() &&
01296         isa<ConstantSDNode>(N0.getOperand(1))) {
01297       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
01298       APInt bestMask;
01299       unsigned bestWidth = 0, bestOffset = 0;
01300       if (!Lod->isVolatile() && Lod->isUnindexed()) {
01301         unsigned origWidth = N0.getValueType().getSizeInBits();
01302         unsigned maskWidth = origWidth;
01303         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
01304         // 8 bits, but have to be careful...
01305         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
01306           origWidth = Lod->getMemoryVT().getSizeInBits();
01307         const APInt &Mask =
01308           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
01309         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
01310           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
01311           for (unsigned offset=0; offset<origWidth/width; offset++) {
01312             if ((newMask & Mask) == Mask) {
01313               if (!getDataLayout()->isLittleEndian())
01314                 bestOffset = (origWidth/width - offset - 1) * (width/8);
01315               else
01316                 bestOffset = (uint64_t)offset * (width/8);
01317               bestMask = Mask.lshr(offset * (width/8) * 8);
01318               bestWidth = width;
01319               break;
01320             }
01321             newMask = newMask << width;
01322           }
01323         }
01324       }
01325       if (bestWidth) {
01326         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
01327         if (newVT.isRound()) {
01328           EVT PtrType = Lod->getOperand(1).getValueType();
01329           SDValue Ptr = Lod->getBasePtr();
01330           if (bestOffset != 0)
01331             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
01332                               DAG.getConstant(bestOffset, PtrType));
01333           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
01334           SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
01335                                 Lod->getPointerInfo().getWithOffset(bestOffset),
01336                                         false, false, false, NewAlign);
01337           return DAG.getSetCC(dl, VT,
01338                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
01339                                       DAG.getConstant(bestMask.trunc(bestWidth),
01340                                                       newVT)),
01341                               DAG.getConstant(0LL, newVT), Cond);
01342         }
01343       }
01344     }
01345 
01346     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
01347     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
01348       unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
01349 
01350       // If the comparison constant has bits in the upper part, the
01351       // zero-extended value could never match.
01352       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
01353                                               C1.getBitWidth() - InSize))) {
01354         switch (Cond) {
01355         case ISD::SETUGT:
01356         case ISD::SETUGE:
01357         case ISD::SETEQ: return DAG.getConstant(0, VT);
01358         case ISD::SETULT:
01359         case ISD::SETULE:
01360         case ISD::SETNE: return DAG.getConstant(1, VT);
01361         case ISD::SETGT:
01362         case ISD::SETGE:
01363           // True if the sign bit of C1 is set.
01364           return DAG.getConstant(C1.isNegative(), VT);
01365         case ISD::SETLT:
01366         case ISD::SETLE:
01367           // True if the sign bit of C1 isn't set.
01368           return DAG.getConstant(C1.isNonNegative(), VT);
01369         default:
01370           break;
01371         }
01372       }
01373 
01374       // Otherwise, we can perform the comparison with the low bits.
01375       switch (Cond) {
01376       case ISD::SETEQ:
01377       case ISD::SETNE:
01378       case ISD::SETUGT:
01379       case ISD::SETUGE:
01380       case ISD::SETULT:
01381       case ISD::SETULE: {
01382         EVT newVT = N0.getOperand(0).getValueType();
01383         if (DCI.isBeforeLegalizeOps() ||
01384             (isOperationLegal(ISD::SETCC, newVT) &&
01385              getCondCodeAction(Cond, newVT.getSimpleVT())==Legal))
01386           return DAG.getSetCC(dl, VT, N0.getOperand(0),
01387                               DAG.getConstant(C1.trunc(InSize), newVT),
01388                               Cond);
01389         break;
01390       }
01391       default:
01392         break;   // todo, be more careful with signed comparisons
01393       }
01394     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
01395                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
01396       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
01397       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
01398       EVT ExtDstTy = N0.getValueType();
01399       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
01400 
01401       // If the constant doesn't fit into the number of bits for the source of
01402       // the sign extension, it is impossible for both sides to be equal.
01403       if (C1.getMinSignedBits() > ExtSrcTyBits)
01404         return DAG.getConstant(Cond == ISD::SETNE, VT);
01405 
01406       SDValue ZextOp;
01407       EVT Op0Ty = N0.getOperand(0).getValueType();
01408       if (Op0Ty == ExtSrcTy) {
01409         ZextOp = N0.getOperand(0);
01410       } else {
01411         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
01412         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
01413                               DAG.getConstant(Imm, Op0Ty));
01414       }
01415       if (!DCI.isCalledByLegalizer())
01416         DCI.AddToWorklist(ZextOp.getNode());
01417       // Otherwise, make this a use of a zext.
01418       return DAG.getSetCC(dl, VT, ZextOp,
01419                           DAG.getConstant(C1 & APInt::getLowBitsSet(
01420                                                               ExtDstTyBits,
01421                                                               ExtSrcTyBits),
01422                                           ExtDstTy),
01423                           Cond);
01424     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
01425                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
01426       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
01427       if (N0.getOpcode() == ISD::SETCC &&
01428           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
01429         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
01430         if (TrueWhenTrue)
01431           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
01432         // Invert the condition.
01433         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
01434         CC = ISD::getSetCCInverse(CC,
01435                                   N0.getOperand(0).getValueType().isInteger());
01436         if (DCI.isBeforeLegalizeOps() ||
01437             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
01438           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
01439       }
01440 
01441       if ((N0.getOpcode() == ISD::XOR ||
01442            (N0.getOpcode() == ISD::AND &&
01443             N0.getOperand(0).getOpcode() == ISD::XOR &&
01444             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
01445           isa<ConstantSDNode>(N0.getOperand(1)) &&
01446           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
01447         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
01448         // can only do this if the top bits are known zero.
01449         unsigned BitWidth = N0.getValueSizeInBits();
01450         if (DAG.MaskedValueIsZero(N0,
01451                                   APInt::getHighBitsSet(BitWidth,
01452                                                         BitWidth-1))) {
01453           // Okay, get the un-inverted input value.
01454           SDValue Val;
01455           if (N0.getOpcode() == ISD::XOR)
01456             Val = N0.getOperand(0);
01457           else {
01458             assert(N0.getOpcode() == ISD::AND &&
01459                     N0.getOperand(0).getOpcode() == ISD::XOR);
01460             // ((X^1)&1)^1 -> X & 1
01461             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
01462                               N0.getOperand(0).getOperand(0),
01463                               N0.getOperand(1));
01464           }
01465 
01466           return DAG.getSetCC(dl, VT, Val, N1,
01467                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01468         }
01469       } else if (N1C->getAPIntValue() == 1 &&
01470                  (VT == MVT::i1 ||
01471                   getBooleanContents(false) == ZeroOrOneBooleanContent)) {
01472         SDValue Op0 = N0;
01473         if (Op0.getOpcode() == ISD::TRUNCATE)
01474           Op0 = Op0.getOperand(0);
01475 
01476         if ((Op0.getOpcode() == ISD::XOR) &&
01477             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
01478             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
01479           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
01480           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
01481           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
01482                               Cond);
01483         }
01484         if (Op0.getOpcode() == ISD::AND &&
01485             isa<ConstantSDNode>(Op0.getOperand(1)) &&
01486             cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
01487           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
01488           if (Op0.getValueType().bitsGT(VT))
01489             Op0 = DAG.getNode(ISD::AND, dl, VT,
01490                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
01491                           DAG.getConstant(1, VT));
01492           else if (Op0.getValueType().bitsLT(VT))
01493             Op0 = DAG.getNode(ISD::AND, dl, VT,
01494                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
01495                         DAG.getConstant(1, VT));
01496 
01497           return DAG.getSetCC(dl, VT, Op0,
01498                               DAG.getConstant(0, Op0.getValueType()),
01499                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01500         }
01501         if (Op0.getOpcode() == ISD::AssertZext &&
01502             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
01503           return DAG.getSetCC(dl, VT, Op0,
01504                               DAG.getConstant(0, Op0.getValueType()),
01505                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
01506       }
01507     }
01508 
01509     APInt MinVal, MaxVal;
01510     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
01511     if (ISD::isSignedIntSetCC(Cond)) {
01512       MinVal = APInt::getSignedMinValue(OperandBitSize);
01513       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
01514     } else {
01515       MinVal = APInt::getMinValue(OperandBitSize);
01516       MaxVal = APInt::getMaxValue(OperandBitSize);
01517     }
01518 
01519     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
01520     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
01521       if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
01522       // X >= C0 --> X > (C0 - 1)
01523       APInt C = C1 - 1;
01524       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
01525       if ((DCI.isBeforeLegalizeOps() ||
01526            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
01527           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
01528                                 isLegalICmpImmediate(C.getSExtValue())))) {
01529         return DAG.getSetCC(dl, VT, N0,
01530                             DAG.getConstant(C, N1.getValueType()),
01531                             NewCC);
01532       }
01533     }
01534 
01535     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
01536       if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
01537       // X <= C0 --> X < (C0 + 1)
01538       APInt C = C1 + 1;
01539       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
01540       if ((DCI.isBeforeLegalizeOps() ||
01541            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
01542           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
01543                                 isLegalICmpImmediate(C.getSExtValue())))) {
01544         return DAG.getSetCC(dl, VT, N0,
01545                             DAG.getConstant(C, N1.getValueType()),
01546                             NewCC);
01547       }
01548     }
01549 
01550     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
01551       return DAG.getConstant(0, VT);      // X < MIN --> false
01552     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
01553       return DAG.getConstant(1, VT);      // X >= MIN --> true
01554     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
01555       return DAG.getConstant(0, VT);      // X > MAX --> false
01556     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
01557       return DAG.getConstant(1, VT);      // X <= MAX --> true
01558 
01559     // Canonicalize setgt X, Min --> setne X, Min
01560     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
01561       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
01562     // Canonicalize setlt X, Max --> setne X, Max
01563     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
01564       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
01565 
01566     // If we have setult X, 1, turn it into seteq X, 0
01567     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
01568       return DAG.getSetCC(dl, VT, N0,
01569                           DAG.getConstant(MinVal, N0.getValueType()),
01570                           ISD::SETEQ);
01571     // If we have setugt X, Max-1, turn it into seteq X, Max
01572     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
01573       return DAG.getSetCC(dl, VT, N0,
01574                           DAG.getConstant(MaxVal, N0.getValueType()),
01575                           ISD::SETEQ);
01576 
01577     // If we have "setcc X, C0", check to see if we can shrink the immediate
01578     // by changing cc.
01579 
01580     // SETUGT X, SINTMAX  -> SETLT X, 0
01581     if (Cond == ISD::SETUGT &&
01582         C1 == APInt::getSignedMaxValue(OperandBitSize))
01583       return DAG.getSetCC(dl, VT, N0,
01584                           DAG.getConstant(0, N1.getValueType()),
01585                           ISD::SETLT);
01586 
01587     // SETULT X, SINTMIN  -> SETGT X, -1
01588     if (Cond == ISD::SETULT &&
01589         C1 == APInt::getSignedMinValue(OperandBitSize)) {
01590       SDValue ConstMinusOne =
01591           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
01592                           N1.getValueType());
01593       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
01594     }
01595 
01596     // Fold bit comparisons when we can.
01597     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01598         (VT == N0.getValueType() ||
01599          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
01600         N0.getOpcode() == ISD::AND)
01601       if (ConstantSDNode *AndRHS =
01602                   dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01603         EVT ShiftTy = DCI.isBeforeLegalize() ?
01604           getPointerTy() : getShiftAmountTy(N0.getValueType());
01605         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
01606           // Perform the xform if the AND RHS is a single bit.
01607           if (AndRHS->getAPIntValue().isPowerOf2()) {
01608             return DAG.getNode(ISD::TRUNCATE, dl, VT,
01609                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
01610                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
01611           }
01612         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
01613           // (X & 8) == 8  -->  (X & 8) >> 3
01614           // Perform the xform if C1 is a single bit.
01615           if (C1.isPowerOf2()) {
01616             return DAG.getNode(ISD::TRUNCATE, dl, VT,
01617                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
01618                                       DAG.getConstant(C1.logBase2(), ShiftTy)));
01619           }
01620         }
01621       }
01622 
01623     if (C1.getMinSignedBits() <= 64 &&
01624         !isLegalICmpImmediate(C1.getSExtValue())) {
01625       // (X & -256) == 256 -> (X >> 8) == 1
01626       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01627           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
01628         if (ConstantSDNode *AndRHS =
01629             dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01630           const APInt &AndRHSC = AndRHS->getAPIntValue();
01631           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
01632             unsigned ShiftBits = AndRHSC.countTrailingZeros();
01633             EVT ShiftTy = DCI.isBeforeLegalize() ?
01634               getPointerTy() : getShiftAmountTy(N0.getValueType());
01635             EVT CmpTy = N0.getValueType();
01636             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
01637                                         DAG.getConstant(ShiftBits, ShiftTy));
01638             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
01639             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
01640           }
01641         }
01642       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
01643                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
01644         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
01645         // X <  0x100000000 -> (X >> 32) <  1
01646         // X >= 0x100000000 -> (X >> 32) >= 1
01647         // X <= 0x0ffffffff -> (X >> 32) <  1
01648         // X >  0x0ffffffff -> (X >> 32) >= 1
01649         unsigned ShiftBits;
01650         APInt NewC = C1;
01651         ISD::CondCode NewCond = Cond;
01652         if (AdjOne) {
01653           ShiftBits = C1.countTrailingOnes();
01654           NewC = NewC + 1;
01655           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
01656         } else {
01657           ShiftBits = C1.countTrailingZeros();
01658         }
01659         NewC = NewC.lshr(ShiftBits);
01660         if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
01661           EVT ShiftTy = DCI.isBeforeLegalize() ?
01662             getPointerTy() : getShiftAmountTy(N0.getValueType());
01663           EVT CmpTy = N0.getValueType();
01664           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
01665                                       DAG.getConstant(ShiftBits, ShiftTy));
01666           SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
01667           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
01668         }
01669       }
01670     }
01671   }
01672 
01673   if (isa<ConstantFPSDNode>(N0.getNode())) {
01674     // Constant fold or commute setcc.
01675     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
01676     if (O.getNode()) return O;
01677   } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
01678     // If the RHS of an FP comparison is a constant, simplify it away in
01679     // some cases.
01680     if (CFP->getValueAPF().isNaN()) {
01681       // If an operand is known to be a nan, we can fold it.
01682       switch (ISD::getUnorderedFlavor(Cond)) {
01683       default: llvm_unreachable("Unknown flavor!");
01684       case 0:  // Known false.
01685         return DAG.getConstant(0, VT);
01686       case 1:  // Known true.
01687         return DAG.getConstant(1, VT);
01688       case 2:  // Undefined.
01689         return DAG.getUNDEF(VT);
01690       }
01691     }
01692 
01693     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
01694     // constant if knowing that the operand is non-nan is enough.  We prefer to
01695     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
01696     // materialize 0.0.
01697     if (Cond == ISD::SETO || Cond == ISD::SETUO)
01698       return DAG.getSetCC(dl, VT, N0, N0, Cond);
01699 
01700     // If the condition is not legal, see if we can find an equivalent one
01701     // which is legal.
01702     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
01703       // If the comparison was an awkward floating-point == or != and one of
01704       // the comparison operands is infinity or negative infinity, convert the
01705       // condition to a less-awkward <= or >=.
01706       if (CFP->getValueAPF().isInfinity()) {
01707         if (CFP->getValueAPF().isNegative()) {
01708           if (Cond == ISD::SETOEQ &&
01709               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
01710             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
01711           if (Cond == ISD::SETUEQ &&
01712               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
01713             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
01714           if (Cond == ISD::SETUNE &&
01715               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
01716             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
01717           if (Cond == ISD::SETONE &&
01718               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
01719             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
01720         } else {
01721           if (Cond == ISD::SETOEQ &&
01722               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
01723             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
01724           if (Cond == ISD::SETUEQ &&
01725               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
01726             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
01727           if (Cond == ISD::SETUNE &&
01728               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
01729             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
01730           if (Cond == ISD::SETONE &&
01731               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
01732             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
01733         }
01734       }
01735     }
01736   }
01737 
01738   if (N0 == N1) {
01739     // The sext(setcc()) => setcc() optimization relies on the appropriate
01740     // constant being emitted.
01741     uint64_t EqVal = 0;
01742     switch (getBooleanContents(N0.getValueType().isVector())) {
01743     case UndefinedBooleanContent:
01744     case ZeroOrOneBooleanContent:
01745       EqVal = ISD::isTrueWhenEqual(Cond);
01746       break;
01747     case ZeroOrNegativeOneBooleanContent:
01748       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
01749       break;
01750     }
01751 
01752     // We can always fold X == X for integer setcc's.
01753     if (N0.getValueType().isInteger()) {
01754       return DAG.getConstant(EqVal, VT);
01755     }
01756     unsigned UOF = ISD::getUnorderedFlavor(Cond);
01757     if (UOF == 2)   // FP operators that are undefined on NaNs.
01758       return DAG.getConstant(EqVal, VT);
01759     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
01760       return DAG.getConstant(EqVal, VT);
01761     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
01762     // if it is not already.
01763     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
01764     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
01765           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
01766       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
01767   }
01768 
01769   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
01770       N0.getValueType().isInteger()) {
01771     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
01772         N0.getOpcode() == ISD::XOR) {
01773       // Simplify (X+Y) == (X+Z) -->  Y == Z
01774       if (N0.getOpcode() == N1.getOpcode()) {
01775         if (N0.getOperand(0) == N1.getOperand(0))
01776           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
01777         if (N0.getOperand(1) == N1.getOperand(1))
01778           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
01779         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
01780           // If X op Y == Y op X, try other combinations.
01781           if (N0.getOperand(0) == N1.getOperand(1))
01782             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
01783                                 Cond);
01784           if (N0.getOperand(1) == N1.getOperand(0))
01785             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
01786                                 Cond);
01787         }
01788       }
01789 
01790       // If RHS is a legal immediate value for a compare instruction, we need
01791       // to be careful about increasing register pressure needlessly.
01792       bool LegalRHSImm = false;
01793 
01794       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
01795         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
01796           // Turn (X+C1) == C2 --> X == C2-C1
01797           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
01798             return DAG.getSetCC(dl, VT, N0.getOperand(0),
01799                                 DAG.getConstant(RHSC->getAPIntValue()-
01800                                                 LHSR->getAPIntValue(),
01801                                 N0.getValueType()), Cond);
01802           }
01803 
01804           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
01805           if (N0.getOpcode() == ISD::XOR)
01806             // If we know that all of the inverted bits are zero, don't bother
01807             // performing the inversion.
01808             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
01809               return
01810                 DAG.getSetCC(dl, VT, N0.getOperand(0),
01811                              DAG.getConstant(LHSR->getAPIntValue() ^
01812                                                RHSC->getAPIntValue(),
01813                                              N0.getValueType()),
01814                              Cond);
01815         }
01816 
01817         // Turn (C1-X) == C2 --> X == C1-C2
01818         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
01819           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
01820             return
01821               DAG.getSetCC(dl, VT, N0.getOperand(1),
01822                            DAG.getConstant(SUBC->getAPIntValue() -
01823                                              RHSC->getAPIntValue(),
01824                                            N0.getValueType()),
01825                            Cond);
01826           }
01827         }
01828 
01829         // Could RHSC fold directly into a compare?
01830         if (RHSC->getValueType(0).getSizeInBits() <= 64)
01831           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
01832       }
01833 
01834       // Simplify (X+Z) == X -->  Z == 0
01835       // Don't do this if X is an immediate that can fold into a cmp
01836       // instruction and X+Z has other uses. It could be an induction variable
01837       // chain, and the transform would increase register pressure.
01838       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
01839         if (N0.getOperand(0) == N1)
01840           return DAG.getSetCC(dl, VT, N0.getOperand(1),
01841                               DAG.getConstant(0, N0.getValueType()), Cond);
01842         if (N0.getOperand(1) == N1) {
01843           if (DAG.isCommutativeBinOp(N0.getOpcode()))
01844             return DAG.getSetCC(dl, VT, N0.getOperand(0),
01845                                 DAG.getConstant(0, N0.getValueType()), Cond);
01846           if (N0.getNode()->hasOneUse()) {
01847             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
01848             // (Z-X) == X  --> Z == X<<1
01849             SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
01850                        DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
01851             if (!DCI.isCalledByLegalizer())
01852               DCI.AddToWorklist(SH.getNode());
01853             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
01854           }
01855         }
01856       }
01857     }
01858 
01859     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
01860         N1.getOpcode() == ISD::XOR) {
01861       // Simplify  X == (X+Z) -->  Z == 0
01862       if (N1.getOperand(0) == N0)
01863         return DAG.getSetCC(dl, VT, N1.getOperand(1),
01864                         DAG.getConstant(0, N1.getValueType()), Cond);
01865       if (N1.getOperand(1) == N0) {
01866         if (DAG.isCommutativeBinOp(N1.getOpcode()))
01867           return DAG.getSetCC(dl, VT, N1.getOperand(0),
01868                           DAG.getConstant(0, N1.getValueType()), Cond);
01869         if (N1.getNode()->hasOneUse()) {
01870           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
01871           // X == (Z-X)  --> X<<1 == Z
01872           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
01873                        DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
01874           if (!DCI.isCalledByLegalizer())
01875             DCI.AddToWorklist(SH.getNode());
01876           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
01877         }
01878       }
01879     }
01880 
01881     // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
01882     // Note that where y is variable and is known to have at most
01883     // one bit set (for example, if it is z&1) we cannot do this;
01884     // the expressions are not equivalent when y==0.
01885     if (N0.getOpcode() == ISD::AND)
01886       if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
01887         if (ValueHasExactlyOneBitSet(N1, DAG)) {
01888           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
01889           if (DCI.isBeforeLegalizeOps() ||
01890               isCondCodeLegal(Cond, N0.getSimpleValueType())) {
01891             SDValue Zero = DAG.getConstant(0, N1.getValueType());
01892             return DAG.getSetCC(dl, VT, N0, Zero, Cond);
01893           }
01894         }
01895       }
01896     if (N1.getOpcode() == ISD::AND)
01897       if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
01898         if (ValueHasExactlyOneBitSet(N0, DAG)) {
01899           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
01900           if (DCI.isBeforeLegalizeOps() ||
01901               isCondCodeLegal(Cond, N1.getSimpleValueType())) {
01902             SDValue Zero = DAG.getConstant(0, N0.getValueType());
01903             return DAG.getSetCC(dl, VT, N1, Zero, Cond);
01904           }
01905         }
01906       }
01907   }
01908 
01909   // Fold away ALL boolean setcc's.
01910   SDValue Temp;
01911   if (N0.getValueType() == MVT::i1 && foldBooleans) {
01912     switch (Cond) {
01913     default: llvm_unreachable("Unknown integer setcc!");
01914     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
01915       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
01916       N0 = DAG.getNOT(dl, Temp, MVT::i1);
01917       if (!DCI.isCalledByLegalizer())
01918         DCI.AddToWorklist(Temp.getNode());
01919       break;
01920     case ISD::SETNE:  // X != Y   -->  (X^Y)
01921       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
01922       break;
01923     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
01924     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
01925       Temp = DAG.getNOT(dl, N0, MVT::i1);
01926       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
01927       if (!DCI.isCalledByLegalizer())
01928         DCI.AddToWorklist(Temp.getNode());
01929       break;
01930     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
01931     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
01932       Temp = DAG.getNOT(dl, N1, MVT::i1);
01933       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
01934       if (!DCI.isCalledByLegalizer())
01935         DCI.AddToWorklist(Temp.getNode());
01936       break;
01937     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
01938     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
01939       Temp = DAG.getNOT(dl, N0, MVT::i1);
01940       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
01941       if (!DCI.isCalledByLegalizer())
01942         DCI.AddToWorklist(Temp.getNode());
01943       break;
01944     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
01945     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
01946       Temp = DAG.getNOT(dl, N1, MVT::i1);
01947       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
01948       break;
01949     }
01950     if (VT != MVT::i1) {
01951       if (!DCI.isCalledByLegalizer())
01952         DCI.AddToWorklist(N0.getNode());
01953       // FIXME: If running after legalize, we probably can't do this.
01954       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
01955     }
01956     return N0;
01957   }
01958 
01959   // Could not fold it.
01960   return SDValue();
01961 }
01962 
01963 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
01964 /// node is a GlobalAddress + offset.
01965 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
01966                                     int64_t &Offset) const {
01967   if (isa<GlobalAddressSDNode>(N)) {
01968     GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
01969     GA = GASD->getGlobal();
01970     Offset += GASD->getOffset();
01971     return true;
01972   }
01973 
01974   if (N->getOpcode() == ISD::ADD) {
01975     SDValue N1 = N->getOperand(0);
01976     SDValue N2 = N->getOperand(1);
01977     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
01978       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
01979       if (V) {
01980         Offset += V->getSExtValue();
01981         return true;
01982       }
01983     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
01984       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
01985       if (V) {
01986         Offset += V->getSExtValue();
01987         return true;
01988       }
01989     }
01990   }
01991 
01992   return false;
01993 }
01994 
01995 
01996 SDValue TargetLowering::
01997 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
01998   // Default implementation: no optimization.
01999   return SDValue();
02000 }
02001 
02002 //===----------------------------------------------------------------------===//
02003 //  Inline Assembler Implementation Methods
02004 //===----------------------------------------------------------------------===//
02005 
02006 
02007 TargetLowering::ConstraintType
02008 TargetLowering::getConstraintType(const std::string &Constraint) const {
02009   unsigned S = Constraint.size();
02010 
02011   if (S == 1) {
02012     switch (Constraint[0]) {
02013     default: break;
02014     case 'r': return C_RegisterClass;
02015     case 'm':    // memory
02016     case 'o':    // offsetable
02017     case 'V':    // not offsetable
02018       return C_Memory;
02019     case 'i':    // Simple Integer or Relocatable Constant
02020     case 'n':    // Simple Integer
02021     case 'E':    // Floating Point Constant
02022     case 'F':    // Floating Point Constant
02023     case 's':    // Relocatable Constant
02024     case 'p':    // Address.
02025     case 'X':    // Allow ANY value.
02026     case 'I':    // Target registers.
02027     case 'J':
02028     case 'K':
02029     case 'L':
02030     case 'M':
02031     case 'N':
02032     case 'O':
02033     case 'P':
02034     case '<':
02035     case '>':
02036       return C_Other;
02037     }
02038   }
02039 
02040   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
02041     if (S == 8 && !Constraint.compare(1, 6, "memory", 6))  // "{memory}"
02042       return C_Memory;
02043     return C_Register;
02044   }
02045   return C_Unknown;
02046 }
02047 
02048 /// LowerXConstraint - try to replace an X constraint, which matches anything,
02049 /// with another that has more specific requirements based on the type of the
02050 /// corresponding operand.
02051 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
02052   if (ConstraintVT.isInteger())
02053     return "r";
02054   if (ConstraintVT.isFloatingPoint())
02055     return "f";      // works for many targets
02056   return nullptr;
02057 }
02058 
02059 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
02060 /// vector.  If it is invalid, don't add anything to Ops.
02061 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
02062                                                   std::string &Constraint,
02063                                                   std::vector<SDValue> &Ops,
02064                                                   SelectionDAG &DAG) const {
02065 
02066   if (Constraint.length() > 1) return;
02067 
02068   char ConstraintLetter = Constraint[0];
02069   switch (ConstraintLetter) {
02070   default: break;
02071   case 'X':     // Allows any operand; labels (basic block) use this.
02072     if (Op.getOpcode() == ISD::BasicBlock) {
02073       Ops.push_back(Op);
02074       return;
02075     }
02076     // fall through
02077   case 'i':    // Simple Integer or Relocatable Constant
02078   case 'n':    // Simple Integer
02079   case 's': {  // Relocatable Constant
02080     // These operands are interested in values of the form (GV+C), where C may
02081     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
02082     // is possible and fine if either GV or C are missing.
02083     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
02084     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
02085 
02086     // If we have "(add GV, C)", pull out GV/C
02087     if (Op.getOpcode() == ISD::ADD) {
02088       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
02089       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
02090       if (!C || !GA) {
02091         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
02092         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
02093       }
02094       if (!C || !GA)
02095         C = nullptr, GA = nullptr;
02096     }
02097 
02098     // If we find a valid operand, map to the TargetXXX version so that the
02099     // value itself doesn't get selected.
02100     if (GA) {   // Either &GV   or   &GV+C
02101       if (ConstraintLetter != 'n') {
02102         int64_t Offs = GA->getOffset();
02103         if (C) Offs += C->getZExtValue();
02104         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
02105                                                  C ? SDLoc(C) : SDLoc(),
02106                                                  Op.getValueType(), Offs));
02107         return;
02108       }
02109     }
02110     if (C) {   // just C, no GV.
02111       // Simple constants are not allowed for 's'.
02112       if (ConstraintLetter != 's') {
02113         // gcc prints these as sign extended.  Sign extend value to 64 bits
02114         // now; without this it would get ZExt'd later in
02115         // ScheduleDAGSDNodes::EmitNode, which is very generic.
02116         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
02117                                             MVT::i64));
02118         return;
02119       }
02120     }
02121     break;
02122   }
02123   }
02124 }
02125 
02126 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
02127 getRegForInlineAsmConstraint(const std::string &Constraint,
02128                              MVT VT) const {
02129   if (Constraint.empty() || Constraint[0] != '{')
02130     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
02131   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
02132 
02133   // Remove the braces from around the name.
02134   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
02135 
02136   std::pair<unsigned, const TargetRegisterClass*> R =
02137     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
02138 
02139   // Figure out which register class contains this reg.
02140   const TargetRegisterInfo *RI = getTargetMachine().getRegisterInfo();
02141   for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
02142        E = RI->regclass_end(); RCI != E; ++RCI) {
02143     const TargetRegisterClass *RC = *RCI;
02144 
02145     // If none of the value types for this register class are valid, we
02146     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
02147     if (!isLegalRC(RC))
02148       continue;
02149 
02150     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
02151          I != E; ++I) {
02152       if (RegName.equals_lower(RI->getName(*I))) {
02153         std::pair<unsigned, const TargetRegisterClass*> S =
02154           std::make_pair(*I, RC);
02155 
02156         // If this register class has the requested value type, return it,
02157         // otherwise keep searching and return the first class found
02158         // if no other is found which explicitly has the requested type.
02159         if (RC->hasType(VT))
02160           return S;
02161         else if (!R.second)
02162           R = S;
02163       }
02164     }
02165   }
02166 
02167   return R;
02168 }
02169 
02170 //===----------------------------------------------------------------------===//
02171 // Constraint Selection.
02172 
02173 /// isMatchingInputConstraint - Return true of this is an input operand that is
02174 /// a matching constraint like "4".
02175 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
02176   assert(!ConstraintCode.empty() && "No known constraint!");
02177   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
02178 }
02179 
02180 /// getMatchedOperand - If this is an input matching constraint, this method
02181 /// returns the output operand it matches.
02182 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
02183   assert(!ConstraintCode.empty() && "No known constraint!");
02184   return atoi(ConstraintCode.c_str());
02185 }
02186 
02187 
02188 /// ParseConstraints - Split up the constraint string from the inline
02189 /// assembly value into the specific constraints and their prefixes,
02190 /// and also tie in the associated operand values.
02191 /// If this returns an empty vector, and if the constraint string itself
02192 /// isn't empty, there was an error parsing.
02193 TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints(
02194     ImmutableCallSite CS) const {
02195   /// ConstraintOperands - Information about all of the constraints.
02196   AsmOperandInfoVector ConstraintOperands;
02197   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
02198   unsigned maCount = 0; // Largest number of multiple alternative constraints.
02199 
02200   // Do a prepass over the constraints, canonicalizing them, and building up the
02201   // ConstraintOperands list.
02202   InlineAsm::ConstraintInfoVector
02203     ConstraintInfos = IA->ParseConstraints();
02204 
02205   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
02206   unsigned ResNo = 0;   // ResNo - The result number of the next output.
02207 
02208   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
02209     ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
02210     AsmOperandInfo &OpInfo = ConstraintOperands.back();
02211 
02212     // Update multiple alternative constraint count.
02213     if (OpInfo.multipleAlternatives.size() > maCount)
02214       maCount = OpInfo.multipleAlternatives.size();
02215 
02216     OpInfo.ConstraintVT = MVT::Other;
02217 
02218     // Compute the value type for each operand.
02219     switch (OpInfo.Type) {
02220     case InlineAsm::isOutput:
02221       // Indirect outputs just consume an argument.
02222       if (OpInfo.isIndirect) {
02223         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
02224         break;
02225       }
02226 
02227       // The return value of the call is this value.  As such, there is no
02228       // corresponding argument.
02229       assert(!CS.getType()->isVoidTy() &&
02230              "Bad inline asm!");
02231       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
02232         OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
02233       } else {
02234         assert(ResNo == 0 && "Asm only has one result!");
02235         OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
02236       }
02237       ++ResNo;
02238       break;
02239     case InlineAsm::isInput:
02240       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
02241       break;
02242     case InlineAsm::isClobber:
02243       // Nothing to do.
02244       break;
02245     }
02246 
02247     if (OpInfo.CallOperandVal) {
02248       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
02249       if (OpInfo.isIndirect) {
02250         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
02251         if (!PtrTy)
02252           report_fatal_error("Indirect operand for inline asm not a pointer!");
02253         OpTy = PtrTy->getElementType();
02254       }
02255 
02256       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
02257       if (StructType *STy = dyn_cast<StructType>(OpTy))
02258         if (STy->getNumElements() == 1)
02259           OpTy = STy->getElementType(0);
02260 
02261       // If OpTy is not a single value, it may be a struct/union that we
02262       // can tile with integers.
02263       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
02264         unsigned BitSize = getDataLayout()->getTypeSizeInBits(OpTy);
02265         switch (BitSize) {
02266         default: break;
02267         case 1:
02268         case 8:
02269         case 16:
02270         case 32:
02271         case 64:
02272         case 128:
02273           OpInfo.ConstraintVT =
02274             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
02275           break;
02276         }
02277       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
02278         unsigned PtrSize
02279           = getDataLayout()->getPointerSizeInBits(PT->getAddressSpace());
02280         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
02281       } else {
02282         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
02283       }
02284     }
02285   }
02286 
02287   // If we have multiple alternative constraints, select the best alternative.
02288   if (ConstraintInfos.size()) {
02289     if (maCount) {
02290       unsigned bestMAIndex = 0;
02291       int bestWeight = -1;
02292       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
02293       int weight = -1;
02294       unsigned maIndex;
02295       // Compute the sums of the weights for each alternative, keeping track
02296       // of the best (highest weight) one so far.
02297       for (maIndex = 0; maIndex < maCount; ++maIndex) {
02298         int weightSum = 0;
02299         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02300             cIndex != eIndex; ++cIndex) {
02301           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
02302           if (OpInfo.Type == InlineAsm::isClobber)
02303             continue;
02304 
02305           // If this is an output operand with a matching input operand,
02306           // look up the matching input. If their types mismatch, e.g. one
02307           // is an integer, the other is floating point, or their sizes are
02308           // different, flag it as an maCantMatch.
02309           if (OpInfo.hasMatchingInput()) {
02310             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
02311             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
02312               if ((OpInfo.ConstraintVT.isInteger() !=
02313                    Input.ConstraintVT.isInteger()) ||
02314                   (OpInfo.ConstraintVT.getSizeInBits() !=
02315                    Input.ConstraintVT.getSizeInBits())) {
02316                 weightSum = -1;  // Can't match.
02317                 break;
02318               }
02319             }
02320           }
02321           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
02322           if (weight == -1) {
02323             weightSum = -1;
02324             break;
02325           }
02326           weightSum += weight;
02327         }
02328         // Update best.
02329         if (weightSum > bestWeight) {
02330           bestWeight = weightSum;
02331           bestMAIndex = maIndex;
02332         }
02333       }
02334 
02335       // Now select chosen alternative in each constraint.
02336       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02337           cIndex != eIndex; ++cIndex) {
02338         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
02339         if (cInfo.Type == InlineAsm::isClobber)
02340           continue;
02341         cInfo.selectAlternative(bestMAIndex);
02342       }
02343     }
02344   }
02345 
02346   // Check and hook up tied operands, choose constraint code to use.
02347   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
02348       cIndex != eIndex; ++cIndex) {
02349     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
02350 
02351     // If this is an output operand with a matching input operand, look up the
02352     // matching input. If their types mismatch, e.g. one is an integer, the
02353     // other is floating point, or their sizes are different, flag it as an
02354     // error.
02355     if (OpInfo.hasMatchingInput()) {
02356       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
02357 
02358       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
02359         std::pair<unsigned, const TargetRegisterClass*> MatchRC =
02360           getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
02361                                        OpInfo.ConstraintVT);
02362         std::pair<unsigned, const TargetRegisterClass*> InputRC =
02363           getRegForInlineAsmConstraint(Input.ConstraintCode,
02364                                        Input.ConstraintVT);
02365         if ((OpInfo.ConstraintVT.isInteger() !=
02366              Input.ConstraintVT.isInteger()) ||
02367             (MatchRC.second != InputRC.second)) {
02368           report_fatal_error("Unsupported asm: input constraint"
02369                              " with a matching output constraint of"
02370                              " incompatible type!");
02371         }
02372       }
02373 
02374     }
02375   }
02376 
02377   return ConstraintOperands;
02378 }
02379 
02380 
02381 /// getConstraintGenerality - Return an integer indicating how general CT
02382 /// is.
02383 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
02384   switch (CT) {
02385   case TargetLowering::C_Other:
02386   case TargetLowering::C_Unknown:
02387     return 0;
02388   case TargetLowering::C_Register:
02389     return 1;
02390   case TargetLowering::C_RegisterClass:
02391     return 2;
02392   case TargetLowering::C_Memory:
02393     return 3;
02394   }
02395   llvm_unreachable("Invalid constraint type");
02396 }
02397 
02398 /// Examine constraint type and operand type and determine a weight value.
02399 /// This object must already have been set up with the operand type
02400 /// and the current alternative constraint selected.
02401 TargetLowering::ConstraintWeight
02402   TargetLowering::getMultipleConstraintMatchWeight(
02403     AsmOperandInfo &info, int maIndex) const {
02404   InlineAsm::ConstraintCodeVector *rCodes;
02405   if (maIndex >= (int)info.multipleAlternatives.size())
02406     rCodes = &info.Codes;
02407   else
02408     rCodes = &info.multipleAlternatives[maIndex].Codes;
02409   ConstraintWeight BestWeight = CW_Invalid;
02410 
02411   // Loop over the options, keeping track of the most general one.
02412   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
02413     ConstraintWeight weight =
02414       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
02415     if (weight > BestWeight)
02416       BestWeight = weight;
02417   }
02418 
02419   return BestWeight;
02420 }
02421 
02422 /// Examine constraint type and operand type and determine a weight value.
02423 /// This object must already have been set up with the operand type
02424 /// and the current alternative constraint selected.
02425 TargetLowering::ConstraintWeight
02426   TargetLowering::getSingleConstraintMatchWeight(
02427     AsmOperandInfo &info, const char *constraint) const {
02428   ConstraintWeight weight = CW_Invalid;
02429   Value *CallOperandVal = info.CallOperandVal;
02430     // If we don't have a value, we can't do a match,
02431     // but allow it at the lowest weight.
02432   if (!CallOperandVal)
02433     return CW_Default;
02434   // Look at the constraint type.
02435   switch (*constraint) {
02436     case 'i': // immediate integer.
02437     case 'n': // immediate integer with a known value.
02438       if (isa<ConstantInt>(CallOperandVal))
02439         weight = CW_Constant;
02440       break;
02441     case 's': // non-explicit intregal immediate.
02442       if (isa<GlobalValue>(CallOperandVal))
02443         weight = CW_Constant;
02444       break;
02445     case 'E': // immediate float if host format.
02446     case 'F': // immediate float.
02447       if (isa<ConstantFP>(CallOperandVal))
02448         weight = CW_Constant;
02449       break;
02450     case '<': // memory operand with autodecrement.
02451     case '>': // memory operand with autoincrement.
02452     case 'm': // memory operand.
02453     case 'o': // offsettable memory operand
02454     case 'V': // non-offsettable memory operand
02455       weight = CW_Memory;
02456       break;
02457     case 'r': // general register.
02458     case 'g': // general register, memory operand or immediate integer.
02459               // note: Clang converts "g" to "imr".
02460       if (CallOperandVal->getType()->isIntegerTy())
02461         weight = CW_Register;
02462       break;
02463     case 'X': // any operand.
02464     default:
02465       weight = CW_Default;
02466       break;
02467   }
02468   return weight;
02469 }
02470 
02471 /// ChooseConstraint - If there are multiple different constraints that we
02472 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
02473 /// This is somewhat tricky: constraints fall into four classes:
02474 ///    Other         -> immediates and magic values
02475 ///    Register      -> one specific register
02476 ///    RegisterClass -> a group of regs
02477 ///    Memory        -> memory
02478 /// Ideally, we would pick the most specific constraint possible: if we have
02479 /// something that fits into a register, we would pick it.  The problem here
02480 /// is that if we have something that could either be in a register or in
02481 /// memory that use of the register could cause selection of *other*
02482 /// operands to fail: they might only succeed if we pick memory.  Because of
02483 /// this the heuristic we use is:
02484 ///
02485 ///  1) If there is an 'other' constraint, and if the operand is valid for
02486 ///     that constraint, use it.  This makes us take advantage of 'i'
02487 ///     constraints when available.
02488 ///  2) Otherwise, pick the most general constraint present.  This prefers
02489 ///     'm' over 'r', for example.
02490 ///
02491 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
02492                              const TargetLowering &TLI,
02493                              SDValue Op, SelectionDAG *DAG) {
02494   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
02495   unsigned BestIdx = 0;
02496   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
02497   int BestGenerality = -1;
02498 
02499   // Loop over the options, keeping track of the most general one.
02500   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
02501     TargetLowering::ConstraintType CType =
02502       TLI.getConstraintType(OpInfo.Codes[i]);
02503 
02504     // If this is an 'other' constraint, see if the operand is valid for it.
02505     // For example, on X86 we might have an 'rI' constraint.  If the operand
02506     // is an integer in the range [0..31] we want to use I (saving a load
02507     // of a register), otherwise we must use 'r'.
02508     if (CType == TargetLowering::C_Other && Op.getNode()) {
02509       assert(OpInfo.Codes[i].size() == 1 &&
02510              "Unhandled multi-letter 'other' constraint");
02511       std::vector<SDValue> ResultOps;
02512       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
02513                                        ResultOps, *DAG);
02514       if (!ResultOps.empty()) {
02515         BestType = CType;
02516         BestIdx = i;
02517         break;
02518       }
02519     }
02520 
02521     // Things with matching constraints can only be registers, per gcc
02522     // documentation.  This mainly affects "g" constraints.
02523     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
02524       continue;
02525 
02526     // This constraint letter is more general than the previous one, use it.
02527     int Generality = getConstraintGenerality(CType);
02528     if (Generality > BestGenerality) {
02529       BestType = CType;
02530       BestIdx = i;
02531       BestGenerality = Generality;
02532     }
02533   }
02534 
02535   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
02536   OpInfo.ConstraintType = BestType;
02537 }
02538 
02539 /// ComputeConstraintToUse - Determines the constraint code and constraint
02540 /// type to use for the specific AsmOperandInfo, setting
02541 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
02542 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
02543                                             SDValue Op,
02544                                             SelectionDAG *DAG) const {
02545   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
02546 
02547   // Single-letter constraints ('r') are very common.
02548   if (OpInfo.Codes.size() == 1) {
02549     OpInfo.ConstraintCode = OpInfo.Codes[0];
02550     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
02551   } else {
02552     ChooseConstraint(OpInfo, *this, Op, DAG);
02553   }
02554 
02555   // 'X' matches anything.
02556   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
02557     // Labels and constants are handled elsewhere ('X' is the only thing
02558     // that matches labels).  For Functions, the type here is the type of
02559     // the result, which is not what we want to look at; leave them alone.
02560     Value *v = OpInfo.CallOperandVal;
02561     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
02562       OpInfo.CallOperandVal = v;
02563       return;
02564     }
02565 
02566     // Otherwise, try to resolve it to something we know about by looking at
02567     // the actual operand type.
02568     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
02569       OpInfo.ConstraintCode = Repl;
02570       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
02571     }
02572   }
02573 }
02574 
02575 /// \brief Given an exact SDIV by a constant, create a multiplication
02576 /// with the multiplicative inverse of the constant.
02577 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
02578                                        SelectionDAG &DAG) const {
02579   ConstantSDNode *C = cast<ConstantSDNode>(Op2);
02580   APInt d = C->getAPIntValue();
02581   assert(d != 0 && "Division by zero!");
02582 
02583   // Shift the value upfront if it is even, so the LSB is one.
02584   unsigned ShAmt = d.countTrailingZeros();
02585   if (ShAmt) {
02586     // TODO: For UDIV use SRL instead of SRA.
02587     SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
02588     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt);
02589     d = d.ashr(ShAmt);
02590   }
02591 
02592   // Calculate the multiplicative inverse, using Newton's method.
02593   APInt t, xn = d;
02594   while ((t = d*xn) != 1)
02595     xn *= APInt(d.getBitWidth(), 2) - t;
02596 
02597   Op2 = DAG.getConstant(xn, Op1.getValueType());
02598   return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
02599 }
02600 
02601 /// \brief Given an ISD::SDIV node expressing a divide by constant,
02602 /// return a DAG expression to select that will generate the same value by
02603 /// multiplying by a magic number.  See:
02604 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
02605 SDValue TargetLowering::
02606 BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
02607           std::vector<SDNode*> *Created) const {
02608   EVT VT = N->getValueType(0);
02609   SDLoc dl(N);
02610 
02611   // Check to see if we can do this.
02612   // FIXME: We should be more aggressive here.
02613   if (!isTypeLegal(VT))
02614     return SDValue();
02615 
02616   APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
02617   APInt::ms magics = d.magic();
02618 
02619   // Multiply the numerator (operand 0) by the magic value
02620   // FIXME: We should support doing a MUL in a wider type
02621   SDValue Q;
02622   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
02623                             isOperationLegalOrCustom(ISD::MULHS, VT))
02624     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
02625                     DAG.getConstant(magics.m, VT));
02626   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
02627                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
02628     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
02629                               N->getOperand(0),
02630                               DAG.getConstant(magics.m, VT)).getNode(), 1);
02631   else
02632     return SDValue();       // No mulhs or equvialent
02633   // If d > 0 and m < 0, add the numerator
02634   if (d.isStrictlyPositive() && magics.m.isNegative()) {
02635     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
02636     if (Created)
02637       Created->push_back(Q.getNode());
02638   }
02639   // If d < 0 and m > 0, subtract the numerator.
02640   if (d.isNegative() && magics.m.isStrictlyPositive()) {
02641     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
02642     if (Created)
02643       Created->push_back(Q.getNode());
02644   }
02645   // Shift right algebraic if shift value is nonzero
02646   if (magics.s > 0) {
02647     Q = DAG.getNode(ISD::SRA, dl, VT, Q,
02648                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
02649     if (Created)
02650       Created->push_back(Q.getNode());
02651   }
02652   // Extract the sign bit and add it to the quotient
02653   SDValue T =
02654     DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
02655                                            getShiftAmountTy(Q.getValueType())));
02656   if (Created)
02657     Created->push_back(T.getNode());
02658   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
02659 }
02660 
02661 /// \brief Given an ISD::UDIV node expressing a divide by constant,
02662 /// return a DAG expression to select that will generate the same value by
02663 /// multiplying by a magic number.  See:
02664 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
02665 SDValue TargetLowering::
02666 BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
02667           std::vector<SDNode*> *Created) const {
02668   EVT VT = N->getValueType(0);
02669   SDLoc dl(N);
02670 
02671   // Check to see if we can do this.
02672   // FIXME: We should be more aggressive here.
02673   if (!isTypeLegal(VT))
02674     return SDValue();
02675 
02676   // FIXME: We should use a narrower constant when the upper
02677   // bits are known to be zero.
02678   const APInt &N1C = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
02679   APInt::mu magics = N1C.magicu();
02680 
02681   SDValue Q = N->getOperand(0);
02682 
02683   // If the divisor is even, we can avoid using the expensive fixup by shifting
02684   // the divided value upfront.
02685   if (magics.a != 0 && !N1C[0]) {
02686     unsigned Shift = N1C.countTrailingZeros();
02687     Q = DAG.getNode(ISD::SRL, dl, VT, Q,
02688                     DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
02689     if (Created)
02690       Created->push_back(Q.getNode());
02691 
02692     // Get magic number for the shifted divisor.
02693     magics = N1C.lshr(Shift).magicu(Shift);
02694     assert(magics.a == 0 && "Should use cheap fixup now");
02695   }
02696 
02697   // Multiply the numerator (operand 0) by the magic value
02698   // FIXME: We should support doing a MUL in a wider type
02699   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
02700                             isOperationLegalOrCustom(ISD::MULHU, VT))
02701     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
02702   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
02703                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
02704     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
02705                             DAG.getConstant(magics.m, VT)).getNode(), 1);
02706   else
02707     return SDValue();       // No mulhu or equvialent
02708   if (Created)
02709     Created->push_back(Q.getNode());
02710 
02711   if (magics.a == 0) {
02712     assert(magics.s < N1C.getBitWidth() &&
02713            "We shouldn't generate an undefined shift!");
02714     return DAG.getNode(ISD::SRL, dl, VT, Q,
02715                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
02716   } else {
02717     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
02718     if (Created)
02719       Created->push_back(NPQ.getNode());
02720     NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
02721                       DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
02722     if (Created)
02723       Created->push_back(NPQ.getNode());
02724     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
02725     if (Created)
02726       Created->push_back(NPQ.getNode());
02727     return DAG.getNode(ISD::SRL, dl, VT, NPQ,
02728              DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));
02729   }
02730 }
02731 
02732 bool TargetLowering::
02733 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
02734   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
02735     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
02736                                 "be a constant integer");
02737     return true;
02738   }
02739 
02740   return false;
02741 }
02742 
02743 //===----------------------------------------------------------------------===//
02744 // Legalization Utilities
02745 //===----------------------------------------------------------------------===//
02746 
02747 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
02748                                SelectionDAG &DAG, SDValue LL, SDValue LH,
02749              SDValue RL, SDValue RH) const {
02750   EVT VT = N->getValueType(0);
02751   SDLoc dl(N);
02752 
02753   bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
02754   bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
02755   bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
02756   bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
02757   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
02758     unsigned OuterBitSize = VT.getSizeInBits();
02759     unsigned InnerBitSize = HiLoVT.getSizeInBits();
02760     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
02761     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
02762 
02763     // LL, LH, RL, and RH must be either all NULL or all set to a value.
02764     assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
02765            (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
02766 
02767     if (!LL.getNode() && !RL.getNode() &&
02768         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
02769       LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
02770       RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
02771     }
02772 
02773     if (!LL.getNode())
02774       return false;
02775 
02776     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
02777     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
02778         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
02779       // The inputs are both zero-extended.
02780       if (HasUMUL_LOHI) {
02781         // We can emit a umul_lohi.
02782         Lo = DAG.getNode(ISD::UMUL_LOHI, dl,
02783                    DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
02784         Hi = SDValue(Lo.getNode(), 1);
02785         return true;
02786       }
02787       if (HasMULHU) {
02788         // We can emit a mulhu+mul.
02789         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02790         Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
02791         return true;
02792       }
02793     }
02794     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
02795       // The input values are both sign-extended.
02796       if (HasSMUL_LOHI) {
02797         // We can emit a smul_lohi.
02798         Lo = DAG.getNode(ISD::SMUL_LOHI, dl,
02799                    DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
02800         Hi = SDValue(Lo.getNode(), 1);
02801         return true;
02802       }
02803       if (HasMULHS) {
02804         // We can emit a mulhs+mul.
02805         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02806         Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
02807         return true;
02808       }
02809     }
02810 
02811     if (!LH.getNode() && !RH.getNode() &&
02812         isOperationLegalOrCustom(ISD::SRL, VT) &&
02813         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
02814       unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
02815       SDValue Shift = DAG.getConstant(ShiftAmt, getShiftAmountTy(VT));
02816       LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
02817       LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
02818       RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
02819       RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
02820     }
02821 
02822     if (!LH.getNode())
02823       return false;
02824 
02825     if (HasUMUL_LOHI) {
02826       // Lo,Hi = umul LHS, RHS.
02827       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
02828                                      DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
02829       Lo = UMulLOHI;
02830       Hi = UMulLOHI.getValue(1);
02831       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
02832       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
02833       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
02834       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
02835       return true;
02836     }
02837     if (HasMULHU) {
02838       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
02839       Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
02840       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
02841       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
02842       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
02843       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
02844       return true;
02845     }
02846   }
02847   return false;
02848 }