1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
37 /// NOTE: The constructor takes ownership of TLOF.
38 TargetLowering::TargetLowering(const TargetMachine &tm,
39 const TargetLoweringObjectFile *tlof)
40 : TargetLoweringBase(tm, tlof) {}
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
46 /// Check whether a given call node is in tail position within its function. If
47 /// so, it sets Chain to the input chain of the tail call.
48 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
49 SDValue &Chain) const {
50 const Function *F = DAG.getMachineFunction().getFunction();
52 // Conservatively require the attributes of the call to match those of
53 // the return. Ignore noalias because it doesn't affect the call sequence.
54 AttributeSet CallerAttrs = F->getAttributes();
55 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
56 .removeAttribute(Attribute::NoAlias).hasAttributes())
59 // It's not safe to eliminate the sign / zero extension of the return value.
60 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
61 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
64 // Check if the only use is a function return node.
65 return isUsedByReturnOnly(Node, Chain);
68 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
69 /// and called function attributes.
70 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
72 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
73 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
74 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
75 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
76 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
77 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
78 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
79 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
80 Alignment = CS->getParamAlignment(AttrIdx);
83 /// Generate a libcall taking the given operands as arguments and returning a
84 /// result of type RetVT.
85 std::pair<SDValue, SDValue>
86 TargetLowering::makeLibCall(SelectionDAG &DAG,
87 RTLIB::Libcall LC, EVT RetVT,
88 const SDValue *Ops, unsigned NumOps,
89 bool isSigned, SDLoc dl,
91 bool isReturnValueUsed) const {
92 TargetLowering::ArgListTy Args;
95 TargetLowering::ArgListEntry Entry;
96 for (unsigned i = 0; i != NumOps; ++i) {
98 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
99 Entry.isSExt = isSigned;
100 Entry.isZExt = !isSigned;
101 Args.push_back(Entry);
103 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy());
105 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
106 TargetLowering::CallLoweringInfo CLI(DAG);
107 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
108 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
109 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
110 .setSExtResult(isSigned).setZExtResult(!isSigned);
111 return LowerCallTo(CLI);
115 /// SoftenSetCCOperands - Soften the operands of a comparison. This code is
116 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
117 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
118 SDValue &NewLHS, SDValue &NewRHS,
119 ISD::CondCode &CCCode,
121 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
122 && "Unsupported setcc type!");
124 // Expand into one or more soft-fp libcall(s).
125 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
129 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
130 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
134 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
135 (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
139 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
140 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
144 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
145 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
149 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
150 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
154 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
155 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
158 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
159 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
162 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
163 (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
166 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
167 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
170 // SETONE = SETOLT | SETOGT
171 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
172 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
175 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
176 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
179 LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
180 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
183 LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
184 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
187 LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
188 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
191 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
192 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
194 default: llvm_unreachable("Do not know how to soften this setcc!");
198 // Use the target specific return value for comparions lib calls.
199 EVT RetVT = getCmpLibcallReturnType();
200 SDValue Ops[2] = { NewLHS, NewRHS };
201 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/,
203 NewRHS = DAG.getConstant(0, RetVT);
204 CCCode = getCmpLibcallCC(LC1);
205 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
206 SDValue Tmp = DAG.getNode(ISD::SETCC, dl,
207 getSetCCResultType(*DAG.getContext(), RetVT),
208 NewLHS, NewRHS, DAG.getCondCode(CCCode));
209 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/,
211 NewLHS = DAG.getNode(ISD::SETCC, dl,
212 getSetCCResultType(*DAG.getContext(), RetVT), NewLHS,
213 NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
214 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
219 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
220 /// current function. The returned value is a member of the
221 /// MachineJumpTableInfo::JTEntryKind enum.
222 unsigned TargetLowering::getJumpTableEncoding() const {
223 // In non-pic modes, just use the address of a block.
224 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
225 return MachineJumpTableInfo::EK_BlockAddress;
227 // In PIC mode, if the target supports a GPRel32 directive, use it.
228 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
229 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
231 // Otherwise, use a label difference.
232 return MachineJumpTableInfo::EK_LabelDifference32;
235 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
236 SelectionDAG &DAG) const {
237 // If our PIC model is GP relative, use the global offset table as the base.
238 unsigned JTEncoding = getJumpTableEncoding();
240 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
241 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
242 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0));
247 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
248 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
251 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
252 unsigned JTI,MCContext &Ctx) const{
253 // The normal PIC reloc base is the label at the start of the jump table.
254 return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
258 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
259 // Assume that everything is safe in static mode.
260 if (getTargetMachine().getRelocationModel() == Reloc::Static)
263 // In dynamic-no-pic mode, assume that known defined values are safe.
264 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
266 !GA->getGlobal()->isDeclaration() &&
267 !GA->getGlobal()->isWeakForLinker())
270 // Otherwise assume nothing is safe.
274 //===----------------------------------------------------------------------===//
275 // Optimization Methods
276 //===----------------------------------------------------------------------===//
278 /// ShrinkDemandedConstant - Check to see if the specified operand of the
279 /// specified instruction is a constant integer. If so, check to see if there
280 /// are any bits set in the constant that are not demanded. If so, shrink the
281 /// constant and return true.
282 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
283 const APInt &Demanded) {
286 // FIXME: ISD::SELECT, ISD::SELECT_CC
287 switch (Op.getOpcode()) {
292 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
293 if (!C) return false;
295 if (Op.getOpcode() == ISD::XOR &&
296 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
299 // if we can expand it to have all bits set, do it
300 if (C->getAPIntValue().intersects(~Demanded)) {
301 EVT VT = Op.getValueType();
302 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
303 DAG.getConstant(Demanded &
306 return CombineTo(Op, New);
316 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
317 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
318 /// cast, but it could be generalized for targets with other types of
319 /// implicit widening casts.
321 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
323 const APInt &Demanded,
325 assert(Op.getNumOperands() == 2 &&
326 "ShrinkDemandedOp only supports binary operators!");
327 assert(Op.getNode()->getNumValues() == 1 &&
328 "ShrinkDemandedOp only supports nodes with one result!");
330 // Don't do this if the node has another user, which may require the
332 if (!Op.getNode()->hasOneUse())
335 // Search for the smallest integer type with free casts to and from
336 // Op's type. For expedience, just check power-of-2 integer types.
337 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
338 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
339 unsigned SmallVTBits = DemandedSize;
340 if (!isPowerOf2_32(SmallVTBits))
341 SmallVTBits = NextPowerOf2(SmallVTBits);
342 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
343 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
344 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
345 TLI.isZExtFree(SmallVT, Op.getValueType())) {
346 // We found a type with free casts.
347 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
348 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
349 Op.getNode()->getOperand(0)),
350 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
351 Op.getNode()->getOperand(1)));
352 bool NeedZext = DemandedSize > SmallVTBits;
353 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
354 dl, Op.getValueType(), X);
355 return CombineTo(Op, Z);
361 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
362 /// DemandedMask bits of the result of Op are ever used downstream. If we can
363 /// use this information to simplify Op, create a new simplified DAG node and
364 /// return true, returning the original and new nodes in Old and New. Otherwise,
365 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
366 /// the expression (used to simplify the caller). The KnownZero/One bits may
367 /// only be accurate for those bits in the DemandedMask.
368 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
369 const APInt &DemandedMask,
372 TargetLoweringOpt &TLO,
373 unsigned Depth) const {
374 unsigned BitWidth = DemandedMask.getBitWidth();
375 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
376 "Mask size mismatches value type size!");
377 APInt NewMask = DemandedMask;
380 // Don't know anything.
381 KnownZero = KnownOne = APInt(BitWidth, 0);
383 // Other users may use these bits.
384 if (!Op.getNode()->hasOneUse()) {
386 // If not at the root, Just compute the KnownZero/KnownOne bits to
387 // simplify things downstream.
388 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
391 // If this is the root being simplified, allow it to have multiple uses,
392 // just set the NewMask to all bits.
393 NewMask = APInt::getAllOnesValue(BitWidth);
394 } else if (DemandedMask == 0) {
395 // Not demanding any bits from Op.
396 if (Op.getOpcode() != ISD::UNDEF)
397 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
399 } else if (Depth == 6) { // Limit search depth.
403 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
404 switch (Op.getOpcode()) {
406 // We know all of the bits for a constant!
407 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
408 KnownZero = ~KnownOne;
409 return false; // Don't fall through, will infinitely loop.
411 // If the RHS is a constant, check to see if the LHS would be zero without
412 // using the bits from the RHS. Below, we use knowledge about the RHS to
413 // simplify the LHS, here we're using information from the LHS to simplify
415 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
416 APInt LHSZero, LHSOne;
417 // Do not increment Depth here; that can cause an infinite loop.
418 TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
419 // If the LHS already has zeros where RHSC does, this and is dead.
420 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
421 return TLO.CombineTo(Op, Op.getOperand(0));
422 // If any of the set bits in the RHS are known zero on the LHS, shrink
424 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
428 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
429 KnownOne, TLO, Depth+1))
431 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
432 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
433 KnownZero2, KnownOne2, TLO, Depth+1))
435 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
437 // If all of the demanded bits are known one on one side, return the other.
438 // These bits cannot contribute to the result of the 'and'.
439 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
440 return TLO.CombineTo(Op, Op.getOperand(0));
441 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
442 return TLO.CombineTo(Op, Op.getOperand(1));
443 // If all of the demanded bits in the inputs are known zeros, return zero.
444 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
445 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
446 // If the RHS is a constant, see if we can simplify it.
447 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
449 // If the operation can be done in a smaller type, do so.
450 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
453 // Output known-1 bits are only known if set in both the LHS & RHS.
454 KnownOne &= KnownOne2;
455 // Output known-0 are known to be clear if zero in either the LHS | RHS.
456 KnownZero |= KnownZero2;
459 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
460 KnownOne, TLO, Depth+1))
462 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
463 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
464 KnownZero2, KnownOne2, TLO, Depth+1))
466 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
468 // If all of the demanded bits are known zero on one side, return the other.
469 // These bits cannot contribute to the result of the 'or'.
470 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
471 return TLO.CombineTo(Op, Op.getOperand(0));
472 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
473 return TLO.CombineTo(Op, Op.getOperand(1));
474 // If all of the potentially set bits on one side are known to be set on
475 // the other side, just use the 'other' side.
476 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
477 return TLO.CombineTo(Op, Op.getOperand(0));
478 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
479 return TLO.CombineTo(Op, Op.getOperand(1));
480 // If the RHS is a constant, see if we can simplify it.
481 if (TLO.ShrinkDemandedConstant(Op, NewMask))
483 // If the operation can be done in a smaller type, do so.
484 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
487 // Output known-0 bits are only known if clear in both the LHS & RHS.
488 KnownZero &= KnownZero2;
489 // Output known-1 are known to be set if set in either the LHS | RHS.
490 KnownOne |= KnownOne2;
493 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
494 KnownOne, TLO, Depth+1))
496 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
497 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
498 KnownOne2, TLO, Depth+1))
500 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
502 // If all of the demanded bits are known zero on one side, return the other.
503 // These bits cannot contribute to the result of the 'xor'.
504 if ((KnownZero & NewMask) == NewMask)
505 return TLO.CombineTo(Op, Op.getOperand(0));
506 if ((KnownZero2 & NewMask) == NewMask)
507 return TLO.CombineTo(Op, Op.getOperand(1));
508 // If the operation can be done in a smaller type, do so.
509 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
512 // If all of the unknown bits are known to be zero on one side or the other
513 // (but not both) turn this into an *inclusive* or.
514 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
515 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
516 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
520 // Output known-0 bits are known if clear or set in both the LHS & RHS.
521 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
522 // Output known-1 are known to be set if set in only one of the LHS, RHS.
523 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
525 // If all of the demanded bits on one side are known, and all of the set
526 // bits on that side are also known to be set on the other side, turn this
527 // into an AND, as we know the bits will be cleared.
528 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
529 // NB: it is okay if more bits are known than are requested
530 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
531 if (KnownOne == KnownOne2) { // set bits are the same on both sides
532 EVT VT = Op.getValueType();
533 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
534 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
535 Op.getOperand(0), ANDC));
539 // If the RHS is a constant, see if we can simplify it.
540 // for XOR, we prefer to force bits to 1 if they will make a -1.
541 // if we can't force bits, try to shrink constant
542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
543 APInt Expanded = C->getAPIntValue() | (~NewMask);
544 // if we can expand it to have all bits set, do it
545 if (Expanded.isAllOnesValue()) {
546 if (Expanded != C->getAPIntValue()) {
547 EVT VT = Op.getValueType();
548 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
549 TLO.DAG.getConstant(Expanded, VT));
550 return TLO.CombineTo(Op, New);
552 // if it already has all the bits set, nothing to change
553 // but don't shrink either!
554 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
559 KnownZero = KnownZeroOut;
560 KnownOne = KnownOneOut;
563 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
564 KnownOne, TLO, Depth+1))
566 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
567 KnownOne2, TLO, Depth+1))
569 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
570 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
572 // If the operands are constants, see if we can simplify them.
573 if (TLO.ShrinkDemandedConstant(Op, NewMask))
576 // Only known if known in both the LHS and RHS.
577 KnownOne &= KnownOne2;
578 KnownZero &= KnownZero2;
581 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
582 KnownOne, TLO, Depth+1))
584 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
585 KnownOne2, TLO, Depth+1))
587 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
588 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
590 // If the operands are constants, see if we can simplify them.
591 if (TLO.ShrinkDemandedConstant(Op, NewMask))
594 // Only known if known in both the LHS and RHS.
595 KnownOne &= KnownOne2;
596 KnownZero &= KnownZero2;
599 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
600 unsigned ShAmt = SA->getZExtValue();
601 SDValue InOp = Op.getOperand(0);
603 // If the shift count is an invalid immediate, don't do anything.
604 if (ShAmt >= BitWidth)
607 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
608 // single shift. We can do this if the bottom bits (which are shifted
609 // out) are never demanded.
610 if (InOp.getOpcode() == ISD::SRL &&
611 isa<ConstantSDNode>(InOp.getOperand(1))) {
612 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
613 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
614 unsigned Opc = ISD::SHL;
622 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
623 EVT VT = Op.getValueType();
624 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
625 InOp.getOperand(0), NewSA));
629 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
630 KnownZero, KnownOne, TLO, Depth+1))
633 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
634 // are not demanded. This will likely allow the anyext to be folded away.
635 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
636 SDValue InnerOp = InOp.getNode()->getOperand(0);
637 EVT InnerVT = InnerOp.getValueType();
638 unsigned InnerBits = InnerVT.getSizeInBits();
639 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
640 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
641 EVT ShTy = getShiftAmountTy(InnerVT);
642 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
645 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
646 TLO.DAG.getConstant(ShAmt, ShTy));
649 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
652 // Repeat the SHL optimization above in cases where an extension
653 // intervenes: (shl (anyext (shr x, c1)), c2) to
654 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
655 // aren't demanded (as above) and that the shifted upper c1 bits of
656 // x aren't demanded.
657 if (InOp.hasOneUse() &&
658 InnerOp.getOpcode() == ISD::SRL &&
659 InnerOp.hasOneUse() &&
660 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
661 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
663 if (InnerShAmt < ShAmt &&
664 InnerShAmt < InnerBits &&
665 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
666 NewMask.trunc(ShAmt) == 0) {
668 TLO.DAG.getConstant(ShAmt - InnerShAmt,
669 Op.getOperand(1).getValueType());
670 EVT VT = Op.getValueType();
671 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
672 InnerOp.getOperand(0));
673 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
679 KnownZero <<= SA->getZExtValue();
680 KnownOne <<= SA->getZExtValue();
681 // low bits known zero.
682 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
686 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
687 EVT VT = Op.getValueType();
688 unsigned ShAmt = SA->getZExtValue();
689 unsigned VTSize = VT.getSizeInBits();
690 SDValue InOp = Op.getOperand(0);
692 // If the shift count is an invalid immediate, don't do anything.
693 if (ShAmt >= BitWidth)
696 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
697 // single shift. We can do this if the top bits (which are shifted out)
698 // are never demanded.
699 if (InOp.getOpcode() == ISD::SHL &&
700 isa<ConstantSDNode>(InOp.getOperand(1))) {
701 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
702 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
703 unsigned Opc = ISD::SRL;
711 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
712 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
713 InOp.getOperand(0), NewSA));
717 // Compute the new bits that are at the top now.
718 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
719 KnownZero, KnownOne, TLO, Depth+1))
721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
722 KnownZero = KnownZero.lshr(ShAmt);
723 KnownOne = KnownOne.lshr(ShAmt);
725 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
726 KnownZero |= HighBits; // High bits known zero.
730 // If this is an arithmetic shift right and only the low-bit is set, we can
731 // always convert this into a logical shr, even if the shift amount is
732 // variable. The low bit of the shift cannot be an input sign bit unless
733 // the shift amount is >= the size of the datatype, which is undefined.
735 return TLO.CombineTo(Op,
736 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
737 Op.getOperand(0), Op.getOperand(1)));
739 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
740 EVT VT = Op.getValueType();
741 unsigned ShAmt = SA->getZExtValue();
743 // If the shift count is an invalid immediate, don't do anything.
744 if (ShAmt >= BitWidth)
747 APInt InDemandedMask = (NewMask << ShAmt);
749 // If any of the demanded bits are produced by the sign extension, we also
750 // demand the input sign bit.
751 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
752 if (HighBits.intersects(NewMask))
753 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
755 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
756 KnownZero, KnownOne, TLO, Depth+1))
758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 KnownZero = KnownZero.lshr(ShAmt);
760 KnownOne = KnownOne.lshr(ShAmt);
762 // Handle the sign bit, adjusted to where it is now in the mask.
763 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
765 // If the input sign bit is known to be zero, or if none of the top bits
766 // are demanded, turn this into an unsigned shift right.
767 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits)
768 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
772 int Log2 = NewMask.exactLogBase2();
774 // The bit must come from the sign.
776 TLO.DAG.getConstant(BitWidth - 1 - Log2,
777 Op.getOperand(1).getValueType());
778 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
779 Op.getOperand(0), NewSA));
782 if (KnownOne.intersects(SignBit))
783 // New bits are known one.
784 KnownOne |= HighBits;
787 case ISD::SIGN_EXTEND_INREG: {
788 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
790 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
791 // If we only care about the highest bit, don't bother shifting right.
792 if (MsbMask == DemandedMask) {
793 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
794 SDValue InOp = Op.getOperand(0);
796 // Compute the correct shift amount type, which must be getShiftAmountTy
797 // for scalar types after legalization.
798 EVT ShiftAmtTy = Op.getValueType();
799 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
800 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
802 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
803 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
804 Op.getValueType(), InOp, ShiftAmt));
807 // Sign extension. Compute the demanded bits in the result that are not
808 // present in the input.
810 APInt::getHighBitsSet(BitWidth,
811 BitWidth - ExVT.getScalarType().getSizeInBits());
813 // If none of the extended bits are demanded, eliminate the sextinreg.
814 if ((NewBits & NewMask) == 0)
815 return TLO.CombineTo(Op, Op.getOperand(0));
818 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
819 APInt InputDemandedBits =
820 APInt::getLowBitsSet(BitWidth,
821 ExVT.getScalarType().getSizeInBits()) &
824 // Since the sign extended bits are demanded, we know that the sign
826 InputDemandedBits |= InSignBit;
828 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
829 KnownZero, KnownOne, TLO, Depth+1))
831 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
833 // If the sign bit of the input is known set or clear, then we know the
834 // top bits of the result.
836 // If the input sign bit is known zero, convert this into a zero extension.
837 if (KnownZero.intersects(InSignBit))
838 return TLO.CombineTo(Op,
839 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
841 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
843 KnownZero &= ~NewBits;
844 } else { // Input sign bit unknown
845 KnownZero &= ~NewBits;
846 KnownOne &= ~NewBits;
850 case ISD::BUILD_PAIR: {
851 EVT HalfVT = Op.getOperand(0).getValueType();
852 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
854 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
855 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
857 APInt KnownZeroLo, KnownOneLo;
858 APInt KnownZeroHi, KnownOneHi;
860 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
861 KnownOneLo, TLO, Depth + 1))
864 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
865 KnownOneHi, TLO, Depth + 1))
868 KnownZero = KnownZeroLo.zext(BitWidth) |
869 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
871 KnownOne = KnownOneLo.zext(BitWidth) |
872 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
875 case ISD::ZERO_EXTEND: {
876 unsigned OperandBitWidth =
877 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
878 APInt InMask = NewMask.trunc(OperandBitWidth);
880 // If none of the top bits are demanded, convert this into an any_extend.
882 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
883 if (!NewBits.intersects(NewMask))
884 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
888 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
889 KnownZero, KnownOne, TLO, Depth+1))
891 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
892 KnownZero = KnownZero.zext(BitWidth);
893 KnownOne = KnownOne.zext(BitWidth);
894 KnownZero |= NewBits;
897 case ISD::SIGN_EXTEND: {
898 EVT InVT = Op.getOperand(0).getValueType();
899 unsigned InBits = InVT.getScalarType().getSizeInBits();
900 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
901 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
902 APInt NewBits = ~InMask & NewMask;
904 // If none of the top bits are demanded, convert this into an any_extend.
906 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
910 // Since some of the sign extended bits are demanded, we know that the sign
912 APInt InDemandedBits = InMask & NewMask;
913 InDemandedBits |= InSignBit;
914 InDemandedBits = InDemandedBits.trunc(InBits);
916 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
917 KnownOne, TLO, Depth+1))
919 KnownZero = KnownZero.zext(BitWidth);
920 KnownOne = KnownOne.zext(BitWidth);
922 // If the sign bit is known zero, convert this to a zero extend.
923 if (KnownZero.intersects(InSignBit))
924 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
928 // If the sign bit is known one, the top bits match.
929 if (KnownOne.intersects(InSignBit)) {
931 assert((KnownZero & NewBits) == 0);
932 } else { // Otherwise, top bits aren't known.
933 assert((KnownOne & NewBits) == 0);
934 assert((KnownZero & NewBits) == 0);
938 case ISD::ANY_EXTEND: {
939 unsigned OperandBitWidth =
940 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
941 APInt InMask = NewMask.trunc(OperandBitWidth);
942 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
943 KnownZero, KnownOne, TLO, Depth+1))
945 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
946 KnownZero = KnownZero.zext(BitWidth);
947 KnownOne = KnownOne.zext(BitWidth);
950 case ISD::TRUNCATE: {
951 // Simplify the input, using demanded bit information, and compute the known
952 // zero/one bits live out.
953 unsigned OperandBitWidth =
954 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
955 APInt TruncMask = NewMask.zext(OperandBitWidth);
956 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
957 KnownZero, KnownOne, TLO, Depth+1))
959 KnownZero = KnownZero.trunc(BitWidth);
960 KnownOne = KnownOne.trunc(BitWidth);
962 // If the input is only used by this truncate, see if we can shrink it based
963 // on the known demanded bits.
964 if (Op.getOperand(0).getNode()->hasOneUse()) {
965 SDValue In = Op.getOperand(0);
966 switch (In.getOpcode()) {
969 // Shrink SRL by a constant if none of the high bits shifted in are
971 if (TLO.LegalTypes() &&
972 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
973 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
976 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
979 SDValue Shift = In.getOperand(1);
980 if (TLO.LegalTypes()) {
981 uint64_t ShVal = ShAmt->getZExtValue();
983 TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
986 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
987 OperandBitWidth - BitWidth);
988 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
990 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
991 // None of the shifted in bits are needed. Add a truncate of the
992 // shift input, then shift it.
993 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
996 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1005 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1008 case ISD::AssertZext: {
1009 // AssertZext demands all of the high bits, plus any of the low bits
1010 // demanded by its users.
1011 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1012 APInt InMask = APInt::getLowBitsSet(BitWidth,
1013 VT.getSizeInBits());
1014 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1015 KnownZero, KnownOne, TLO, Depth+1))
1017 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1019 KnownZero |= ~InMask & NewMask;
1023 // If this is an FP->Int bitcast and if the sign bit is the only
1024 // thing demanded, turn this into a FGETSIGN.
1025 if (!TLO.LegalOperations() &&
1026 !Op.getValueType().isVector() &&
1027 !Op.getOperand(0).getValueType().isVector() &&
1028 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1029 Op.getOperand(0).getValueType().isFloatingPoint()) {
1030 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1031 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1032 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
1033 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1034 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1035 // place. We expect the SHL to be eliminated by other optimizations.
1036 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1037 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1038 if (!OpVTLegal && OpVTSizeInBits > 32)
1039 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1040 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1041 SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
1042 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1051 // Add, Sub, and Mul don't demand any bits in positions beyond that
1052 // of the highest bit demanded of them.
1053 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1054 BitWidth - NewMask.countLeadingZeros());
1055 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1056 KnownOne2, TLO, Depth+1))
1058 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1059 KnownOne2, TLO, Depth+1))
1061 // See if the operation should be performed at a smaller bit width.
1062 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1067 // Just use computeKnownBits to compute output bits.
1068 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1072 // If we know the value of all of the demanded bits, return this as a
1074 if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1075 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1080 /// computeKnownBitsForTargetNode - Determine which of the bits specified
1081 /// in Mask are known to be either zero or one and return them in the
1082 /// KnownZero/KnownOne bitsets.
1083 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1086 const SelectionDAG &DAG,
1087 unsigned Depth) const {
1088 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1089 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1090 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1091 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1092 "Should use MaskedValueIsZero if you don't know whether Op"
1093 " is a target node!");
1094 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1097 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1098 /// targets that want to expose additional information about sign bits to the
1100 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1101 const SelectionDAG &,
1102 unsigned Depth) const {
1103 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1104 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1105 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1106 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1107 "Should use ComputeNumSignBits if you don't know whether Op"
1108 " is a target node!");
1112 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1113 /// one bit set. This differs from computeKnownBits in that it doesn't need to
1114 /// determine which bit is set.
1116 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1117 // A left-shift of a constant one will have exactly one bit set, because
1118 // shifting the bit off the end is undefined.
1119 if (Val.getOpcode() == ISD::SHL)
1120 if (ConstantSDNode *C =
1121 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1122 if (C->getAPIntValue() == 1)
1125 // Similarly, a right-shift of a constant sign-bit will have exactly
1127 if (Val.getOpcode() == ISD::SRL)
1128 if (ConstantSDNode *C =
1129 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1130 if (C->getAPIntValue().isSignBit())
1133 // More could be done here, though the above checks are enough
1134 // to handle some common cases.
1136 // Fall back to computeKnownBits to catch other known cases.
1137 EVT OpVT = Val.getValueType();
1138 unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
1139 APInt KnownZero, KnownOne;
1140 DAG.computeKnownBits(Val, KnownZero, KnownOne);
1141 return (KnownZero.countPopulation() == BitWidth - 1) &&
1142 (KnownOne.countPopulation() == 1);
1145 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1150 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1152 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1157 CN = BV->getConstantSplatValue();
1160 switch (getBooleanContents(IsVec)) {
1161 case UndefinedBooleanContent:
1162 return CN->getAPIntValue()[0];
1163 case ZeroOrOneBooleanContent:
1165 case ZeroOrNegativeOneBooleanContent:
1166 return CN->isAllOnesValue();
1169 llvm_unreachable("Invalid boolean contents");
1172 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1177 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1179 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1184 CN = BV->getConstantSplatValue();
1187 if (getBooleanContents(IsVec) == UndefinedBooleanContent)
1188 return !CN->getAPIntValue()[0];
1190 return CN->isNullValue();
1193 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1194 /// and cc. If it is unable to simplify it, return a null SDValue.
1196 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1197 ISD::CondCode Cond, bool foldBooleans,
1198 DAGCombinerInfo &DCI, SDLoc dl) const {
1199 SelectionDAG &DAG = DCI.DAG;
1201 // These setcc operations always fold.
1205 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1207 case ISD::SETTRUE2: {
1208 TargetLowering::BooleanContent Cnt = getBooleanContents(VT.isVector());
1209 return DAG.getConstant(
1210 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
1214 // Ensure that the constant occurs on the RHS, and fold constant
1216 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1217 if (isa<ConstantSDNode>(N0.getNode()) &&
1218 (DCI.isBeforeLegalizeOps() ||
1219 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1220 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1222 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1223 const APInt &C1 = N1C->getAPIntValue();
1225 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1226 // equality comparison, then we're just comparing whether X itself is
1228 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1229 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1230 N0.getOperand(1).getOpcode() == ISD::Constant) {
1232 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1233 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1234 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1235 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1236 // (srl (ctlz x), 5) == 0 -> X != 0
1237 // (srl (ctlz x), 5) != 1 -> X != 0
1240 // (srl (ctlz x), 5) != 0 -> X == 0
1241 // (srl (ctlz x), 5) == 1 -> X == 0
1244 SDValue Zero = DAG.getConstant(0, N0.getValueType());
1245 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1251 // Look through truncs that don't change the value of a ctpop.
1252 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1253 CTPOP = N0.getOperand(0);
1255 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1256 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1257 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1258 EVT CTVT = CTPOP.getValueType();
1259 SDValue CTOp = CTPOP.getOperand(0);
1261 // (ctpop x) u< 2 -> (x & x-1) == 0
1262 // (ctpop x) u> 1 -> (x & x-1) != 0
1263 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1264 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1265 DAG.getConstant(1, CTVT));
1266 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1267 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1268 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
1271 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1274 // (zext x) == C --> x == (trunc C)
1275 if (DCI.isBeforeLegalize() && N0->hasOneUse() &&
1276 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1277 unsigned MinBits = N0.getValueSizeInBits();
1279 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1281 MinBits = N0->getOperand(0).getValueSizeInBits();
1282 PreZExt = N0->getOperand(0);
1283 } else if (N0->getOpcode() == ISD::AND) {
1284 // DAGCombine turns costly ZExts into ANDs
1285 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1286 if ((C->getAPIntValue()+1).isPowerOf2()) {
1287 MinBits = C->getAPIntValue().countTrailingOnes();
1288 PreZExt = N0->getOperand(0);
1290 } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
1292 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1293 MinBits = LN0->getMemoryVT().getSizeInBits();
1298 // Make sure we're not losing bits from the constant.
1300 MinBits < C1.getBitWidth() && MinBits >= C1.getActiveBits()) {
1301 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1302 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1303 // Will get folded away.
1304 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt);
1305 SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
1306 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1311 // If the LHS is '(and load, const)', the RHS is 0,
1312 // the test is for equality or unsigned, and all 1 bits of the const are
1313 // in the same partial word, see if we can shorten the load.
1314 if (DCI.isBeforeLegalize() &&
1315 !ISD::isSignedIntSetCC(Cond) &&
1316 N0.getOpcode() == ISD::AND && C1 == 0 &&
1317 N0.getNode()->hasOneUse() &&
1318 isa<LoadSDNode>(N0.getOperand(0)) &&
1319 N0.getOperand(0).getNode()->hasOneUse() &&
1320 isa<ConstantSDNode>(N0.getOperand(1))) {
1321 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1323 unsigned bestWidth = 0, bestOffset = 0;
1324 if (!Lod->isVolatile() && Lod->isUnindexed()) {
1325 unsigned origWidth = N0.getValueType().getSizeInBits();
1326 unsigned maskWidth = origWidth;
1327 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1328 // 8 bits, but have to be careful...
1329 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1330 origWidth = Lod->getMemoryVT().getSizeInBits();
1332 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1333 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1334 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1335 for (unsigned offset=0; offset<origWidth/width; offset++) {
1336 if ((newMask & Mask) == Mask) {
1337 if (!getDataLayout()->isLittleEndian())
1338 bestOffset = (origWidth/width - offset - 1) * (width/8);
1340 bestOffset = (uint64_t)offset * (width/8);
1341 bestMask = Mask.lshr(offset * (width/8) * 8);
1345 newMask = newMask << width;
1350 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1351 if (newVT.isRound()) {
1352 EVT PtrType = Lod->getOperand(1).getValueType();
1353 SDValue Ptr = Lod->getBasePtr();
1354 if (bestOffset != 0)
1355 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1356 DAG.getConstant(bestOffset, PtrType));
1357 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1358 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
1359 Lod->getPointerInfo().getWithOffset(bestOffset),
1360 false, false, false, NewAlign);
1361 return DAG.getSetCC(dl, VT,
1362 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1363 DAG.getConstant(bestMask.trunc(bestWidth),
1365 DAG.getConstant(0LL, newVT), Cond);
1370 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1371 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1372 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1374 // If the comparison constant has bits in the upper part, the
1375 // zero-extended value could never match.
1376 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1377 C1.getBitWidth() - InSize))) {
1381 case ISD::SETEQ: return DAG.getConstant(0, VT);
1384 case ISD::SETNE: return DAG.getConstant(1, VT);
1387 // True if the sign bit of C1 is set.
1388 return DAG.getConstant(C1.isNegative(), VT);
1391 // True if the sign bit of C1 isn't set.
1392 return DAG.getConstant(C1.isNonNegative(), VT);
1398 // Otherwise, we can perform the comparison with the low bits.
1406 EVT newVT = N0.getOperand(0).getValueType();
1407 if (DCI.isBeforeLegalizeOps() ||
1408 (isOperationLegal(ISD::SETCC, newVT) &&
1409 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1410 EVT NewSetCCVT = getSetCCResultType(*DAG.getContext(), newVT);
1411 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), newVT);
1413 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1415 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT);
1420 break; // todo, be more careful with signed comparisons
1422 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1423 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1424 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1425 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1426 EVT ExtDstTy = N0.getValueType();
1427 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1429 // If the constant doesn't fit into the number of bits for the source of
1430 // the sign extension, it is impossible for both sides to be equal.
1431 if (C1.getMinSignedBits() > ExtSrcTyBits)
1432 return DAG.getConstant(Cond == ISD::SETNE, VT);
1435 EVT Op0Ty = N0.getOperand(0).getValueType();
1436 if (Op0Ty == ExtSrcTy) {
1437 ZextOp = N0.getOperand(0);
1439 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1440 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1441 DAG.getConstant(Imm, Op0Ty));
1443 if (!DCI.isCalledByLegalizer())
1444 DCI.AddToWorklist(ZextOp.getNode());
1445 // Otherwise, make this a use of a zext.
1446 return DAG.getSetCC(dl, VT, ZextOp,
1447 DAG.getConstant(C1 & APInt::getLowBitsSet(
1452 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1453 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1454 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1455 if (N0.getOpcode() == ISD::SETCC &&
1456 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1457 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1459 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1460 // Invert the condition.
1461 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1462 CC = ISD::getSetCCInverse(CC,
1463 N0.getOperand(0).getValueType().isInteger());
1464 if (DCI.isBeforeLegalizeOps() ||
1465 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1466 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1469 if ((N0.getOpcode() == ISD::XOR ||
1470 (N0.getOpcode() == ISD::AND &&
1471 N0.getOperand(0).getOpcode() == ISD::XOR &&
1472 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1473 isa<ConstantSDNode>(N0.getOperand(1)) &&
1474 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1475 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1476 // can only do this if the top bits are known zero.
1477 unsigned BitWidth = N0.getValueSizeInBits();
1478 if (DAG.MaskedValueIsZero(N0,
1479 APInt::getHighBitsSet(BitWidth,
1481 // Okay, get the un-inverted input value.
1483 if (N0.getOpcode() == ISD::XOR)
1484 Val = N0.getOperand(0);
1486 assert(N0.getOpcode() == ISD::AND &&
1487 N0.getOperand(0).getOpcode() == ISD::XOR);
1488 // ((X^1)&1)^1 -> X & 1
1489 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1490 N0.getOperand(0).getOperand(0),
1494 return DAG.getSetCC(dl, VT, Val, N1,
1495 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1497 } else if (N1C->getAPIntValue() == 1 &&
1499 getBooleanContents(false) == ZeroOrOneBooleanContent)) {
1501 if (Op0.getOpcode() == ISD::TRUNCATE)
1502 Op0 = Op0.getOperand(0);
1504 if ((Op0.getOpcode() == ISD::XOR) &&
1505 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1506 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1507 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1508 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1509 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1512 if (Op0.getOpcode() == ISD::AND &&
1513 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1514 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1515 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1516 if (Op0.getValueType().bitsGT(VT))
1517 Op0 = DAG.getNode(ISD::AND, dl, VT,
1518 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1519 DAG.getConstant(1, VT));
1520 else if (Op0.getValueType().bitsLT(VT))
1521 Op0 = DAG.getNode(ISD::AND, dl, VT,
1522 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1523 DAG.getConstant(1, VT));
1525 return DAG.getSetCC(dl, VT, Op0,
1526 DAG.getConstant(0, Op0.getValueType()),
1527 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1529 if (Op0.getOpcode() == ISD::AssertZext &&
1530 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1531 return DAG.getSetCC(dl, VT, Op0,
1532 DAG.getConstant(0, Op0.getValueType()),
1533 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1537 APInt MinVal, MaxVal;
1538 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1539 if (ISD::isSignedIntSetCC(Cond)) {
1540 MinVal = APInt::getSignedMinValue(OperandBitSize);
1541 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1543 MinVal = APInt::getMinValue(OperandBitSize);
1544 MaxVal = APInt::getMaxValue(OperandBitSize);
1547 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1548 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1549 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
1550 // X >= C0 --> X > (C0 - 1)
1552 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1553 if ((DCI.isBeforeLegalizeOps() ||
1554 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1555 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1556 isLegalICmpImmediate(C.getSExtValue())))) {
1557 return DAG.getSetCC(dl, VT, N0,
1558 DAG.getConstant(C, N1.getValueType()),
1563 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1564 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
1565 // X <= C0 --> X < (C0 + 1)
1567 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1568 if ((DCI.isBeforeLegalizeOps() ||
1569 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1570 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1571 isLegalICmpImmediate(C.getSExtValue())))) {
1572 return DAG.getSetCC(dl, VT, N0,
1573 DAG.getConstant(C, N1.getValueType()),
1578 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1579 return DAG.getConstant(0, VT); // X < MIN --> false
1580 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1581 return DAG.getConstant(1, VT); // X >= MIN --> true
1582 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1583 return DAG.getConstant(0, VT); // X > MAX --> false
1584 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1585 return DAG.getConstant(1, VT); // X <= MAX --> true
1587 // Canonicalize setgt X, Min --> setne X, Min
1588 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1589 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1590 // Canonicalize setlt X, Max --> setne X, Max
1591 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1592 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1594 // If we have setult X, 1, turn it into seteq X, 0
1595 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1596 return DAG.getSetCC(dl, VT, N0,
1597 DAG.getConstant(MinVal, N0.getValueType()),
1599 // If we have setugt X, Max-1, turn it into seteq X, Max
1600 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1601 return DAG.getSetCC(dl, VT, N0,
1602 DAG.getConstant(MaxVal, N0.getValueType()),
1605 // If we have "setcc X, C0", check to see if we can shrink the immediate
1608 // SETUGT X, SINTMAX -> SETLT X, 0
1609 if (Cond == ISD::SETUGT &&
1610 C1 == APInt::getSignedMaxValue(OperandBitSize))
1611 return DAG.getSetCC(dl, VT, N0,
1612 DAG.getConstant(0, N1.getValueType()),
1615 // SETULT X, SINTMIN -> SETGT X, -1
1616 if (Cond == ISD::SETULT &&
1617 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1618 SDValue ConstMinusOne =
1619 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
1621 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1624 // Fold bit comparisons when we can.
1625 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1626 (VT == N0.getValueType() ||
1627 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1628 N0.getOpcode() == ISD::AND)
1629 if (ConstantSDNode *AndRHS =
1630 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1631 EVT ShiftTy = DCI.isBeforeLegalize() ?
1632 getPointerTy() : getShiftAmountTy(N0.getValueType());
1633 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1634 // Perform the xform if the AND RHS is a single bit.
1635 if (AndRHS->getAPIntValue().isPowerOf2()) {
1636 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1637 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1638 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
1640 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1641 // (X & 8) == 8 --> (X & 8) >> 3
1642 // Perform the xform if C1 is a single bit.
1643 if (C1.isPowerOf2()) {
1644 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1645 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1646 DAG.getConstant(C1.logBase2(), ShiftTy)));
1651 if (C1.getMinSignedBits() <= 64 &&
1652 !isLegalICmpImmediate(C1.getSExtValue())) {
1653 // (X & -256) == 256 -> (X >> 8) == 1
1654 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1655 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
1656 if (ConstantSDNode *AndRHS =
1657 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1658 const APInt &AndRHSC = AndRHS->getAPIntValue();
1659 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1660 unsigned ShiftBits = AndRHSC.countTrailingZeros();
1661 EVT ShiftTy = DCI.isBeforeLegalize() ?
1662 getPointerTy() : getShiftAmountTy(N0.getValueType());
1663 EVT CmpTy = N0.getValueType();
1664 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
1665 DAG.getConstant(ShiftBits, ShiftTy));
1666 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
1667 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1670 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1671 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1672 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1673 // X < 0x100000000 -> (X >> 32) < 1
1674 // X >= 0x100000000 -> (X >> 32) >= 1
1675 // X <= 0x0ffffffff -> (X >> 32) < 1
1676 // X > 0x0ffffffff -> (X >> 32) >= 1
1679 ISD::CondCode NewCond = Cond;
1681 ShiftBits = C1.countTrailingOnes();
1683 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1685 ShiftBits = C1.countTrailingZeros();
1687 NewC = NewC.lshr(ShiftBits);
1688 if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
1689 EVT ShiftTy = DCI.isBeforeLegalize() ?
1690 getPointerTy() : getShiftAmountTy(N0.getValueType());
1691 EVT CmpTy = N0.getValueType();
1692 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
1693 DAG.getConstant(ShiftBits, ShiftTy));
1694 SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
1695 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1701 if (isa<ConstantFPSDNode>(N0.getNode())) {
1702 // Constant fold or commute setcc.
1703 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
1704 if (O.getNode()) return O;
1705 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1706 // If the RHS of an FP comparison is a constant, simplify it away in
1708 if (CFP->getValueAPF().isNaN()) {
1709 // If an operand is known to be a nan, we can fold it.
1710 switch (ISD::getUnorderedFlavor(Cond)) {
1711 default: llvm_unreachable("Unknown flavor!");
1712 case 0: // Known false.
1713 return DAG.getConstant(0, VT);
1714 case 1: // Known true.
1715 return DAG.getConstant(1, VT);
1716 case 2: // Undefined.
1717 return DAG.getUNDEF(VT);
1721 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1722 // constant if knowing that the operand is non-nan is enough. We prefer to
1723 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1725 if (Cond == ISD::SETO || Cond == ISD::SETUO)
1726 return DAG.getSetCC(dl, VT, N0, N0, Cond);
1728 // If the condition is not legal, see if we can find an equivalent one
1730 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1731 // If the comparison was an awkward floating-point == or != and one of
1732 // the comparison operands is infinity or negative infinity, convert the
1733 // condition to a less-awkward <= or >=.
1734 if (CFP->getValueAPF().isInfinity()) {
1735 if (CFP->getValueAPF().isNegative()) {
1736 if (Cond == ISD::SETOEQ &&
1737 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1738 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1739 if (Cond == ISD::SETUEQ &&
1740 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1741 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1742 if (Cond == ISD::SETUNE &&
1743 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1744 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1745 if (Cond == ISD::SETONE &&
1746 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1747 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1749 if (Cond == ISD::SETOEQ &&
1750 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1751 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1752 if (Cond == ISD::SETUEQ &&
1753 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1754 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1755 if (Cond == ISD::SETUNE &&
1756 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1757 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1758 if (Cond == ISD::SETONE &&
1759 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1760 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1767 // The sext(setcc()) => setcc() optimization relies on the appropriate
1768 // constant being emitted.
1770 switch (getBooleanContents(N0.getValueType().isVector())) {
1771 case UndefinedBooleanContent:
1772 case ZeroOrOneBooleanContent:
1773 EqVal = ISD::isTrueWhenEqual(Cond);
1775 case ZeroOrNegativeOneBooleanContent:
1776 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1780 // We can always fold X == X for integer setcc's.
1781 if (N0.getValueType().isInteger()) {
1782 return DAG.getConstant(EqVal, VT);
1784 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1785 if (UOF == 2) // FP operators that are undefined on NaNs.
1786 return DAG.getConstant(EqVal, VT);
1787 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1788 return DAG.getConstant(EqVal, VT);
1789 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
1790 // if it is not already.
1791 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1792 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
1793 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
1794 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
1797 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1798 N0.getValueType().isInteger()) {
1799 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1800 N0.getOpcode() == ISD::XOR) {
1801 // Simplify (X+Y) == (X+Z) --> Y == Z
1802 if (N0.getOpcode() == N1.getOpcode()) {
1803 if (N0.getOperand(0) == N1.getOperand(0))
1804 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
1805 if (N0.getOperand(1) == N1.getOperand(1))
1806 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
1807 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1808 // If X op Y == Y op X, try other combinations.
1809 if (N0.getOperand(0) == N1.getOperand(1))
1810 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
1812 if (N0.getOperand(1) == N1.getOperand(0))
1813 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
1818 // If RHS is a legal immediate value for a compare instruction, we need
1819 // to be careful about increasing register pressure needlessly.
1820 bool LegalRHSImm = false;
1822 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1823 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1824 // Turn (X+C1) == C2 --> X == C2-C1
1825 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
1826 return DAG.getSetCC(dl, VT, N0.getOperand(0),
1827 DAG.getConstant(RHSC->getAPIntValue()-
1828 LHSR->getAPIntValue(),
1829 N0.getValueType()), Cond);
1832 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1833 if (N0.getOpcode() == ISD::XOR)
1834 // If we know that all of the inverted bits are zero, don't bother
1835 // performing the inversion.
1836 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1838 DAG.getSetCC(dl, VT, N0.getOperand(0),
1839 DAG.getConstant(LHSR->getAPIntValue() ^
1840 RHSC->getAPIntValue(),
1845 // Turn (C1-X) == C2 --> X == C1-C2
1846 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1847 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
1849 DAG.getSetCC(dl, VT, N0.getOperand(1),
1850 DAG.getConstant(SUBC->getAPIntValue() -
1851 RHSC->getAPIntValue(),
1857 // Could RHSC fold directly into a compare?
1858 if (RHSC->getValueType(0).getSizeInBits() <= 64)
1859 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
1862 // Simplify (X+Z) == X --> Z == 0
1863 // Don't do this if X is an immediate that can fold into a cmp
1864 // instruction and X+Z has other uses. It could be an induction variable
1865 // chain, and the transform would increase register pressure.
1866 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
1867 if (N0.getOperand(0) == N1)
1868 return DAG.getSetCC(dl, VT, N0.getOperand(1),
1869 DAG.getConstant(0, N0.getValueType()), Cond);
1870 if (N0.getOperand(1) == N1) {
1871 if (DAG.isCommutativeBinOp(N0.getOpcode()))
1872 return DAG.getSetCC(dl, VT, N0.getOperand(0),
1873 DAG.getConstant(0, N0.getValueType()), Cond);
1874 if (N0.getNode()->hasOneUse()) {
1875 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1876 // (Z-X) == X --> Z == X<<1
1877 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
1878 DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
1879 if (!DCI.isCalledByLegalizer())
1880 DCI.AddToWorklist(SH.getNode());
1881 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
1887 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1888 N1.getOpcode() == ISD::XOR) {
1889 // Simplify X == (X+Z) --> Z == 0
1890 if (N1.getOperand(0) == N0)
1891 return DAG.getSetCC(dl, VT, N1.getOperand(1),
1892 DAG.getConstant(0, N1.getValueType()), Cond);
1893 if (N1.getOperand(1) == N0) {
1894 if (DAG.isCommutativeBinOp(N1.getOpcode()))
1895 return DAG.getSetCC(dl, VT, N1.getOperand(0),
1896 DAG.getConstant(0, N1.getValueType()), Cond);
1897 if (N1.getNode()->hasOneUse()) {
1898 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1899 // X == (Z-X) --> X<<1 == Z
1900 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
1901 DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
1902 if (!DCI.isCalledByLegalizer())
1903 DCI.AddToWorklist(SH.getNode());
1904 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
1909 // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
1910 // Note that where y is variable and is known to have at most
1911 // one bit set (for example, if it is z&1) we cannot do this;
1912 // the expressions are not equivalent when y==0.
1913 if (N0.getOpcode() == ISD::AND)
1914 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
1915 if (ValueHasExactlyOneBitSet(N1, DAG)) {
1916 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1917 if (DCI.isBeforeLegalizeOps() ||
1918 isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1919 SDValue Zero = DAG.getConstant(0, N1.getValueType());
1920 return DAG.getSetCC(dl, VT, N0, Zero, Cond);
1924 if (N1.getOpcode() == ISD::AND)
1925 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
1926 if (ValueHasExactlyOneBitSet(N0, DAG)) {
1927 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1928 if (DCI.isBeforeLegalizeOps() ||
1929 isCondCodeLegal(Cond, N1.getSimpleValueType())) {
1930 SDValue Zero = DAG.getConstant(0, N0.getValueType());
1931 return DAG.getSetCC(dl, VT, N1, Zero, Cond);
1937 // Fold away ALL boolean setcc's.
1939 if (N0.getValueType() == MVT::i1 && foldBooleans) {
1941 default: llvm_unreachable("Unknown integer setcc!");
1942 case ISD::SETEQ: // X == Y -> ~(X^Y)
1943 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
1944 N0 = DAG.getNOT(dl, Temp, MVT::i1);
1945 if (!DCI.isCalledByLegalizer())
1946 DCI.AddToWorklist(Temp.getNode());
1948 case ISD::SETNE: // X != Y --> (X^Y)
1949 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
1951 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
1952 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
1953 Temp = DAG.getNOT(dl, N0, MVT::i1);
1954 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
1955 if (!DCI.isCalledByLegalizer())
1956 DCI.AddToWorklist(Temp.getNode());
1958 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
1959 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
1960 Temp = DAG.getNOT(dl, N1, MVT::i1);
1961 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
1962 if (!DCI.isCalledByLegalizer())
1963 DCI.AddToWorklist(Temp.getNode());
1965 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
1966 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
1967 Temp = DAG.getNOT(dl, N0, MVT::i1);
1968 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
1969 if (!DCI.isCalledByLegalizer())
1970 DCI.AddToWorklist(Temp.getNode());
1972 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
1973 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
1974 Temp = DAG.getNOT(dl, N1, MVT::i1);
1975 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
1978 if (VT != MVT::i1) {
1979 if (!DCI.isCalledByLegalizer())
1980 DCI.AddToWorklist(N0.getNode());
1981 // FIXME: If running after legalize, we probably can't do this.
1982 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
1987 // Could not fold it.
1991 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
1992 /// node is a GlobalAddress + offset.
1993 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
1994 int64_t &Offset) const {
1995 if (isa<GlobalAddressSDNode>(N)) {
1996 GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
1997 GA = GASD->getGlobal();
1998 Offset += GASD->getOffset();
2002 if (N->getOpcode() == ISD::ADD) {
2003 SDValue N1 = N->getOperand(0);
2004 SDValue N2 = N->getOperand(1);
2005 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2006 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
2008 Offset += V->getSExtValue();
2011 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2012 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
2014 Offset += V->getSExtValue();
2024 SDValue TargetLowering::
2025 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
2026 // Default implementation: no optimization.
2030 //===----------------------------------------------------------------------===//
2031 // Inline Assembler Implementation Methods
2032 //===----------------------------------------------------------------------===//
2035 TargetLowering::ConstraintType
2036 TargetLowering::getConstraintType(const std::string &Constraint) const {
2037 unsigned S = Constraint.size();
2040 switch (Constraint[0]) {
2042 case 'r': return C_RegisterClass;
2044 case 'o': // offsetable
2045 case 'V': // not offsetable
2047 case 'i': // Simple Integer or Relocatable Constant
2048 case 'n': // Simple Integer
2049 case 'E': // Floating Point Constant
2050 case 'F': // Floating Point Constant
2051 case 's': // Relocatable Constant
2052 case 'p': // Address.
2053 case 'X': // Allow ANY value.
2054 case 'I': // Target registers.
2068 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2069 if (S == 8 && !Constraint.compare(1, 6, "memory", 6)) // "{memory}"
2076 /// LowerXConstraint - try to replace an X constraint, which matches anything,
2077 /// with another that has more specific requirements based on the type of the
2078 /// corresponding operand.
2079 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2080 if (ConstraintVT.isInteger())
2082 if (ConstraintVT.isFloatingPoint())
2083 return "f"; // works for many targets
2087 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2088 /// vector. If it is invalid, don't add anything to Ops.
2089 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2090 std::string &Constraint,
2091 std::vector<SDValue> &Ops,
2092 SelectionDAG &DAG) const {
2094 if (Constraint.length() > 1) return;
2096 char ConstraintLetter = Constraint[0];
2097 switch (ConstraintLetter) {
2099 case 'X': // Allows any operand; labels (basic block) use this.
2100 if (Op.getOpcode() == ISD::BasicBlock) {
2105 case 'i': // Simple Integer or Relocatable Constant
2106 case 'n': // Simple Integer
2107 case 's': { // Relocatable Constant
2108 // These operands are interested in values of the form (GV+C), where C may
2109 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2110 // is possible and fine if either GV or C are missing.
2111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2112 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2114 // If we have "(add GV, C)", pull out GV/C
2115 if (Op.getOpcode() == ISD::ADD) {
2116 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2117 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2119 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2120 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2123 C = nullptr, GA = nullptr;
2126 // If we find a valid operand, map to the TargetXXX version so that the
2127 // value itself doesn't get selected.
2128 if (GA) { // Either &GV or &GV+C
2129 if (ConstraintLetter != 'n') {
2130 int64_t Offs = GA->getOffset();
2131 if (C) Offs += C->getZExtValue();
2132 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2133 C ? SDLoc(C) : SDLoc(),
2134 Op.getValueType(), Offs));
2138 if (C) { // just C, no GV.
2139 // Simple constants are not allowed for 's'.
2140 if (ConstraintLetter != 's') {
2141 // gcc prints these as sign extended. Sign extend value to 64 bits
2142 // now; without this it would get ZExt'd later in
2143 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2144 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2154 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
2155 getRegForInlineAsmConstraint(const std::string &Constraint,
2157 if (Constraint.empty() || Constraint[0] != '{')
2158 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2159 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2161 // Remove the braces from around the name.
2162 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2164 std::pair<unsigned, const TargetRegisterClass*> R =
2165 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2167 // Figure out which register class contains this reg.
2168 const TargetRegisterInfo *RI = getTargetMachine().getRegisterInfo();
2169 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2170 E = RI->regclass_end(); RCI != E; ++RCI) {
2171 const TargetRegisterClass *RC = *RCI;
2173 // If none of the value types for this register class are valid, we
2174 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2178 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2180 if (RegName.equals_lower(RI->getName(*I))) {
2181 std::pair<unsigned, const TargetRegisterClass*> S =
2182 std::make_pair(*I, RC);
2184 // If this register class has the requested value type, return it,
2185 // otherwise keep searching and return the first class found
2186 // if no other is found which explicitly has the requested type.
2187 if (RC->hasType(VT))
2198 //===----------------------------------------------------------------------===//
2199 // Constraint Selection.
2201 /// isMatchingInputConstraint - Return true of this is an input operand that is
2202 /// a matching constraint like "4".
2203 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2204 assert(!ConstraintCode.empty() && "No known constraint!");
2205 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2208 /// getMatchedOperand - If this is an input matching constraint, this method
2209 /// returns the output operand it matches.
2210 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2211 assert(!ConstraintCode.empty() && "No known constraint!");
2212 return atoi(ConstraintCode.c_str());
2216 /// ParseConstraints - Split up the constraint string from the inline
2217 /// assembly value into the specific constraints and their prefixes,
2218 /// and also tie in the associated operand values.
2219 /// If this returns an empty vector, and if the constraint string itself
2220 /// isn't empty, there was an error parsing.
2221 TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints(
2222 ImmutableCallSite CS) const {
2223 /// ConstraintOperands - Information about all of the constraints.
2224 AsmOperandInfoVector ConstraintOperands;
2225 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2226 unsigned maCount = 0; // Largest number of multiple alternative constraints.
2228 // Do a prepass over the constraints, canonicalizing them, and building up the
2229 // ConstraintOperands list.
2230 InlineAsm::ConstraintInfoVector
2231 ConstraintInfos = IA->ParseConstraints();
2233 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2234 unsigned ResNo = 0; // ResNo - The result number of the next output.
2236 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
2237 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
2238 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2240 // Update multiple alternative constraint count.
2241 if (OpInfo.multipleAlternatives.size() > maCount)
2242 maCount = OpInfo.multipleAlternatives.size();
2244 OpInfo.ConstraintVT = MVT::Other;
2246 // Compute the value type for each operand.
2247 switch (OpInfo.Type) {
2248 case InlineAsm::isOutput:
2249 // Indirect outputs just consume an argument.
2250 if (OpInfo.isIndirect) {
2251 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2255 // The return value of the call is this value. As such, there is no
2256 // corresponding argument.
2257 assert(!CS.getType()->isVoidTy() &&
2259 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2260 OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
2262 assert(ResNo == 0 && "Asm only has one result!");
2263 OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
2267 case InlineAsm::isInput:
2268 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2270 case InlineAsm::isClobber:
2275 if (OpInfo.CallOperandVal) {
2276 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2277 if (OpInfo.isIndirect) {
2278 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2280 report_fatal_error("Indirect operand for inline asm not a pointer!");
2281 OpTy = PtrTy->getElementType();
2284 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2285 if (StructType *STy = dyn_cast<StructType>(OpTy))
2286 if (STy->getNumElements() == 1)
2287 OpTy = STy->getElementType(0);
2289 // If OpTy is not a single value, it may be a struct/union that we
2290 // can tile with integers.
2291 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2292 unsigned BitSize = getDataLayout()->getTypeSizeInBits(OpTy);
2301 OpInfo.ConstraintVT =
2302 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2305 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2307 = getDataLayout()->getPointerSizeInBits(PT->getAddressSpace());
2308 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2310 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2315 // If we have multiple alternative constraints, select the best alternative.
2316 if (ConstraintInfos.size()) {
2318 unsigned bestMAIndex = 0;
2319 int bestWeight = -1;
2320 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2323 // Compute the sums of the weights for each alternative, keeping track
2324 // of the best (highest weight) one so far.
2325 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2327 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2328 cIndex != eIndex; ++cIndex) {
2329 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2330 if (OpInfo.Type == InlineAsm::isClobber)
2333 // If this is an output operand with a matching input operand,
2334 // look up the matching input. If their types mismatch, e.g. one
2335 // is an integer, the other is floating point, or their sizes are
2336 // different, flag it as an maCantMatch.
2337 if (OpInfo.hasMatchingInput()) {
2338 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2339 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2340 if ((OpInfo.ConstraintVT.isInteger() !=
2341 Input.ConstraintVT.isInteger()) ||
2342 (OpInfo.ConstraintVT.getSizeInBits() !=
2343 Input.ConstraintVT.getSizeInBits())) {
2344 weightSum = -1; // Can't match.
2349 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2354 weightSum += weight;
2357 if (weightSum > bestWeight) {
2358 bestWeight = weightSum;
2359 bestMAIndex = maIndex;
2363 // Now select chosen alternative in each constraint.
2364 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2365 cIndex != eIndex; ++cIndex) {
2366 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2367 if (cInfo.Type == InlineAsm::isClobber)
2369 cInfo.selectAlternative(bestMAIndex);
2374 // Check and hook up tied operands, choose constraint code to use.
2375 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2376 cIndex != eIndex; ++cIndex) {
2377 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2379 // If this is an output operand with a matching input operand, look up the
2380 // matching input. If their types mismatch, e.g. one is an integer, the
2381 // other is floating point, or their sizes are different, flag it as an
2383 if (OpInfo.hasMatchingInput()) {
2384 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2386 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2387 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
2388 getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
2389 OpInfo.ConstraintVT);
2390 std::pair<unsigned, const TargetRegisterClass*> InputRC =
2391 getRegForInlineAsmConstraint(Input.ConstraintCode,
2392 Input.ConstraintVT);
2393 if ((OpInfo.ConstraintVT.isInteger() !=
2394 Input.ConstraintVT.isInteger()) ||
2395 (MatchRC.second != InputRC.second)) {
2396 report_fatal_error("Unsupported asm: input constraint"
2397 " with a matching output constraint of"
2398 " incompatible type!");
2405 return ConstraintOperands;
2409 /// getConstraintGenerality - Return an integer indicating how general CT
2411 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2413 case TargetLowering::C_Other:
2414 case TargetLowering::C_Unknown:
2416 case TargetLowering::C_Register:
2418 case TargetLowering::C_RegisterClass:
2420 case TargetLowering::C_Memory:
2423 llvm_unreachable("Invalid constraint type");
2426 /// Examine constraint type and operand type and determine a weight value.
2427 /// This object must already have been set up with the operand type
2428 /// and the current alternative constraint selected.
2429 TargetLowering::ConstraintWeight
2430 TargetLowering::getMultipleConstraintMatchWeight(
2431 AsmOperandInfo &info, int maIndex) const {
2432 InlineAsm::ConstraintCodeVector *rCodes;
2433 if (maIndex >= (int)info.multipleAlternatives.size())
2434 rCodes = &info.Codes;
2436 rCodes = &info.multipleAlternatives[maIndex].Codes;
2437 ConstraintWeight BestWeight = CW_Invalid;
2439 // Loop over the options, keeping track of the most general one.
2440 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2441 ConstraintWeight weight =
2442 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2443 if (weight > BestWeight)
2444 BestWeight = weight;
2450 /// Examine constraint type and operand type and determine a weight value.
2451 /// This object must already have been set up with the operand type
2452 /// and the current alternative constraint selected.
2453 TargetLowering::ConstraintWeight
2454 TargetLowering::getSingleConstraintMatchWeight(
2455 AsmOperandInfo &info, const char *constraint) const {
2456 ConstraintWeight weight = CW_Invalid;
2457 Value *CallOperandVal = info.CallOperandVal;
2458 // If we don't have a value, we can't do a match,
2459 // but allow it at the lowest weight.
2460 if (!CallOperandVal)
2462 // Look at the constraint type.
2463 switch (*constraint) {
2464 case 'i': // immediate integer.
2465 case 'n': // immediate integer with a known value.
2466 if (isa<ConstantInt>(CallOperandVal))
2467 weight = CW_Constant;
2469 case 's': // non-explicit intregal immediate.
2470 if (isa<GlobalValue>(CallOperandVal))
2471 weight = CW_Constant;
2473 case 'E': // immediate float if host format.
2474 case 'F': // immediate float.
2475 if (isa<ConstantFP>(CallOperandVal))
2476 weight = CW_Constant;
2478 case '<': // memory operand with autodecrement.
2479 case '>': // memory operand with autoincrement.
2480 case 'm': // memory operand.
2481 case 'o': // offsettable memory operand
2482 case 'V': // non-offsettable memory operand
2485 case 'r': // general register.
2486 case 'g': // general register, memory operand or immediate integer.
2487 // note: Clang converts "g" to "imr".
2488 if (CallOperandVal->getType()->isIntegerTy())
2489 weight = CW_Register;
2491 case 'X': // any operand.
2493 weight = CW_Default;
2499 /// ChooseConstraint - If there are multiple different constraints that we
2500 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
2501 /// This is somewhat tricky: constraints fall into four classes:
2502 /// Other -> immediates and magic values
2503 /// Register -> one specific register
2504 /// RegisterClass -> a group of regs
2505 /// Memory -> memory
2506 /// Ideally, we would pick the most specific constraint possible: if we have
2507 /// something that fits into a register, we would pick it. The problem here
2508 /// is that if we have something that could either be in a register or in
2509 /// memory that use of the register could cause selection of *other*
2510 /// operands to fail: they might only succeed if we pick memory. Because of
2511 /// this the heuristic we use is:
2513 /// 1) If there is an 'other' constraint, and if the operand is valid for
2514 /// that constraint, use it. This makes us take advantage of 'i'
2515 /// constraints when available.
2516 /// 2) Otherwise, pick the most general constraint present. This prefers
2517 /// 'm' over 'r', for example.
2519 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2520 const TargetLowering &TLI,
2521 SDValue Op, SelectionDAG *DAG) {
2522 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2523 unsigned BestIdx = 0;
2524 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2525 int BestGenerality = -1;
2527 // Loop over the options, keeping track of the most general one.
2528 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2529 TargetLowering::ConstraintType CType =
2530 TLI.getConstraintType(OpInfo.Codes[i]);
2532 // If this is an 'other' constraint, see if the operand is valid for it.
2533 // For example, on X86 we might have an 'rI' constraint. If the operand
2534 // is an integer in the range [0..31] we want to use I (saving a load
2535 // of a register), otherwise we must use 'r'.
2536 if (CType == TargetLowering::C_Other && Op.getNode()) {
2537 assert(OpInfo.Codes[i].size() == 1 &&
2538 "Unhandled multi-letter 'other' constraint");
2539 std::vector<SDValue> ResultOps;
2540 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2542 if (!ResultOps.empty()) {
2549 // Things with matching constraints can only be registers, per gcc
2550 // documentation. This mainly affects "g" constraints.
2551 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2554 // This constraint letter is more general than the previous one, use it.
2555 int Generality = getConstraintGenerality(CType);
2556 if (Generality > BestGenerality) {
2559 BestGenerality = Generality;
2563 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2564 OpInfo.ConstraintType = BestType;
2567 /// ComputeConstraintToUse - Determines the constraint code and constraint
2568 /// type to use for the specific AsmOperandInfo, setting
2569 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
2570 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2572 SelectionDAG *DAG) const {
2573 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2575 // Single-letter constraints ('r') are very common.
2576 if (OpInfo.Codes.size() == 1) {
2577 OpInfo.ConstraintCode = OpInfo.Codes[0];
2578 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2580 ChooseConstraint(OpInfo, *this, Op, DAG);
2583 // 'X' matches anything.
2584 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2585 // Labels and constants are handled elsewhere ('X' is the only thing
2586 // that matches labels). For Functions, the type here is the type of
2587 // the result, which is not what we want to look at; leave them alone.
2588 Value *v = OpInfo.CallOperandVal;
2589 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2590 OpInfo.CallOperandVal = v;
2594 // Otherwise, try to resolve it to something we know about by looking at
2595 // the actual operand type.
2596 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2597 OpInfo.ConstraintCode = Repl;
2598 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2603 /// \brief Given an exact SDIV by a constant, create a multiplication
2604 /// with the multiplicative inverse of the constant.
2605 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2606 SelectionDAG &DAG) const {
2607 ConstantSDNode *C = cast<ConstantSDNode>(Op2);
2608 APInt d = C->getAPIntValue();
2609 assert(d != 0 && "Division by zero!");
2611 // Shift the value upfront if it is even, so the LSB is one.
2612 unsigned ShAmt = d.countTrailingZeros();
2614 // TODO: For UDIV use SRL instead of SRA.
2615 SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
2616 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt);
2620 // Calculate the multiplicative inverse, using Newton's method.
2622 while ((t = d*xn) != 1)
2623 xn *= APInt(d.getBitWidth(), 2) - t;
2625 Op2 = DAG.getConstant(xn, Op1.getValueType());
2626 return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2629 /// \brief Given an ISD::SDIV node expressing a divide by constant,
2630 /// return a DAG expression to select that will generate the same value by
2631 /// multiplying by a magic number. See:
2632 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2633 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2634 SelectionDAG &DAG, bool IsAfterLegalization,
2635 std::vector<SDNode *> *Created) const {
2636 EVT VT = N->getValueType(0);
2639 // Check to see if we can do this.
2640 // FIXME: We should be more aggressive here.
2641 if (!isTypeLegal(VT))
2644 APInt::ms magics = Divisor.magic();
2646 // Multiply the numerator (operand 0) by the magic value
2647 // FIXME: We should support doing a MUL in a wider type
2649 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2650 isOperationLegalOrCustom(ISD::MULHS, VT))
2651 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2652 DAG.getConstant(magics.m, VT));
2653 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2654 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2655 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2657 DAG.getConstant(magics.m, VT)).getNode(), 1);
2659 return SDValue(); // No mulhs or equvialent
2660 // If d > 0 and m < 0, add the numerator
2661 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
2662 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2664 Created->push_back(Q.getNode());
2666 // If d < 0 and m > 0, subtract the numerator.
2667 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
2668 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2670 Created->push_back(Q.getNode());
2672 // Shift right algebraic if shift value is nonzero
2674 Q = DAG.getNode(ISD::SRA, dl, VT, Q,
2675 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
2677 Created->push_back(Q.getNode());
2679 // Extract the sign bit and add it to the quotient
2680 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q,
2681 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2682 getShiftAmountTy(Q.getValueType())));
2684 Created->push_back(T.getNode());
2685 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2688 /// \brief Given an ISD::UDIV node expressing a divide by constant,
2689 /// return a DAG expression to select that will generate the same value by
2690 /// multiplying by a magic number. See:
2691 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2692 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2693 SelectionDAG &DAG, bool IsAfterLegalization,
2694 std::vector<SDNode *> *Created) const {
2695 EVT VT = N->getValueType(0);
2698 // Check to see if we can do this.
2699 // FIXME: We should be more aggressive here.
2700 if (!isTypeLegal(VT))
2703 // FIXME: We should use a narrower constant when the upper
2704 // bits are known to be zero.
2705 APInt::mu magics = Divisor.magicu();
2707 SDValue Q = N->getOperand(0);
2709 // If the divisor is even, we can avoid using the expensive fixup by shifting
2710 // the divided value upfront.
2711 if (magics.a != 0 && !Divisor[0]) {
2712 unsigned Shift = Divisor.countTrailingZeros();
2713 Q = DAG.getNode(ISD::SRL, dl, VT, Q,
2714 DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
2716 Created->push_back(Q.getNode());
2718 // Get magic number for the shifted divisor.
2719 magics = Divisor.lshr(Shift).magicu(Shift);
2720 assert(magics.a == 0 && "Should use cheap fixup now");
2723 // Multiply the numerator (operand 0) by the magic value
2724 // FIXME: We should support doing a MUL in a wider type
2725 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2726 isOperationLegalOrCustom(ISD::MULHU, VT))
2727 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
2728 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2729 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2730 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
2731 DAG.getConstant(magics.m, VT)).getNode(), 1);
2733 return SDValue(); // No mulhu or equvialent
2735 Created->push_back(Q.getNode());
2737 if (magics.a == 0) {
2738 assert(magics.s < Divisor.getBitWidth() &&
2739 "We shouldn't generate an undefined shift!");
2740 return DAG.getNode(ISD::SRL, dl, VT, Q,
2741 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
2743 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2745 Created->push_back(NPQ.getNode());
2746 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
2747 DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
2749 Created->push_back(NPQ.getNode());
2750 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2752 Created->push_back(NPQ.getNode());
2753 return DAG.getNode(ISD::SRL, dl, VT, NPQ,
2754 DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));
2758 bool TargetLowering::
2759 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
2760 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
2761 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
2762 "be a constant integer");
2769 //===----------------------------------------------------------------------===//
2770 // Legalization Utilities
2771 //===----------------------------------------------------------------------===//
2773 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
2774 SelectionDAG &DAG, SDValue LL, SDValue LH,
2775 SDValue RL, SDValue RH) const {
2776 EVT VT = N->getValueType(0);
2779 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
2780 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
2781 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
2782 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
2783 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
2784 unsigned OuterBitSize = VT.getSizeInBits();
2785 unsigned InnerBitSize = HiLoVT.getSizeInBits();
2786 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
2787 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
2789 // LL, LH, RL, and RH must be either all NULL or all set to a value.
2790 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
2791 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
2793 if (!LL.getNode() && !RL.getNode() &&
2794 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
2795 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
2796 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
2802 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
2803 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
2804 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
2805 // The inputs are both zero-extended.
2807 // We can emit a umul_lohi.
2808 Lo = DAG.getNode(ISD::UMUL_LOHI, dl,
2809 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
2810 Hi = SDValue(Lo.getNode(), 1);
2814 // We can emit a mulhu+mul.
2815 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2816 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
2820 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
2821 // The input values are both sign-extended.
2823 // We can emit a smul_lohi.
2824 Lo = DAG.getNode(ISD::SMUL_LOHI, dl,
2825 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
2826 Hi = SDValue(Lo.getNode(), 1);
2830 // We can emit a mulhs+mul.
2831 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2832 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
2837 if (!LH.getNode() && !RH.getNode() &&
2838 isOperationLegalOrCustom(ISD::SRL, VT) &&
2839 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
2840 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
2841 SDValue Shift = DAG.getConstant(ShiftAmt, getShiftAmountTy(VT));
2842 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
2843 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
2844 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
2845 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
2852 // Lo,Hi = umul LHS, RHS.
2853 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
2854 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
2856 Hi = UMulLOHI.getValue(1);
2857 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
2858 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
2859 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
2860 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
2864 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2865 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
2866 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
2867 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
2868 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
2869 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);