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