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