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/CallingConvLower.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.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"
34 #include "llvm/Target/TargetSubtargetInfo.h"
38 /// NOTE: The TargetMachine owns TLOF.
39 TargetLowering::TargetLowering(const TargetMachine &tm)
40 : TargetLoweringBase(tm) {}
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
46 bool TargetLowering::isPositionIndependent() const {
47 return getTargetMachine().isPositionIndependent();
50 /// Check whether a given call node is in tail position within its function. If
51 /// so, it sets Chain to the input chain of the tail call.
52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
53 SDValue &Chain) const {
54 const Function *F = DAG.getMachineFunction().getFunction();
56 // Conservatively require the attributes of the call to match those of
57 // the return. Ignore noalias because it doesn't affect the call sequence.
58 AttributeList CallerAttrs = F->getAttributes();
59 if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
60 .removeAttribute(Attribute::NoAlias)
64 // It's not safe to eliminate the sign / zero extension of the return value.
65 if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
66 CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
69 // Check if the only use is a function return node.
70 return isUsedByReturnOnly(Node, Chain);
73 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
74 const uint32_t *CallerPreservedMask,
75 const SmallVectorImpl<CCValAssign> &ArgLocs,
76 const SmallVectorImpl<SDValue> &OutVals) const {
77 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
78 const CCValAssign &ArgLoc = ArgLocs[I];
79 if (!ArgLoc.isRegLoc())
81 unsigned Reg = ArgLoc.getLocReg();
82 // Only look at callee saved registers.
83 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
85 // Check that we pass the value used for the caller.
86 // (We look for a CopyFromReg reading a virtual register that is used
87 // for the function live-in value of register Reg)
88 SDValue Value = OutVals[I];
89 if (Value->getOpcode() != ISD::CopyFromReg)
91 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
92 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
98 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
99 /// and called function attributes.
100 void TargetLoweringBase::ArgListEntry::setAttributes(ImmutableCallSite *CS,
102 IsSExt = CS->paramHasAttr(ArgIdx, Attribute::SExt);
103 IsZExt = CS->paramHasAttr(ArgIdx, Attribute::ZExt);
104 IsInReg = CS->paramHasAttr(ArgIdx, Attribute::InReg);
105 IsSRet = CS->paramHasAttr(ArgIdx, Attribute::StructRet);
106 IsNest = CS->paramHasAttr(ArgIdx, Attribute::Nest);
107 IsByVal = CS->paramHasAttr(ArgIdx, Attribute::ByVal);
108 IsInAlloca = CS->paramHasAttr(ArgIdx, Attribute::InAlloca);
109 IsReturned = CS->paramHasAttr(ArgIdx, Attribute::Returned);
110 IsSwiftSelf = CS->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
111 IsSwiftError = CS->paramHasAttr(ArgIdx, Attribute::SwiftError);
112 // FIXME: getParamAlignment is off by one from argument index.
113 Alignment = CS->getParamAlignment(ArgIdx + 1);
116 /// Generate a libcall taking the given operands as arguments and returning a
117 /// result of type RetVT.
118 std::pair<SDValue, SDValue>
119 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
120 ArrayRef<SDValue> Ops, bool isSigned,
121 const SDLoc &dl, bool doesNotReturn,
122 bool isReturnValueUsed) const {
123 TargetLowering::ArgListTy Args;
124 Args.reserve(Ops.size());
126 TargetLowering::ArgListEntry Entry;
127 for (SDValue Op : Ops) {
129 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
130 Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
131 Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
132 Args.push_back(Entry);
135 if (LC == RTLIB::UNKNOWN_LIBCALL)
136 report_fatal_error("Unsupported library call operation!");
137 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
138 getPointerTy(DAG.getDataLayout()));
140 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
141 TargetLowering::CallLoweringInfo CLI(DAG);
142 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
144 .setChain(DAG.getEntryNode())
145 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
146 .setNoReturn(doesNotReturn)
147 .setDiscardResult(!isReturnValueUsed)
148 .setSExtResult(signExtend)
149 .setZExtResult(!signExtend);
150 return LowerCallTo(CLI);
153 /// Soften the operands of a comparison. This code is shared among BR_CC,
154 /// SELECT_CC, and SETCC handlers.
155 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
156 SDValue &NewLHS, SDValue &NewRHS,
157 ISD::CondCode &CCCode,
158 const SDLoc &dl) const {
159 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
160 && "Unsupported setcc type!");
162 // Expand into one or more soft-fp libcall(s).
163 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
164 bool ShouldInvertCC = false;
168 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
169 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
170 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
174 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
175 (VT == MVT::f64) ? RTLIB::UNE_F64 :
176 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
180 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
181 (VT == MVT::f64) ? RTLIB::OGE_F64 :
182 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
186 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
187 (VT == MVT::f64) ? RTLIB::OLT_F64 :
188 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
192 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
193 (VT == MVT::f64) ? RTLIB::OLE_F64 :
194 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
198 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
199 (VT == MVT::f64) ? RTLIB::OGT_F64 :
200 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
203 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
204 (VT == MVT::f64) ? RTLIB::UO_F64 :
205 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
208 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
209 (VT == MVT::f64) ? RTLIB::O_F64 :
210 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
213 // SETONE = SETOLT | SETOGT
214 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
215 (VT == MVT::f64) ? RTLIB::OLT_F64 :
216 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
217 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
218 (VT == MVT::f64) ? RTLIB::OGT_F64 :
219 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
222 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
223 (VT == MVT::f64) ? RTLIB::UO_F64 :
224 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
225 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
226 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
227 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
230 // Invert CC for unordered comparisons
231 ShouldInvertCC = true;
234 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
235 (VT == MVT::f64) ? RTLIB::OGE_F64 :
236 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
239 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
240 (VT == MVT::f64) ? RTLIB::OGT_F64 :
241 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
244 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
245 (VT == MVT::f64) ? RTLIB::OLE_F64 :
246 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
249 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
250 (VT == MVT::f64) ? RTLIB::OLT_F64 :
251 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
253 default: llvm_unreachable("Do not know how to soften this setcc!");
257 // Use the target specific return value for comparions lib calls.
258 EVT RetVT = getCmpLibcallReturnType();
259 SDValue Ops[2] = {NewLHS, NewRHS};
260 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
262 NewRHS = DAG.getConstant(0, dl, RetVT);
264 CCCode = getCmpLibcallCC(LC1);
266 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
268 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
269 SDValue Tmp = DAG.getNode(
271 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
272 NewLHS, NewRHS, DAG.getCondCode(CCCode));
273 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
275 NewLHS = DAG.getNode(
277 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
278 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
279 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
284 /// Return the entry encoding for a jump table in the current function. The
285 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
286 unsigned TargetLowering::getJumpTableEncoding() const {
287 // In non-pic modes, just use the address of a block.
288 if (!isPositionIndependent())
289 return MachineJumpTableInfo::EK_BlockAddress;
291 // In PIC mode, if the target supports a GPRel32 directive, use it.
292 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
293 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
295 // Otherwise, use a label difference.
296 return MachineJumpTableInfo::EK_LabelDifference32;
299 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
300 SelectionDAG &DAG) const {
301 // If our PIC model is GP relative, use the global offset table as the base.
302 unsigned JTEncoding = getJumpTableEncoding();
304 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
305 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
306 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
311 /// This returns the relocation base for the given PIC jumptable, the same as
312 /// getPICJumpTableRelocBase, but as an MCExpr.
314 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
315 unsigned JTI,MCContext &Ctx) const{
316 // The normal PIC reloc base is the label at the start of the jump table.
317 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
321 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
322 const TargetMachine &TM = getTargetMachine();
323 const GlobalValue *GV = GA->getGlobal();
325 // If the address is not even local to this DSO we will have to load it from
326 // a got and then add the offset.
327 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
330 // If the code is position independent we will have to add a base register.
331 if (isPositionIndependent())
334 // Otherwise we can do it.
338 //===----------------------------------------------------------------------===//
339 // Optimization Methods
340 //===----------------------------------------------------------------------===//
342 /// If the specified instruction has a constant integer operand and there are
343 /// bits set in that constant that are not demanded, then clear those bits and
345 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(
346 SDValue Op, const APInt &Demanded) {
348 unsigned Opcode = Op.getOpcode();
350 // FIXME: ISD::SELECT, ISD::SELECT_CC
357 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
361 // If this is a 'not' op, don't touch it because that's a canonical form.
362 const APInt &C = Op1C->getAPIntValue();
363 if (Opcode == ISD::XOR && (C | ~Demanded).isAllOnesValue())
366 if (C.intersects(~Demanded)) {
367 EVT VT = Op.getValueType();
368 SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
369 SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
370 return CombineTo(Op, NewOp);
380 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
381 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
382 /// generalized for targets with other types of implicit widening casts.
383 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
385 const APInt &Demanded,
387 assert(Op.getNumOperands() == 2 &&
388 "ShrinkDemandedOp only supports binary operators!");
389 assert(Op.getNode()->getNumValues() == 1 &&
390 "ShrinkDemandedOp only supports nodes with one result!");
392 // Early return, as this function cannot handle vector types.
393 if (Op.getValueType().isVector())
396 // Don't do this if the node has another user, which may require the
398 if (!Op.getNode()->hasOneUse())
401 // Search for the smallest integer type with free casts to and from
402 // Op's type. For expedience, just check power-of-2 integer types.
403 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
404 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
405 unsigned SmallVTBits = DemandedSize;
406 if (!isPowerOf2_32(SmallVTBits))
407 SmallVTBits = NextPowerOf2(SmallVTBits);
408 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
409 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
410 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
411 TLI.isZExtFree(SmallVT, Op.getValueType())) {
412 // We found a type with free casts.
413 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
414 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
415 Op.getNode()->getOperand(0)),
416 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
417 Op.getNode()->getOperand(1)));
418 bool NeedZext = DemandedSize > SmallVTBits;
419 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
420 dl, Op.getValueType(), X);
421 return CombineTo(Op, Z);
428 TargetLowering::TargetLoweringOpt::SimplifyDemandedBits(SDNode *User,
430 const APInt &Demanded,
431 DAGCombinerInfo &DCI) {
432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
433 SDValue Op = User->getOperand(OpIdx);
434 APInt KnownZero, KnownOne;
436 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne,
441 // Old will not always be the same as Op. For example:
443 // Demanded = 0xffffff
444 // Op = i64 truncate (i32 and x, 0xffffff)
445 // In this case simplify demand bits will want to replace the 'and' node
446 // with the value 'x', which will give us:
447 // Old = i32 and x, 0xffffff
449 if (Old.hasOneUse()) {
450 // For the one use case, we just commit the change.
451 DCI.CommitTargetLoweringOpt(*this);
455 // If Old has more than one use then it must be Op, because the
456 // AssumeSingleUse flag is not propogated to recursive calls of
457 // SimplifyDemanded bits, so the only node with multiple use that
458 // it will attempt to combine will be opt.
461 SmallVector <SDValue, 4> NewOps;
462 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
464 NewOps.push_back(New);
467 NewOps.push_back(User->getOperand(i));
469 DAG.UpdateNodeOperands(User, NewOps);
470 // Op has less users now, so we may be able to perform additional combines
472 DCI.AddToWorklist(Op.getNode());
473 // User's operands have been updated, so we may be able to do new combines
475 DCI.AddToWorklist(User);
479 bool TargetLowering::SimplifyDemandedBits(SDValue Op, APInt &DemandedMask,
480 DAGCombinerInfo &DCI) const {
482 SelectionDAG &DAG = DCI.DAG;
483 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
484 !DCI.isBeforeLegalizeOps());
485 APInt KnownZero, KnownOne;
487 bool Simplified = SimplifyDemandedBits(Op, DemandedMask, KnownZero, KnownOne,
490 DCI.CommitTargetLoweringOpt(TLO);
494 /// Look at Op. At this point, we know that only the DemandedMask bits of the
495 /// result of Op are ever used downstream. If we can use this information to
496 /// simplify Op, create a new simplified DAG node and return true, returning the
497 /// original and new nodes in Old and New. Otherwise, analyze the expression and
498 /// return a mask of KnownOne and KnownZero bits for the expression (used to
499 /// simplify the caller). The KnownZero/One bits may only be accurate for those
500 /// bits in the DemandedMask.
501 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
502 const APInt &DemandedMask,
505 TargetLoweringOpt &TLO,
507 bool AssumeSingleUse) const {
508 unsigned BitWidth = DemandedMask.getBitWidth();
509 assert(Op.getScalarValueSizeInBits() == BitWidth &&
510 "Mask size mismatches value type size!");
511 APInt NewMask = DemandedMask;
513 auto &DL = TLO.DAG.getDataLayout();
515 // Don't know anything.
516 KnownZero = KnownOne = APInt(BitWidth, 0);
518 // Other users may use these bits.
519 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
521 // If not at the root, Just compute the KnownZero/KnownOne bits to
522 // simplify things downstream.
523 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
526 // If this is the root being simplified, allow it to have multiple uses,
527 // just set the NewMask to all bits.
528 NewMask = APInt::getAllOnesValue(BitWidth);
529 } else if (DemandedMask == 0) {
530 // Not demanding any bits from Op.
532 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
534 } else if (Depth == 6) { // Limit search depth.
538 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
539 switch (Op.getOpcode()) {
541 // We know all of the bits for a constant!
542 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
543 KnownZero = ~KnownOne;
544 return false; // Don't fall through, will infinitely loop.
545 case ISD::BUILD_VECTOR:
546 // Collect the known bits that are shared by every constant vector element.
547 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
548 for (SDValue SrcOp : Op->ops()) {
549 if (!isa<ConstantSDNode>(SrcOp)) {
550 // We can only handle all constant values - bail out with no known bits.
551 KnownZero = KnownOne = APInt(BitWidth, 0);
554 KnownOne2 = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
555 KnownZero2 = ~KnownOne2;
557 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
558 if (KnownOne2.getBitWidth() != BitWidth) {
559 assert(KnownOne2.getBitWidth() > BitWidth &&
560 KnownZero2.getBitWidth() > BitWidth &&
561 "Expected BUILD_VECTOR implicit truncation");
562 KnownOne2 = KnownOne2.trunc(BitWidth);
563 KnownZero2 = KnownZero2.trunc(BitWidth);
566 // Known bits are the values that are shared by every element.
567 // TODO: support per-element known bits.
568 KnownOne &= KnownOne2;
569 KnownZero &= KnownZero2;
571 return false; // Don't fall through, will infinitely loop.
573 // If the RHS is a constant, check to see if the LHS would be zero without
574 // using the bits from the RHS. Below, we use knowledge about the RHS to
575 // simplify the LHS, here we're using information from the LHS to simplify
577 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op.getOperand(1))) {
578 SDValue Op0 = Op.getOperand(0);
579 APInt LHSZero, LHSOne;
580 // Do not increment Depth here; that can cause an infinite loop.
581 TLO.DAG.computeKnownBits(Op0, LHSZero, LHSOne, Depth);
582 // If the LHS already has zeros where RHSC does, this and is dead.
583 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
584 return TLO.CombineTo(Op, Op0);
586 // If any of the set bits in the RHS are known zero on the LHS, shrink
588 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
591 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
592 // constant, but if this 'and' is only clearing bits that were just set by
593 // the xor, then this 'and' can be eliminated by shrinking the mask of
594 // the xor. For example, for a 32-bit X:
595 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
596 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
597 LHSOne == ~RHSC->getAPIntValue()) {
598 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, Op.getValueType(),
599 Op0.getOperand(0), Op.getOperand(1));
600 return TLO.CombineTo(Op, Xor);
604 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
605 KnownOne, TLO, Depth+1))
607 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
608 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
609 KnownZero2, KnownOne2, TLO, Depth+1))
611 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
613 // If all of the demanded bits are known one on one side, return the other.
614 // These bits cannot contribute to the result of the 'and'.
615 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
616 return TLO.CombineTo(Op, Op.getOperand(0));
617 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
618 return TLO.CombineTo(Op, Op.getOperand(1));
619 // If all of the demanded bits in the inputs are known zeros, return zero.
620 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
621 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
622 // If the RHS is a constant, see if we can simplify it.
623 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
625 // If the operation can be done in a smaller type, do so.
626 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
629 // Output known-1 bits are only known if set in both the LHS & RHS.
630 KnownOne &= KnownOne2;
631 // Output known-0 are known to be clear if zero in either the LHS | RHS.
632 KnownZero |= KnownZero2;
635 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
636 KnownOne, TLO, Depth+1))
638 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
639 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
640 KnownZero2, KnownOne2, TLO, Depth+1))
642 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
644 // If all of the demanded bits are known zero on one side, return the other.
645 // These bits cannot contribute to the result of the 'or'.
646 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
647 return TLO.CombineTo(Op, Op.getOperand(0));
648 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
649 return TLO.CombineTo(Op, Op.getOperand(1));
650 // If all of the potentially set bits on one side are known to be set on
651 // the other side, just use the 'other' side.
652 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
653 return TLO.CombineTo(Op, Op.getOperand(0));
654 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
655 return TLO.CombineTo(Op, Op.getOperand(1));
656 // If the RHS is a constant, see if we can simplify it.
657 if (TLO.ShrinkDemandedConstant(Op, NewMask))
659 // If the operation can be done in a smaller type, do so.
660 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
663 // Output known-0 bits are only known if clear in both the LHS & RHS.
664 KnownZero &= KnownZero2;
665 // Output known-1 are known to be set if set in either the LHS | RHS.
666 KnownOne |= KnownOne2;
669 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
670 KnownOne, TLO, Depth+1))
672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
673 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
674 KnownOne2, TLO, Depth+1))
676 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
678 // If all of the demanded bits are known zero on one side, return the other.
679 // These bits cannot contribute to the result of the 'xor'.
680 if ((KnownZero & NewMask) == NewMask)
681 return TLO.CombineTo(Op, Op.getOperand(0));
682 if ((KnownZero2 & NewMask) == NewMask)
683 return TLO.CombineTo(Op, Op.getOperand(1));
684 // If the operation can be done in a smaller type, do so.
685 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
688 // If all of the unknown bits are known to be zero on one side or the other
689 // (but not both) turn this into an *inclusive* or.
690 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
691 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
692 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
696 // Output known-0 bits are known if clear or set in both the LHS & RHS.
697 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
698 // Output known-1 are known to be set if set in only one of the LHS, RHS.
699 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
701 // If all of the demanded bits on one side are known, and all of the set
702 // bits on that side are also known to be set on the other side, turn this
703 // into an AND, as we know the bits will be cleared.
704 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
705 // NB: it is okay if more bits are known than are requested
706 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
707 if (KnownOne == KnownOne2) { // set bits are the same on both sides
708 EVT VT = Op.getValueType();
709 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
710 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
711 Op.getOperand(0), ANDC));
715 // If the RHS is a constant, see if we can simplify it.
716 // for XOR, we prefer to force bits to 1 if they will make a -1.
717 // If we can't force bits, try to shrink the constant.
718 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
719 APInt Expanded = C->getAPIntValue() | (~NewMask);
720 // If we can expand it to have all bits set, do it.
721 if (Expanded.isAllOnesValue()) {
722 if (Expanded != C->getAPIntValue()) {
723 EVT VT = Op.getValueType();
724 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
725 TLO.DAG.getConstant(Expanded, dl, VT));
726 return TLO.CombineTo(Op, New);
728 // If it already has all the bits set, nothing to change
729 // but don't shrink either!
730 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
735 KnownZero = std::move(KnownZeroOut);
736 KnownOne = std::move(KnownOneOut);
739 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
740 KnownOne, TLO, Depth+1))
742 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
743 KnownOne2, TLO, Depth+1))
745 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
746 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
748 // If the operands are constants, see if we can simplify them.
749 if (TLO.ShrinkDemandedConstant(Op, NewMask))
752 // Only known if known in both the LHS and RHS.
753 KnownOne &= KnownOne2;
754 KnownZero &= KnownZero2;
757 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
758 KnownOne, TLO, Depth+1))
760 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
761 KnownOne2, TLO, Depth+1))
763 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
764 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
766 // If the operands are constants, see if we can simplify them.
767 if (TLO.ShrinkDemandedConstant(Op, NewMask))
770 // Only known if known in both the LHS and RHS.
771 KnownOne &= KnownOne2;
772 KnownZero &= KnownZero2;
775 SDValue Op0 = Op.getOperand(0);
776 SDValue Op1 = Op.getOperand(1);
777 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
778 // If (1) we only need the sign-bit, (2) the setcc operands are the same
779 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
780 // -1, we may be able to bypass the setcc.
781 if (NewMask.isSignMask() && Op0.getScalarValueSizeInBits() == BitWidth &&
782 getBooleanContents(Op.getValueType()) ==
783 BooleanContent::ZeroOrNegativeOneBooleanContent) {
784 // If we're testing X < 0, then this compare isn't needed - just use X!
785 // FIXME: We're limiting to integer types here, but this should also work
786 // if we don't care about FP signed-zero. The use of SETLT with FP means
787 // that we don't care about NaNs.
788 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
789 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
790 return TLO.CombineTo(Op, Op0);
792 // TODO: Should we check for other forms of sign-bit comparisons?
793 // Examples: X <= -1, X >= 0
795 if (getBooleanContents(Op0.getValueType()) ==
796 TargetLowering::ZeroOrOneBooleanContent &&
798 KnownZero.setBitsFrom(1);
802 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
803 unsigned ShAmt = SA->getZExtValue();
804 SDValue InOp = Op.getOperand(0);
806 // If the shift count is an invalid immediate, don't do anything.
807 if (ShAmt >= BitWidth)
810 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
811 // single shift. We can do this if the bottom bits (which are shifted
812 // out) are never demanded.
813 if (InOp.getOpcode() == ISD::SRL &&
814 isa<ConstantSDNode>(InOp.getOperand(1))) {
815 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
816 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
817 unsigned Opc = ISD::SHL;
825 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
826 EVT VT = Op.getValueType();
827 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
828 InOp.getOperand(0), NewSA));
832 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
833 KnownZero, KnownOne, TLO, Depth+1))
836 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
837 // are not demanded. This will likely allow the anyext to be folded away.
838 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
839 SDValue InnerOp = InOp.getNode()->getOperand(0);
840 EVT InnerVT = InnerOp.getValueType();
841 unsigned InnerBits = InnerVT.getSizeInBits();
842 if (ShAmt < InnerBits && NewMask.getActiveBits() <= InnerBits &&
843 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
844 EVT ShTy = getShiftAmountTy(InnerVT, DL);
845 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
848 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
849 TLO.DAG.getConstant(ShAmt, dl, ShTy));
852 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
855 // Repeat the SHL optimization above in cases where an extension
856 // intervenes: (shl (anyext (shr x, c1)), c2) to
857 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
858 // aren't demanded (as above) and that the shifted upper c1 bits of
859 // x aren't demanded.
860 if (InOp.hasOneUse() &&
861 InnerOp.getOpcode() == ISD::SRL &&
862 InnerOp.hasOneUse() &&
863 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
864 unsigned InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
866 if (InnerShAmt < ShAmt &&
867 InnerShAmt < InnerBits &&
868 NewMask.getActiveBits() <= (InnerBits - InnerShAmt + ShAmt) &&
869 NewMask.countTrailingZeros() >= ShAmt) {
871 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
872 Op.getOperand(1).getValueType());
873 EVT VT = Op.getValueType();
874 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
875 InnerOp.getOperand(0));
876 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
882 KnownZero <<= SA->getZExtValue();
883 KnownOne <<= SA->getZExtValue();
884 // low bits known zero.
885 KnownZero.setLowBits(SA->getZExtValue());
889 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
890 EVT VT = Op.getValueType();
891 unsigned ShAmt = SA->getZExtValue();
892 unsigned VTSize = VT.getSizeInBits();
893 SDValue InOp = Op.getOperand(0);
895 // If the shift count is an invalid immediate, don't do anything.
896 if (ShAmt >= BitWidth)
899 APInt InDemandedMask = (NewMask << ShAmt);
901 // If the shift is exact, then it does demand the low bits (and knows that
903 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
904 InDemandedMask.setLowBits(ShAmt);
906 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
907 // single shift. We can do this if the top bits (which are shifted out)
908 // are never demanded.
909 if (InOp.getOpcode() == ISD::SHL &&
910 isa<ConstantSDNode>(InOp.getOperand(1))) {
911 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
912 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
913 unsigned Opc = ISD::SRL;
921 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
922 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
923 InOp.getOperand(0), NewSA));
927 // Compute the new bits that are at the top now.
928 if (SimplifyDemandedBits(InOp, InDemandedMask,
929 KnownZero, KnownOne, TLO, Depth+1))
931 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
932 KnownZero.lshrInPlace(ShAmt);
933 KnownOne.lshrInPlace(ShAmt);
935 KnownZero.setHighBits(ShAmt); // High bits known zero.
939 // If this is an arithmetic shift right and only the low-bit is set, we can
940 // always convert this into a logical shr, even if the shift amount is
941 // variable. The low bit of the shift cannot be an input sign bit unless
942 // the shift amount is >= the size of the datatype, which is undefined.
944 return TLO.CombineTo(Op,
945 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
946 Op.getOperand(0), Op.getOperand(1)));
948 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
949 EVT VT = Op.getValueType();
950 unsigned ShAmt = SA->getZExtValue();
952 // If the shift count is an invalid immediate, don't do anything.
953 if (ShAmt >= BitWidth)
956 APInt InDemandedMask = (NewMask << ShAmt);
958 // If the shift is exact, then it does demand the low bits (and knows that
960 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
961 InDemandedMask.setLowBits(ShAmt);
963 // If any of the demanded bits are produced by the sign extension, we also
964 // demand the input sign bit.
965 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
966 if (HighBits.intersects(NewMask))
967 InDemandedMask |= APInt::getSignMask(VT.getScalarSizeInBits());
969 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
970 KnownZero, KnownOne, TLO, Depth+1))
972 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
973 KnownZero.lshrInPlace(ShAmt);
974 KnownOne.lshrInPlace(ShAmt);
976 // Handle the sign bit, adjusted to where it is now in the mask.
977 APInt SignMask = APInt::getSignMask(BitWidth).lshr(ShAmt);
979 // If the input sign bit is known to be zero, or if none of the top bits
980 // are demanded, turn this into an unsigned shift right.
981 if (KnownZero.intersects(SignMask) || (HighBits & ~NewMask) == HighBits) {
983 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
984 return TLO.CombineTo(Op,
985 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
986 Op.getOperand(1), &Flags));
989 int Log2 = NewMask.exactLogBase2();
991 // The bit must come from the sign.
993 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
994 Op.getOperand(1).getValueType());
995 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
996 Op.getOperand(0), NewSA));
999 if (KnownOne.intersects(SignMask))
1000 // New bits are known one.
1001 KnownOne |= HighBits;
1004 case ISD::SIGN_EXTEND_INREG: {
1005 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1007 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
1008 // If we only care about the highest bit, don't bother shifting right.
1009 if (MsbMask == NewMask) {
1010 unsigned ShAmt = ExVT.getScalarSizeInBits();
1011 SDValue InOp = Op.getOperand(0);
1012 unsigned VTBits = Op->getValueType(0).getScalarSizeInBits();
1013 bool AlreadySignExtended =
1014 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
1015 // However if the input is already sign extended we expect the sign
1016 // extension to be dropped altogether later and do not simplify.
1017 if (!AlreadySignExtended) {
1018 // Compute the correct shift amount type, which must be getShiftAmountTy
1019 // for scalar types after legalization.
1020 EVT ShiftAmtTy = Op.getValueType();
1021 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1022 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1024 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
1026 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1027 Op.getValueType(), InOp,
1032 // Sign extension. Compute the demanded bits in the result that are not
1033 // present in the input.
1035 APInt::getHighBitsSet(BitWidth,
1036 BitWidth - ExVT.getScalarSizeInBits());
1038 // If none of the extended bits are demanded, eliminate the sextinreg.
1039 if ((NewBits & NewMask) == 0)
1040 return TLO.CombineTo(Op, Op.getOperand(0));
1043 APInt::getSignMask(ExVT.getScalarSizeInBits()).zext(BitWidth);
1044 APInt InputDemandedBits =
1045 APInt::getLowBitsSet(BitWidth,
1046 ExVT.getScalarSizeInBits()) &
1049 // Since the sign extended bits are demanded, we know that the sign
1051 InputDemandedBits |= InSignBit;
1053 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1054 KnownZero, KnownOne, TLO, Depth+1))
1056 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1058 // If the sign bit of the input is known set or clear, then we know the
1059 // top bits of the result.
1061 // If the input sign bit is known zero, convert this into a zero extension.
1062 if (KnownZero.intersects(InSignBit))
1063 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(
1064 Op.getOperand(0), dl, ExVT.getScalarType()));
1066 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1067 KnownOne |= NewBits;
1068 KnownZero &= ~NewBits;
1069 } else { // Input sign bit unknown
1070 KnownZero &= ~NewBits;
1071 KnownOne &= ~NewBits;
1075 case ISD::BUILD_PAIR: {
1076 EVT HalfVT = Op.getOperand(0).getValueType();
1077 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1079 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1080 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1082 APInt KnownZeroLo, KnownOneLo;
1083 APInt KnownZeroHi, KnownOneHi;
1085 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
1086 KnownOneLo, TLO, Depth + 1))
1089 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
1090 KnownOneHi, TLO, Depth + 1))
1093 KnownZero = KnownZeroLo.zext(BitWidth) |
1094 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
1096 KnownOne = KnownOneLo.zext(BitWidth) |
1097 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
1100 case ISD::ZERO_EXTEND: {
1101 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1102 APInt InMask = NewMask.trunc(OperandBitWidth);
1104 // If none of the top bits are demanded, convert this into an any_extend.
1106 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1107 if (!NewBits.intersects(NewMask))
1108 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1112 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1113 KnownZero, KnownOne, TLO, Depth+1))
1115 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1116 KnownZero = KnownZero.zext(BitWidth);
1117 KnownOne = KnownOne.zext(BitWidth);
1118 KnownZero |= NewBits;
1121 case ISD::SIGN_EXTEND: {
1122 EVT InVT = Op.getOperand(0).getValueType();
1123 unsigned InBits = InVT.getScalarSizeInBits();
1124 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
1125 APInt InSignBit = APInt::getOneBitSet(BitWidth, InBits - 1);
1126 APInt NewBits = ~InMask & NewMask;
1128 // If none of the top bits are demanded, convert this into an any_extend.
1130 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1134 // Since some of the sign extended bits are demanded, we know that the sign
1136 APInt InDemandedBits = InMask & NewMask;
1137 InDemandedBits |= InSignBit;
1138 InDemandedBits = InDemandedBits.trunc(InBits);
1140 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1141 KnownOne, TLO, Depth+1))
1143 KnownZero = KnownZero.zext(BitWidth);
1144 KnownOne = KnownOne.zext(BitWidth);
1146 // If the sign bit is known zero, convert this to a zero extend.
1147 if (KnownZero.intersects(InSignBit))
1148 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1152 // If the sign bit is known one, the top bits match.
1153 if (KnownOne.intersects(InSignBit)) {
1154 KnownOne |= NewBits;
1155 assert((KnownZero & NewBits) == 0);
1156 } else { // Otherwise, top bits aren't known.
1157 assert((KnownOne & NewBits) == 0);
1158 assert((KnownZero & NewBits) == 0);
1162 case ISD::ANY_EXTEND: {
1163 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1164 APInt InMask = NewMask.trunc(OperandBitWidth);
1165 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1166 KnownZero, KnownOne, TLO, Depth+1))
1168 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1169 KnownZero = KnownZero.zext(BitWidth);
1170 KnownOne = KnownOne.zext(BitWidth);
1173 case ISD::TRUNCATE: {
1174 // Simplify the input, using demanded bit information, and compute the known
1175 // zero/one bits live out.
1176 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1177 APInt TruncMask = NewMask.zext(OperandBitWidth);
1178 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1179 KnownZero, KnownOne, TLO, Depth+1))
1181 KnownZero = KnownZero.trunc(BitWidth);
1182 KnownOne = KnownOne.trunc(BitWidth);
1184 // If the input is only used by this truncate, see if we can shrink it based
1185 // on the known demanded bits.
1186 if (Op.getOperand(0).getNode()->hasOneUse()) {
1187 SDValue In = Op.getOperand(0);
1188 switch (In.getOpcode()) {
1191 // Shrink SRL by a constant if none of the high bits shifted in are
1193 if (TLO.LegalTypes() &&
1194 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1195 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1198 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1201 SDValue Shift = In.getOperand(1);
1202 if (TLO.LegalTypes()) {
1203 uint64_t ShVal = ShAmt->getZExtValue();
1204 Shift = TLO.DAG.getConstant(ShVal, dl,
1205 getShiftAmountTy(Op.getValueType(), DL));
1208 if (ShAmt->getZExtValue() < BitWidth) {
1209 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1210 OperandBitWidth - BitWidth);
1211 HighBits.lshrInPlace(ShAmt->getZExtValue());
1212 HighBits = HighBits.trunc(BitWidth);
1214 if (!(HighBits & NewMask)) {
1215 // None of the shifted in bits are needed. Add a truncate of the
1216 // shift input, then shift it.
1217 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1220 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1230 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1233 case ISD::AssertZext: {
1234 // AssertZext demands all of the high bits, plus any of the low bits
1235 // demanded by its users.
1236 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1237 APInt InMask = APInt::getLowBitsSet(BitWidth,
1238 VT.getSizeInBits());
1239 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1240 KnownZero, KnownOne, TLO, Depth+1))
1242 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1244 KnownZero |= ~InMask;
1248 // If this is an FP->Int bitcast and if the sign bit is the only
1249 // thing demanded, turn this into a FGETSIGN.
1250 if (!TLO.LegalOperations() &&
1251 !Op.getValueType().isVector() &&
1252 !Op.getOperand(0).getValueType().isVector() &&
1253 NewMask == APInt::getSignMask(Op.getValueSizeInBits()) &&
1254 Op.getOperand(0).getValueType().isFloatingPoint()) {
1255 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1256 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1257 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1258 Op.getOperand(0).getValueType() != MVT::f128) {
1259 // Cannot eliminate/lower SHL for f128 yet.
1260 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1261 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1262 // place. We expect the SHL to be eliminated by other optimizations.
1263 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1264 unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1265 if (!OpVTLegal && OpVTSizeInBits > 32)
1266 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1267 unsigned ShVal = Op.getValueSizeInBits() - 1;
1268 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
1269 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1278 // Add, Sub, and Mul don't demand any bits in positions beyond that
1279 // of the highest bit demanded of them.
1280 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1281 BitWidth - NewMask.countLeadingZeros());
1282 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1283 KnownOne2, TLO, Depth+1) ||
1284 SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1285 KnownOne2, TLO, Depth+1) ||
1286 // See if the operation should be performed at a smaller bit width.
1287 TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) {
1288 const SDNodeFlags *Flags = Op.getNode()->getFlags();
1289 if (Flags->hasNoSignedWrap() || Flags->hasNoUnsignedWrap()) {
1290 // Disable the nsw and nuw flags. We can no longer guarantee that we
1291 // won't wrap after simplification.
1292 SDNodeFlags NewFlags = *Flags;
1293 NewFlags.setNoSignedWrap(false);
1294 NewFlags.setNoUnsignedWrap(false);
1295 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, Op.getValueType(),
1296 Op.getOperand(0), Op.getOperand(1),
1298 return TLO.CombineTo(Op, NewOp);
1305 // Just use computeKnownBits to compute output bits.
1306 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1310 // If we know the value of all of the demanded bits, return this as a
1312 if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1313 // Avoid folding to a constant if any OpaqueConstant is involved.
1314 const SDNode *N = Op.getNode();
1315 for (SDNodeIterator I = SDNodeIterator::begin(N),
1316 E = SDNodeIterator::end(N); I != E; ++I) {
1318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1322 return TLO.CombineTo(Op,
1323 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
1329 /// Determine which of the bits specified in Mask are known to be either zero or
1330 /// one and return them in the KnownZero/KnownOne bitsets.
1331 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1334 const APInt &DemandedElts,
1335 const SelectionDAG &DAG,
1336 unsigned Depth) const {
1337 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1338 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1339 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1340 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1341 "Should use MaskedValueIsZero if you don't know whether Op"
1342 " is a target node!");
1343 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1346 /// This method can be implemented by targets that want to expose additional
1347 /// information about sign bits to the DAG Combiner.
1348 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1350 const SelectionDAG &,
1351 unsigned Depth) const {
1352 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1353 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1354 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1355 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1356 "Should use ComputeNumSignBits if you don't know whether Op"
1357 " is a target node!");
1361 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1365 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1367 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1371 // Only interested in constant splats, we don't care about undef
1372 // elements in identifying boolean constants and getConstantSplatNode
1373 // returns NULL if all ops are undef;
1374 CN = BV->getConstantSplatNode();
1379 switch (getBooleanContents(N->getValueType(0))) {
1380 case UndefinedBooleanContent:
1381 return CN->getAPIntValue()[0];
1382 case ZeroOrOneBooleanContent:
1384 case ZeroOrNegativeOneBooleanContent:
1385 return CN->isAllOnesValue();
1388 llvm_unreachable("Invalid boolean contents");
1391 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
1392 const SDLoc &DL) const {
1393 unsigned ElementWidth = VT.getScalarSizeInBits();
1395 getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
1396 ? APInt(ElementWidth, 1)
1397 : APInt::getAllOnesValue(ElementWidth);
1398 return DAG.getConstant(TrueInt, DL, VT);
1401 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1405 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1407 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1411 // Only interested in constant splats, we don't care about undef
1412 // elements in identifying boolean constants and getConstantSplatNode
1413 // returns NULL if all ops are undef;
1414 CN = BV->getConstantSplatNode();
1419 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1420 return !CN->getAPIntValue()[0];
1422 return CN->isNullValue();
1425 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1430 TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1432 case TargetLowering::ZeroOrOneBooleanContent:
1433 // An extended value of 1 is always true, unless its original type is i1,
1434 // in which case it will be sign extended to -1.
1435 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1436 case TargetLowering::UndefinedBooleanContent:
1437 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1438 return N->isAllOnesValue() && SExt;
1440 llvm_unreachable("Unexpected enumeration.");
1443 /// This helper function of SimplifySetCC tries to optimize the comparison when
1444 /// either operand of the SetCC node is a bitwise-and instruction.
1445 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1447 DAGCombinerInfo &DCI,
1448 const SDLoc &DL) const {
1449 // Match these patterns in any of their permutations:
1452 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1455 EVT OpVT = N0.getValueType();
1456 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
1457 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1461 if (N0.getOperand(0) == N1) {
1462 X = N0.getOperand(1);
1463 Y = N0.getOperand(0);
1464 } else if (N0.getOperand(1) == N1) {
1465 X = N0.getOperand(0);
1466 Y = N0.getOperand(1);
1471 SelectionDAG &DAG = DCI.DAG;
1472 SDValue Zero = DAG.getConstant(0, DL, OpVT);
1473 if (DAG.isKnownToBeAPowerOfTwo(Y)) {
1474 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1475 // Note that where Y is variable and is known to have at most one bit set
1476 // (for example, if it is Z & 1) we cannot do this; the expressions are not
1477 // equivalent when Y == 0.
1478 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1479 if (DCI.isBeforeLegalizeOps() ||
1480 isCondCodeLegal(Cond, N0.getSimpleValueType()))
1481 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1482 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1483 // If the target supports an 'and-not' or 'and-complement' logic operation,
1484 // try to use that to make a comparison operation more efficient.
1485 // But don't do this transform if the mask is a single bit because there are
1486 // more efficient ways to deal with that case (for example, 'bt' on x86 or
1487 // 'rlwinm' on PPC).
1489 // Bail out if the compare operand that we want to turn into a zero is
1490 // already a zero (otherwise, infinite loop).
1491 auto *YConst = dyn_cast<ConstantSDNode>(Y);
1492 if (YConst && YConst->isNullValue())
1495 // Transform this into: ~X & Y == 0.
1496 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1497 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1498 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1504 /// Try to simplify a setcc built with the specified operands and cc. If it is
1505 /// unable to simplify it, return a null SDValue.
1506 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1507 ISD::CondCode Cond, bool foldBooleans,
1508 DAGCombinerInfo &DCI,
1509 const SDLoc &dl) const {
1510 SelectionDAG &DAG = DCI.DAG;
1512 // These setcc operations always fold.
1516 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
1518 case ISD::SETTRUE2: {
1519 TargetLowering::BooleanContent Cnt =
1520 getBooleanContents(N0->getValueType(0));
1521 return DAG.getConstant(
1522 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1527 // Ensure that the constant occurs on the RHS, and fold constant
1529 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1530 if (isa<ConstantSDNode>(N0.getNode()) &&
1531 (DCI.isBeforeLegalizeOps() ||
1532 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1533 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1535 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1536 const APInt &C1 = N1C->getAPIntValue();
1538 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1539 // equality comparison, then we're just comparing whether X itself is
1541 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1542 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1543 N0.getOperand(1).getOpcode() == ISD::Constant) {
1545 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1546 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1547 ShAmt == Log2_32(N0.getValueSizeInBits())) {
1548 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1549 // (srl (ctlz x), 5) == 0 -> X != 0
1550 // (srl (ctlz x), 5) != 1 -> X != 0
1553 // (srl (ctlz x), 5) != 0 -> X == 0
1554 // (srl (ctlz x), 5) == 1 -> X == 0
1557 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1558 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1564 // Look through truncs that don't change the value of a ctpop.
1565 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1566 CTPOP = N0.getOperand(0);
1568 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1570 N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
1571 EVT CTVT = CTPOP.getValueType();
1572 SDValue CTOp = CTPOP.getOperand(0);
1574 // (ctpop x) u< 2 -> (x & x-1) == 0
1575 // (ctpop x) u> 1 -> (x & x-1) != 0
1576 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1577 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1578 DAG.getConstant(1, dl, CTVT));
1579 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1580 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1581 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1584 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1587 // (zext x) == C --> x == (trunc C)
1588 // (sext x) == C --> x == (trunc C)
1589 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1590 DCI.isBeforeLegalize() && N0->hasOneUse()) {
1591 unsigned MinBits = N0.getValueSizeInBits();
1593 bool Signed = false;
1594 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1596 MinBits = N0->getOperand(0).getValueSizeInBits();
1597 PreExt = N0->getOperand(0);
1598 } else if (N0->getOpcode() == ISD::AND) {
1599 // DAGCombine turns costly ZExts into ANDs
1600 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1601 if ((C->getAPIntValue()+1).isPowerOf2()) {
1602 MinBits = C->getAPIntValue().countTrailingOnes();
1603 PreExt = N0->getOperand(0);
1605 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1607 MinBits = N0->getOperand(0).getValueSizeInBits();
1608 PreExt = N0->getOperand(0);
1610 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
1611 // ZEXTLOAD / SEXTLOAD
1612 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1613 MinBits = LN0->getMemoryVT().getSizeInBits();
1615 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1617 MinBits = LN0->getMemoryVT().getSizeInBits();
1622 // Figure out how many bits we need to preserve this constant.
1623 unsigned ReqdBits = Signed ?
1624 C1.getBitWidth() - C1.getNumSignBits() + 1 :
1627 // Make sure we're not losing bits from the constant.
1629 MinBits < C1.getBitWidth() &&
1630 MinBits >= ReqdBits) {
1631 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1632 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1633 // Will get folded away.
1634 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1635 if (MinBits == 1 && C1 == 1)
1636 // Invert the condition.
1637 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
1638 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1639 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1640 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1643 // If truncating the setcc operands is not desirable, we can still
1644 // simplify the expression in some cases:
1645 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1646 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1647 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1648 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1649 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1650 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1651 SDValue TopSetCC = N0->getOperand(0);
1652 unsigned N0Opc = N0->getOpcode();
1653 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1654 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1655 TopSetCC.getOpcode() == ISD::SETCC &&
1656 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1657 (isConstFalseVal(N1C) ||
1658 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1660 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1661 (!N1C->isNullValue() && Cond == ISD::SETNE);
1666 ISD::CondCode InvCond = ISD::getSetCCInverse(
1667 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1668 TopSetCC.getOperand(0).getValueType().isInteger());
1669 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1670 TopSetCC.getOperand(1),
1677 // If the LHS is '(and load, const)', the RHS is 0,
1678 // the test is for equality or unsigned, and all 1 bits of the const are
1679 // in the same partial word, see if we can shorten the load.
1680 if (DCI.isBeforeLegalize() &&
1681 !ISD::isSignedIntSetCC(Cond) &&
1682 N0.getOpcode() == ISD::AND && C1 == 0 &&
1683 N0.getNode()->hasOneUse() &&
1684 isa<LoadSDNode>(N0.getOperand(0)) &&
1685 N0.getOperand(0).getNode()->hasOneUse() &&
1686 isa<ConstantSDNode>(N0.getOperand(1))) {
1687 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1689 unsigned bestWidth = 0, bestOffset = 0;
1690 if (!Lod->isVolatile() && Lod->isUnindexed()) {
1691 unsigned origWidth = N0.getValueSizeInBits();
1692 unsigned maskWidth = origWidth;
1693 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1694 // 8 bits, but have to be careful...
1695 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1696 origWidth = Lod->getMemoryVT().getSizeInBits();
1698 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1699 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1700 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1701 for (unsigned offset=0; offset<origWidth/width; offset++) {
1702 if ((newMask & Mask) == Mask) {
1703 if (!DAG.getDataLayout().isLittleEndian())
1704 bestOffset = (origWidth/width - offset - 1) * (width/8);
1706 bestOffset = (uint64_t)offset * (width/8);
1707 bestMask = Mask.lshr(offset * (width/8) * 8);
1711 newMask = newMask << width;
1716 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1717 if (newVT.isRound()) {
1718 EVT PtrType = Lod->getOperand(1).getValueType();
1719 SDValue Ptr = Lod->getBasePtr();
1720 if (bestOffset != 0)
1721 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1722 DAG.getConstant(bestOffset, dl, PtrType));
1723 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1724 SDValue NewLoad = DAG.getLoad(
1725 newVT, dl, Lod->getChain(), Ptr,
1726 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
1727 return DAG.getSetCC(dl, VT,
1728 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1729 DAG.getConstant(bestMask.trunc(bestWidth),
1731 DAG.getConstant(0LL, dl, newVT), Cond);
1736 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1737 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1738 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
1740 // If the comparison constant has bits in the upper part, the
1741 // zero-extended value could never match.
1742 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1743 C1.getBitWidth() - InSize))) {
1747 case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
1750 case ISD::SETNE: return DAG.getConstant(1, dl, VT);
1753 // True if the sign bit of C1 is set.
1754 return DAG.getConstant(C1.isNegative(), dl, VT);
1757 // True if the sign bit of C1 isn't set.
1758 return DAG.getConstant(C1.isNonNegative(), dl, VT);
1764 // Otherwise, we can perform the comparison with the low bits.
1772 EVT newVT = N0.getOperand(0).getValueType();
1773 if (DCI.isBeforeLegalizeOps() ||
1774 (isOperationLegal(ISD::SETCC, newVT) &&
1775 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1777 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
1778 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
1780 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1782 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
1787 break; // todo, be more careful with signed comparisons
1789 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1790 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1791 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1792 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1793 EVT ExtDstTy = N0.getValueType();
1794 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1796 // If the constant doesn't fit into the number of bits for the source of
1797 // the sign extension, it is impossible for both sides to be equal.
1798 if (C1.getMinSignedBits() > ExtSrcTyBits)
1799 return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
1802 EVT Op0Ty = N0.getOperand(0).getValueType();
1803 if (Op0Ty == ExtSrcTy) {
1804 ZextOp = N0.getOperand(0);
1806 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1807 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1808 DAG.getConstant(Imm, dl, Op0Ty));
1810 if (!DCI.isCalledByLegalizer())
1811 DCI.AddToWorklist(ZextOp.getNode());
1812 // Otherwise, make this a use of a zext.
1813 return DAG.getSetCC(dl, VT, ZextOp,
1814 DAG.getConstant(C1 & APInt::getLowBitsSet(
1819 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1820 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1821 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1822 if (N0.getOpcode() == ISD::SETCC &&
1823 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1824 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1826 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1827 // Invert the condition.
1828 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1829 CC = ISD::getSetCCInverse(CC,
1830 N0.getOperand(0).getValueType().isInteger());
1831 if (DCI.isBeforeLegalizeOps() ||
1832 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1833 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1836 if ((N0.getOpcode() == ISD::XOR ||
1837 (N0.getOpcode() == ISD::AND &&
1838 N0.getOperand(0).getOpcode() == ISD::XOR &&
1839 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1840 isa<ConstantSDNode>(N0.getOperand(1)) &&
1841 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1842 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1843 // can only do this if the top bits are known zero.
1844 unsigned BitWidth = N0.getValueSizeInBits();
1845 if (DAG.MaskedValueIsZero(N0,
1846 APInt::getHighBitsSet(BitWidth,
1848 // Okay, get the un-inverted input value.
1850 if (N0.getOpcode() == ISD::XOR)
1851 Val = N0.getOperand(0);
1853 assert(N0.getOpcode() == ISD::AND &&
1854 N0.getOperand(0).getOpcode() == ISD::XOR);
1855 // ((X^1)&1)^1 -> X & 1
1856 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1857 N0.getOperand(0).getOperand(0),
1861 return DAG.getSetCC(dl, VT, Val, N1,
1862 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1864 } else if (N1C->getAPIntValue() == 1 &&
1866 getBooleanContents(N0->getValueType(0)) ==
1867 ZeroOrOneBooleanContent)) {
1869 if (Op0.getOpcode() == ISD::TRUNCATE)
1870 Op0 = Op0.getOperand(0);
1872 if ((Op0.getOpcode() == ISD::XOR) &&
1873 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1874 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1875 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1876 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1877 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1880 if (Op0.getOpcode() == ISD::AND &&
1881 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1882 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1883 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1884 if (Op0.getValueType().bitsGT(VT))
1885 Op0 = DAG.getNode(ISD::AND, dl, VT,
1886 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1887 DAG.getConstant(1, dl, VT));
1888 else if (Op0.getValueType().bitsLT(VT))
1889 Op0 = DAG.getNode(ISD::AND, dl, VT,
1890 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1891 DAG.getConstant(1, dl, VT));
1893 return DAG.getSetCC(dl, VT, Op0,
1894 DAG.getConstant(0, dl, Op0.getValueType()),
1895 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1897 if (Op0.getOpcode() == ISD::AssertZext &&
1898 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1899 return DAG.getSetCC(dl, VT, Op0,
1900 DAG.getConstant(0, dl, Op0.getValueType()),
1901 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1905 APInt MinVal, MaxVal;
1906 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1907 if (ISD::isSignedIntSetCC(Cond)) {
1908 MinVal = APInt::getSignedMinValue(OperandBitSize);
1909 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1911 MinVal = APInt::getMinValue(OperandBitSize);
1912 MaxVal = APInt::getMaxValue(OperandBitSize);
1915 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1916 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1917 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true
1918 // X >= C0 --> X > (C0 - 1)
1920 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1921 if ((DCI.isBeforeLegalizeOps() ||
1922 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1923 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1924 isLegalICmpImmediate(C.getSExtValue())))) {
1925 return DAG.getSetCC(dl, VT, N0,
1926 DAG.getConstant(C, dl, N1.getValueType()),
1931 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1932 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true
1933 // X <= C0 --> X < (C0 + 1)
1935 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1936 if ((DCI.isBeforeLegalizeOps() ||
1937 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1938 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1939 isLegalICmpImmediate(C.getSExtValue())))) {
1940 return DAG.getSetCC(dl, VT, N0,
1941 DAG.getConstant(C, dl, N1.getValueType()),
1946 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1947 return DAG.getConstant(0, dl, VT); // X < MIN --> false
1948 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1949 return DAG.getConstant(1, dl, VT); // X >= MIN --> true
1950 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1951 return DAG.getConstant(0, dl, VT); // X > MAX --> false
1952 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1953 return DAG.getConstant(1, dl, VT); // X <= MAX --> true
1955 // Canonicalize setgt X, Min --> setne X, Min
1956 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1957 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1958 // Canonicalize setlt X, Max --> setne X, Max
1959 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1960 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1962 // If we have setult X, 1, turn it into seteq X, 0
1963 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1964 return DAG.getSetCC(dl, VT, N0,
1965 DAG.getConstant(MinVal, dl, N0.getValueType()),
1967 // If we have setugt X, Max-1, turn it into seteq X, Max
1968 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1969 return DAG.getSetCC(dl, VT, N0,
1970 DAG.getConstant(MaxVal, dl, N0.getValueType()),
1973 // If we have "setcc X, C0", check to see if we can shrink the immediate
1976 // SETUGT X, SINTMAX -> SETLT X, 0
1977 if (Cond == ISD::SETUGT &&
1978 C1 == APInt::getSignedMaxValue(OperandBitSize))
1979 return DAG.getSetCC(dl, VT, N0,
1980 DAG.getConstant(0, dl, N1.getValueType()),
1983 // SETULT X, SINTMIN -> SETGT X, -1
1984 if (Cond == ISD::SETULT &&
1985 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1986 SDValue ConstMinusOne =
1987 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
1989 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1992 // Fold bit comparisons when we can.
1993 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1994 (VT == N0.getValueType() ||
1995 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1996 N0.getOpcode() == ISD::AND) {
1997 auto &DL = DAG.getDataLayout();
1998 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1999 EVT ShiftTy = DCI.isBeforeLegalize()
2001 : getShiftAmountTy(N0.getValueType(), DL);
2002 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
2003 // Perform the xform if the AND RHS is a single bit.
2004 if (AndRHS->getAPIntValue().isPowerOf2()) {
2005 return DAG.getNode(ISD::TRUNCATE, dl, VT,
2006 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2007 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
2010 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2011 // (X & 8) == 8 --> (X & 8) >> 3
2012 // Perform the xform if C1 is a single bit.
2013 if (C1.isPowerOf2()) {
2014 return DAG.getNode(ISD::TRUNCATE, dl, VT,
2015 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2016 DAG.getConstant(C1.logBase2(), dl,
2023 if (C1.getMinSignedBits() <= 64 &&
2024 !isLegalICmpImmediate(C1.getSExtValue())) {
2025 // (X & -256) == 256 -> (X >> 8) == 1
2026 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2027 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2028 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2029 const APInt &AndRHSC = AndRHS->getAPIntValue();
2030 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2031 unsigned ShiftBits = AndRHSC.countTrailingZeros();
2032 auto &DL = DAG.getDataLayout();
2033 EVT ShiftTy = DCI.isBeforeLegalize()
2035 : getShiftAmountTy(N0.getValueType(), DL);
2036 EVT CmpTy = N0.getValueType();
2037 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2038 DAG.getConstant(ShiftBits, dl,
2040 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
2041 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2044 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2045 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2046 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2047 // X < 0x100000000 -> (X >> 32) < 1
2048 // X >= 0x100000000 -> (X >> 32) >= 1
2049 // X <= 0x0ffffffff -> (X >> 32) < 1
2050 // X > 0x0ffffffff -> (X >> 32) >= 1
2053 ISD::CondCode NewCond = Cond;
2055 ShiftBits = C1.countTrailingOnes();
2057 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2059 ShiftBits = C1.countTrailingZeros();
2061 NewC.lshrInPlace(ShiftBits);
2062 if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
2063 isLegalICmpImmediate(NewC.getSExtValue())) {
2064 auto &DL = DAG.getDataLayout();
2065 EVT ShiftTy = DCI.isBeforeLegalize()
2067 : getShiftAmountTy(N0.getValueType(), DL);
2068 EVT CmpTy = N0.getValueType();
2069 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2070 DAG.getConstant(ShiftBits, dl, ShiftTy));
2071 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
2072 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2078 if (isa<ConstantFPSDNode>(N0.getNode())) {
2079 // Constant fold or commute setcc.
2080 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2081 if (O.getNode()) return O;
2082 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2083 // If the RHS of an FP comparison is a constant, simplify it away in
2085 if (CFP->getValueAPF().isNaN()) {
2086 // If an operand is known to be a nan, we can fold it.
2087 switch (ISD::getUnorderedFlavor(Cond)) {
2088 default: llvm_unreachable("Unknown flavor!");
2089 case 0: // Known false.
2090 return DAG.getConstant(0, dl, VT);
2091 case 1: // Known true.
2092 return DAG.getConstant(1, dl, VT);
2093 case 2: // Undefined.
2094 return DAG.getUNDEF(VT);
2098 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
2099 // constant if knowing that the operand is non-nan is enough. We prefer to
2100 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2102 if (Cond == ISD::SETO || Cond == ISD::SETUO)
2103 return DAG.getSetCC(dl, VT, N0, N0, Cond);
2105 // setcc (fneg x), C -> setcc swap(pred) x, -C
2106 if (N0.getOpcode() == ISD::FNEG) {
2107 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
2108 if (DCI.isBeforeLegalizeOps() ||
2109 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
2110 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
2111 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
2115 // If the condition is not legal, see if we can find an equivalent one
2117 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2118 // If the comparison was an awkward floating-point == or != and one of
2119 // the comparison operands is infinity or negative infinity, convert the
2120 // condition to a less-awkward <= or >=.
2121 if (CFP->getValueAPF().isInfinity()) {
2122 if (CFP->getValueAPF().isNegative()) {
2123 if (Cond == ISD::SETOEQ &&
2124 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2125 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2126 if (Cond == ISD::SETUEQ &&
2127 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2128 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2129 if (Cond == ISD::SETUNE &&
2130 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2131 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2132 if (Cond == ISD::SETONE &&
2133 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2134 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2136 if (Cond == ISD::SETOEQ &&
2137 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2138 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2139 if (Cond == ISD::SETUEQ &&
2140 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2141 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2142 if (Cond == ISD::SETUNE &&
2143 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2144 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2145 if (Cond == ISD::SETONE &&
2146 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2147 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2154 // The sext(setcc()) => setcc() optimization relies on the appropriate
2155 // constant being emitted.
2157 switch (getBooleanContents(N0.getValueType())) {
2158 case UndefinedBooleanContent:
2159 case ZeroOrOneBooleanContent:
2160 EqVal = ISD::isTrueWhenEqual(Cond);
2162 case ZeroOrNegativeOneBooleanContent:
2163 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2167 // We can always fold X == X for integer setcc's.
2168 if (N0.getValueType().isInteger()) {
2169 return DAG.getConstant(EqVal, dl, VT);
2171 unsigned UOF = ISD::getUnorderedFlavor(Cond);
2172 if (UOF == 2) // FP operators that are undefined on NaNs.
2173 return DAG.getConstant(EqVal, dl, VT);
2174 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2175 return DAG.getConstant(EqVal, dl, VT);
2176 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2177 // if it is not already.
2178 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2179 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2180 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2181 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2184 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2185 N0.getValueType().isInteger()) {
2186 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2187 N0.getOpcode() == ISD::XOR) {
2188 // Simplify (X+Y) == (X+Z) --> Y == Z
2189 if (N0.getOpcode() == N1.getOpcode()) {
2190 if (N0.getOperand(0) == N1.getOperand(0))
2191 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2192 if (N0.getOperand(1) == N1.getOperand(1))
2193 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2194 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2195 // If X op Y == Y op X, try other combinations.
2196 if (N0.getOperand(0) == N1.getOperand(1))
2197 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2199 if (N0.getOperand(1) == N1.getOperand(0))
2200 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2205 // If RHS is a legal immediate value for a compare instruction, we need
2206 // to be careful about increasing register pressure needlessly.
2207 bool LegalRHSImm = false;
2209 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2210 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2211 // Turn (X+C1) == C2 --> X == C2-C1
2212 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2213 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2214 DAG.getConstant(RHSC->getAPIntValue()-
2215 LHSR->getAPIntValue(),
2216 dl, N0.getValueType()), Cond);
2219 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2220 if (N0.getOpcode() == ISD::XOR)
2221 // If we know that all of the inverted bits are zero, don't bother
2222 // performing the inversion.
2223 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2225 DAG.getSetCC(dl, VT, N0.getOperand(0),
2226 DAG.getConstant(LHSR->getAPIntValue() ^
2227 RHSC->getAPIntValue(),
2228 dl, N0.getValueType()),
2232 // Turn (C1-X) == C2 --> X == C1-C2
2233 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2234 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2236 DAG.getSetCC(dl, VT, N0.getOperand(1),
2237 DAG.getConstant(SUBC->getAPIntValue() -
2238 RHSC->getAPIntValue(),
2239 dl, N0.getValueType()),
2244 // Could RHSC fold directly into a compare?
2245 if (RHSC->getValueType(0).getSizeInBits() <= 64)
2246 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2249 // Simplify (X+Z) == X --> Z == 0
2250 // Don't do this if X is an immediate that can fold into a cmp
2251 // instruction and X+Z has other uses. It could be an induction variable
2252 // chain, and the transform would increase register pressure.
2253 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2254 if (N0.getOperand(0) == N1)
2255 return DAG.getSetCC(dl, VT, N0.getOperand(1),
2256 DAG.getConstant(0, dl, N0.getValueType()), Cond);
2257 if (N0.getOperand(1) == N1) {
2258 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2259 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2260 DAG.getConstant(0, dl, N0.getValueType()),
2262 if (N0.getNode()->hasOneUse()) {
2263 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2264 auto &DL = DAG.getDataLayout();
2265 // (Z-X) == X --> Z == X<<1
2266 SDValue SH = DAG.getNode(
2267 ISD::SHL, dl, N1.getValueType(), N1,
2268 DAG.getConstant(1, dl,
2269 getShiftAmountTy(N1.getValueType(), DL)));
2270 if (!DCI.isCalledByLegalizer())
2271 DCI.AddToWorklist(SH.getNode());
2272 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2278 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2279 N1.getOpcode() == ISD::XOR) {
2280 // Simplify X == (X+Z) --> Z == 0
2281 if (N1.getOperand(0) == N0)
2282 return DAG.getSetCC(dl, VT, N1.getOperand(1),
2283 DAG.getConstant(0, dl, N1.getValueType()), Cond);
2284 if (N1.getOperand(1) == N0) {
2285 if (DAG.isCommutativeBinOp(N1.getOpcode()))
2286 return DAG.getSetCC(dl, VT, N1.getOperand(0),
2287 DAG.getConstant(0, dl, N1.getValueType()), Cond);
2288 if (N1.getNode()->hasOneUse()) {
2289 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2290 auto &DL = DAG.getDataLayout();
2291 // X == (Z-X) --> X<<1 == Z
2292 SDValue SH = DAG.getNode(
2293 ISD::SHL, dl, N1.getValueType(), N0,
2294 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
2295 if (!DCI.isCalledByLegalizer())
2296 DCI.AddToWorklist(SH.getNode());
2297 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2302 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2306 // Fold away ALL boolean setcc's.
2308 if (N0.getValueType() == MVT::i1 && foldBooleans) {
2310 default: llvm_unreachable("Unknown integer setcc!");
2311 case ISD::SETEQ: // X == Y -> ~(X^Y)
2312 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2313 N0 = DAG.getNOT(dl, Temp, MVT::i1);
2314 if (!DCI.isCalledByLegalizer())
2315 DCI.AddToWorklist(Temp.getNode());
2317 case ISD::SETNE: // X != Y --> (X^Y)
2318 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2320 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2321 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
2322 Temp = DAG.getNOT(dl, N0, MVT::i1);
2323 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2324 if (!DCI.isCalledByLegalizer())
2325 DCI.AddToWorklist(Temp.getNode());
2327 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2328 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
2329 Temp = DAG.getNOT(dl, N1, MVT::i1);
2330 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2331 if (!DCI.isCalledByLegalizer())
2332 DCI.AddToWorklist(Temp.getNode());
2334 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2335 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
2336 Temp = DAG.getNOT(dl, N0, MVT::i1);
2337 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2338 if (!DCI.isCalledByLegalizer())
2339 DCI.AddToWorklist(Temp.getNode());
2341 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2342 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
2343 Temp = DAG.getNOT(dl, N1, MVT::i1);
2344 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2347 if (VT != MVT::i1) {
2348 if (!DCI.isCalledByLegalizer())
2349 DCI.AddToWorklist(N0.getNode());
2350 // FIXME: If running after legalize, we probably can't do this.
2351 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2356 // Could not fold it.
2360 /// Returns true (and the GlobalValue and the offset) if the node is a
2361 /// GlobalAddress + offset.
2362 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2363 int64_t &Offset) const {
2364 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
2365 GA = GASD->getGlobal();
2366 Offset += GASD->getOffset();
2370 if (N->getOpcode() == ISD::ADD) {
2371 SDValue N1 = N->getOperand(0);
2372 SDValue N2 = N->getOperand(1);
2373 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2374 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
2375 Offset += V->getSExtValue();
2378 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2379 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
2380 Offset += V->getSExtValue();
2389 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2390 DAGCombinerInfo &DCI) const {
2391 // Default implementation: no optimization.
2395 //===----------------------------------------------------------------------===//
2396 // Inline Assembler Implementation Methods
2397 //===----------------------------------------------------------------------===//
2399 TargetLowering::ConstraintType
2400 TargetLowering::getConstraintType(StringRef Constraint) const {
2401 unsigned S = Constraint.size();
2404 switch (Constraint[0]) {
2406 case 'r': return C_RegisterClass;
2408 case 'o': // offsetable
2409 case 'V': // not offsetable
2411 case 'i': // Simple Integer or Relocatable Constant
2412 case 'n': // Simple Integer
2413 case 'E': // Floating Point Constant
2414 case 'F': // Floating Point Constant
2415 case 's': // Relocatable Constant
2416 case 'p': // Address.
2417 case 'X': // Allow ANY value.
2418 case 'I': // Target registers.
2432 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2433 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2440 /// Try to replace an X constraint, which matches anything, with another that
2441 /// has more specific requirements based on the type of the corresponding
2443 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2444 if (ConstraintVT.isInteger())
2446 if (ConstraintVT.isFloatingPoint())
2447 return "f"; // works for many targets
2451 /// Lower the specified operand into the Ops vector.
2452 /// If it is invalid, don't add anything to Ops.
2453 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2454 std::string &Constraint,
2455 std::vector<SDValue> &Ops,
2456 SelectionDAG &DAG) const {
2458 if (Constraint.length() > 1) return;
2460 char ConstraintLetter = Constraint[0];
2461 switch (ConstraintLetter) {
2463 case 'X': // Allows any operand; labels (basic block) use this.
2464 if (Op.getOpcode() == ISD::BasicBlock) {
2469 case 'i': // Simple Integer or Relocatable Constant
2470 case 'n': // Simple Integer
2471 case 's': { // Relocatable Constant
2472 // These operands are interested in values of the form (GV+C), where C may
2473 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2474 // is possible and fine if either GV or C are missing.
2475 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2476 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2478 // If we have "(add GV, C)", pull out GV/C
2479 if (Op.getOpcode() == ISD::ADD) {
2480 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2481 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2483 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2484 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2492 // If we find a valid operand, map to the TargetXXX version so that the
2493 // value itself doesn't get selected.
2494 if (GA) { // Either &GV or &GV+C
2495 if (ConstraintLetter != 'n') {
2496 int64_t Offs = GA->getOffset();
2497 if (C) Offs += C->getZExtValue();
2498 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2499 C ? SDLoc(C) : SDLoc(),
2500 Op.getValueType(), Offs));
2504 if (C) { // just C, no GV.
2505 // Simple constants are not allowed for 's'.
2506 if (ConstraintLetter != 's') {
2507 // gcc prints these as sign extended. Sign extend value to 64 bits
2508 // now; without this it would get ZExt'd later in
2509 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2510 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2511 SDLoc(C), MVT::i64));
2520 std::pair<unsigned, const TargetRegisterClass *>
2521 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2522 StringRef Constraint,
2524 if (Constraint.empty() || Constraint[0] != '{')
2525 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2526 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2528 // Remove the braces from around the name.
2529 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2531 std::pair<unsigned, const TargetRegisterClass*> R =
2532 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2534 // Figure out which register class contains this reg.
2535 for (const TargetRegisterClass *RC : RI->regclasses()) {
2536 // If none of the value types for this register class are valid, we
2537 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2541 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2543 if (RegName.equals_lower(RI->getRegAsmName(*I))) {
2544 std::pair<unsigned, const TargetRegisterClass*> S =
2545 std::make_pair(*I, RC);
2547 // If this register class has the requested value type, return it,
2548 // otherwise keep searching and return the first class found
2549 // if no other is found which explicitly has the requested type.
2550 if (RC->hasType(VT))
2561 //===----------------------------------------------------------------------===//
2562 // Constraint Selection.
2564 /// Return true of this is an input operand that is a matching constraint like
2566 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2567 assert(!ConstraintCode.empty() && "No known constraint!");
2568 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2571 /// If this is an input matching constraint, this method returns the output
2572 /// operand it matches.
2573 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2574 assert(!ConstraintCode.empty() && "No known constraint!");
2575 return atoi(ConstraintCode.c_str());
2578 /// Split up the constraint string from the inline assembly value into the
2579 /// specific constraints and their prefixes, and also tie in the associated
2581 /// If this returns an empty vector, and if the constraint string itself
2582 /// isn't empty, there was an error parsing.
2583 TargetLowering::AsmOperandInfoVector
2584 TargetLowering::ParseConstraints(const DataLayout &DL,
2585 const TargetRegisterInfo *TRI,
2586 ImmutableCallSite CS) const {
2587 /// Information about all of the constraints.
2588 AsmOperandInfoVector ConstraintOperands;
2589 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2590 unsigned maCount = 0; // Largest number of multiple alternative constraints.
2592 // Do a prepass over the constraints, canonicalizing them, and building up the
2593 // ConstraintOperands list.
2594 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2595 unsigned ResNo = 0; // ResNo - The result number of the next output.
2597 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2598 ConstraintOperands.emplace_back(std::move(CI));
2599 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2601 // Update multiple alternative constraint count.
2602 if (OpInfo.multipleAlternatives.size() > maCount)
2603 maCount = OpInfo.multipleAlternatives.size();
2605 OpInfo.ConstraintVT = MVT::Other;
2607 // Compute the value type for each operand.
2608 switch (OpInfo.Type) {
2609 case InlineAsm::isOutput:
2610 // Indirect outputs just consume an argument.
2611 if (OpInfo.isIndirect) {
2612 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2616 // The return value of the call is this value. As such, there is no
2617 // corresponding argument.
2618 assert(!CS.getType()->isVoidTy() &&
2620 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2621 OpInfo.ConstraintVT =
2622 getSimpleValueType(DL, STy->getElementType(ResNo));
2624 assert(ResNo == 0 && "Asm only has one result!");
2625 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2629 case InlineAsm::isInput:
2630 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2632 case InlineAsm::isClobber:
2637 if (OpInfo.CallOperandVal) {
2638 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2639 if (OpInfo.isIndirect) {
2640 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2642 report_fatal_error("Indirect operand for inline asm not a pointer!");
2643 OpTy = PtrTy->getElementType();
2646 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2647 if (StructType *STy = dyn_cast<StructType>(OpTy))
2648 if (STy->getNumElements() == 1)
2649 OpTy = STy->getElementType(0);
2651 // If OpTy is not a single value, it may be a struct/union that we
2652 // can tile with integers.
2653 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2654 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2663 OpInfo.ConstraintVT =
2664 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2667 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2668 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2669 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2671 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2676 // If we have multiple alternative constraints, select the best alternative.
2677 if (!ConstraintOperands.empty()) {
2679 unsigned bestMAIndex = 0;
2680 int bestWeight = -1;
2681 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2684 // Compute the sums of the weights for each alternative, keeping track
2685 // of the best (highest weight) one so far.
2686 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2688 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2689 cIndex != eIndex; ++cIndex) {
2690 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2691 if (OpInfo.Type == InlineAsm::isClobber)
2694 // If this is an output operand with a matching input operand,
2695 // look up the matching input. If their types mismatch, e.g. one
2696 // is an integer, the other is floating point, or their sizes are
2697 // different, flag it as an maCantMatch.
2698 if (OpInfo.hasMatchingInput()) {
2699 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2700 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2701 if ((OpInfo.ConstraintVT.isInteger() !=
2702 Input.ConstraintVT.isInteger()) ||
2703 (OpInfo.ConstraintVT.getSizeInBits() !=
2704 Input.ConstraintVT.getSizeInBits())) {
2705 weightSum = -1; // Can't match.
2710 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2715 weightSum += weight;
2718 if (weightSum > bestWeight) {
2719 bestWeight = weightSum;
2720 bestMAIndex = maIndex;
2724 // Now select chosen alternative in each constraint.
2725 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2726 cIndex != eIndex; ++cIndex) {
2727 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2728 if (cInfo.Type == InlineAsm::isClobber)
2730 cInfo.selectAlternative(bestMAIndex);
2735 // Check and hook up tied operands, choose constraint code to use.
2736 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2737 cIndex != eIndex; ++cIndex) {
2738 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2740 // If this is an output operand with a matching input operand, look up the
2741 // matching input. If their types mismatch, e.g. one is an integer, the
2742 // other is floating point, or their sizes are different, flag it as an
2744 if (OpInfo.hasMatchingInput()) {
2745 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2747 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2748 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2749 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2750 OpInfo.ConstraintVT);
2751 std::pair<unsigned, const TargetRegisterClass *> InputRC =
2752 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2753 Input.ConstraintVT);
2754 if ((OpInfo.ConstraintVT.isInteger() !=
2755 Input.ConstraintVT.isInteger()) ||
2756 (MatchRC.second != InputRC.second)) {
2757 report_fatal_error("Unsupported asm: input constraint"
2758 " with a matching output constraint of"
2759 " incompatible type!");
2765 return ConstraintOperands;
2768 /// Return an integer indicating how general CT is.
2769 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2771 case TargetLowering::C_Other:
2772 case TargetLowering::C_Unknown:
2774 case TargetLowering::C_Register:
2776 case TargetLowering::C_RegisterClass:
2778 case TargetLowering::C_Memory:
2781 llvm_unreachable("Invalid constraint type");
2784 /// Examine constraint type and operand type and determine a weight value.
2785 /// This object must already have been set up with the operand type
2786 /// and the current alternative constraint selected.
2787 TargetLowering::ConstraintWeight
2788 TargetLowering::getMultipleConstraintMatchWeight(
2789 AsmOperandInfo &info, int maIndex) const {
2790 InlineAsm::ConstraintCodeVector *rCodes;
2791 if (maIndex >= (int)info.multipleAlternatives.size())
2792 rCodes = &info.Codes;
2794 rCodes = &info.multipleAlternatives[maIndex].Codes;
2795 ConstraintWeight BestWeight = CW_Invalid;
2797 // Loop over the options, keeping track of the most general one.
2798 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2799 ConstraintWeight weight =
2800 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2801 if (weight > BestWeight)
2802 BestWeight = weight;
2808 /// Examine constraint type and operand type and determine a weight value.
2809 /// This object must already have been set up with the operand type
2810 /// and the current alternative constraint selected.
2811 TargetLowering::ConstraintWeight
2812 TargetLowering::getSingleConstraintMatchWeight(
2813 AsmOperandInfo &info, const char *constraint) const {
2814 ConstraintWeight weight = CW_Invalid;
2815 Value *CallOperandVal = info.CallOperandVal;
2816 // If we don't have a value, we can't do a match,
2817 // but allow it at the lowest weight.
2818 if (!CallOperandVal)
2820 // Look at the constraint type.
2821 switch (*constraint) {
2822 case 'i': // immediate integer.
2823 case 'n': // immediate integer with a known value.
2824 if (isa<ConstantInt>(CallOperandVal))
2825 weight = CW_Constant;
2827 case 's': // non-explicit intregal immediate.
2828 if (isa<GlobalValue>(CallOperandVal))
2829 weight = CW_Constant;
2831 case 'E': // immediate float if host format.
2832 case 'F': // immediate float.
2833 if (isa<ConstantFP>(CallOperandVal))
2834 weight = CW_Constant;
2836 case '<': // memory operand with autodecrement.
2837 case '>': // memory operand with autoincrement.
2838 case 'm': // memory operand.
2839 case 'o': // offsettable memory operand
2840 case 'V': // non-offsettable memory operand
2843 case 'r': // general register.
2844 case 'g': // general register, memory operand or immediate integer.
2845 // note: Clang converts "g" to "imr".
2846 if (CallOperandVal->getType()->isIntegerTy())
2847 weight = CW_Register;
2849 case 'X': // any operand.
2851 weight = CW_Default;
2857 /// If there are multiple different constraints that we could pick for this
2858 /// operand (e.g. "imr") try to pick the 'best' one.
2859 /// This is somewhat tricky: constraints fall into four classes:
2860 /// Other -> immediates and magic values
2861 /// Register -> one specific register
2862 /// RegisterClass -> a group of regs
2863 /// Memory -> memory
2864 /// Ideally, we would pick the most specific constraint possible: if we have
2865 /// something that fits into a register, we would pick it. The problem here
2866 /// is that if we have something that could either be in a register or in
2867 /// memory that use of the register could cause selection of *other*
2868 /// operands to fail: they might only succeed if we pick memory. Because of
2869 /// this the heuristic we use is:
2871 /// 1) If there is an 'other' constraint, and if the operand is valid for
2872 /// that constraint, use it. This makes us take advantage of 'i'
2873 /// constraints when available.
2874 /// 2) Otherwise, pick the most general constraint present. This prefers
2875 /// 'm' over 'r', for example.
2877 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2878 const TargetLowering &TLI,
2879 SDValue Op, SelectionDAG *DAG) {
2880 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2881 unsigned BestIdx = 0;
2882 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2883 int BestGenerality = -1;
2885 // Loop over the options, keeping track of the most general one.
2886 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2887 TargetLowering::ConstraintType CType =
2888 TLI.getConstraintType(OpInfo.Codes[i]);
2890 // If this is an 'other' constraint, see if the operand is valid for it.
2891 // For example, on X86 we might have an 'rI' constraint. If the operand
2892 // is an integer in the range [0..31] we want to use I (saving a load
2893 // of a register), otherwise we must use 'r'.
2894 if (CType == TargetLowering::C_Other && Op.getNode()) {
2895 assert(OpInfo.Codes[i].size() == 1 &&
2896 "Unhandled multi-letter 'other' constraint");
2897 std::vector<SDValue> ResultOps;
2898 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2900 if (!ResultOps.empty()) {
2907 // Things with matching constraints can only be registers, per gcc
2908 // documentation. This mainly affects "g" constraints.
2909 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2912 // This constraint letter is more general than the previous one, use it.
2913 int Generality = getConstraintGenerality(CType);
2914 if (Generality > BestGenerality) {
2917 BestGenerality = Generality;
2921 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2922 OpInfo.ConstraintType = BestType;
2925 /// Determines the constraint code and constraint type to use for the specific
2926 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2927 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2929 SelectionDAG *DAG) const {
2930 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2932 // Single-letter constraints ('r') are very common.
2933 if (OpInfo.Codes.size() == 1) {
2934 OpInfo.ConstraintCode = OpInfo.Codes[0];
2935 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2937 ChooseConstraint(OpInfo, *this, Op, DAG);
2940 // 'X' matches anything.
2941 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2942 // Labels and constants are handled elsewhere ('X' is the only thing
2943 // that matches labels). For Functions, the type here is the type of
2944 // the result, which is not what we want to look at; leave them alone.
2945 Value *v = OpInfo.CallOperandVal;
2946 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2947 OpInfo.CallOperandVal = v;
2951 // Otherwise, try to resolve it to something we know about by looking at
2952 // the actual operand type.
2953 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2954 OpInfo.ConstraintCode = Repl;
2955 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2960 /// \brief Given an exact SDIV by a constant, create a multiplication
2961 /// with the multiplicative inverse of the constant.
2962 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2963 const SDLoc &dl, SelectionDAG &DAG,
2964 std::vector<SDNode *> &Created) {
2965 assert(d != 0 && "Division by zero!");
2967 // Shift the value upfront if it is even, so the LSB is one.
2968 unsigned ShAmt = d.countTrailingZeros();
2970 // TODO: For UDIV use SRL instead of SRA.
2972 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2973 DAG.getDataLayout()));
2975 Flags.setExact(true);
2976 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
2977 Created.push_back(Op1.getNode());
2981 // Calculate the multiplicative inverse, using Newton's method.
2983 while ((t = d*xn) != 1)
2984 xn *= APInt(d.getBitWidth(), 2) - t;
2986 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2987 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2988 Created.push_back(Mul.getNode());
2992 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2994 std::vector<SDNode *> *Created) const {
2995 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2997 if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2998 return SDValue(N,0); // Lower SDIV as SDIV
3002 /// \brief Given an ISD::SDIV node expressing a divide by constant,
3003 /// return a DAG expression to select that will generate the same value by
3004 /// multiplying by a magic number.
3005 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3006 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
3007 SelectionDAG &DAG, bool IsAfterLegalization,
3008 std::vector<SDNode *> *Created) const {
3009 assert(Created && "No vector to hold sdiv ops.");
3011 EVT VT = N->getValueType(0);
3014 // Check to see if we can do this.
3015 // FIXME: We should be more aggressive here.
3016 if (!isTypeLegal(VT))
3019 // If the sdiv has an 'exact' bit we can use a simpler lowering.
3020 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
3021 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
3023 APInt::ms magics = Divisor.magic();
3025 // Multiply the numerator (operand 0) by the magic value
3026 // FIXME: We should support doing a MUL in a wider type
3028 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
3029 isOperationLegalOrCustom(ISD::MULHS, VT))
3030 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3031 DAG.getConstant(magics.m, dl, VT));
3032 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
3033 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3034 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3036 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3038 return SDValue(); // No mulhs or equvialent
3039 // If d > 0 and m < 0, add the numerator
3040 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
3041 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3042 Created->push_back(Q.getNode());
3044 // If d < 0 and m > 0, subtract the numerator.
3045 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
3046 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3047 Created->push_back(Q.getNode());
3049 auto &DL = DAG.getDataLayout();
3050 // Shift right algebraic if shift value is nonzero
3053 ISD::SRA, dl, VT, Q,
3054 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3055 Created->push_back(Q.getNode());
3057 // Extract the sign bit and add it to the quotient
3059 DAG.getNode(ISD::SRL, dl, VT, Q,
3060 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
3061 getShiftAmountTy(Q.getValueType(), DL)));
3062 Created->push_back(T.getNode());
3063 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3066 /// \brief Given an ISD::UDIV node expressing a divide by constant,
3067 /// return a DAG expression to select that will generate the same value by
3068 /// multiplying by a magic number.
3069 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3070 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
3071 SelectionDAG &DAG, bool IsAfterLegalization,
3072 std::vector<SDNode *> *Created) const {
3073 assert(Created && "No vector to hold udiv ops.");
3075 EVT VT = N->getValueType(0);
3077 auto &DL = DAG.getDataLayout();
3079 // Check to see if we can do this.
3080 // FIXME: We should be more aggressive here.
3081 if (!isTypeLegal(VT))
3084 // FIXME: We should use a narrower constant when the upper
3085 // bits are known to be zero.
3086 APInt::mu magics = Divisor.magicu();
3088 SDValue Q = N->getOperand(0);
3090 // If the divisor is even, we can avoid using the expensive fixup by shifting
3091 // the divided value upfront.
3092 if (magics.a != 0 && !Divisor[0]) {
3093 unsigned Shift = Divisor.countTrailingZeros();
3095 ISD::SRL, dl, VT, Q,
3096 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
3097 Created->push_back(Q.getNode());
3099 // Get magic number for the shifted divisor.
3100 magics = Divisor.lshr(Shift).magicu(Shift);
3101 assert(magics.a == 0 && "Should use cheap fixup now");
3104 // Multiply the numerator (operand 0) by the magic value
3105 // FIXME: We should support doing a MUL in a wider type
3106 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
3107 isOperationLegalOrCustom(ISD::MULHU, VT))
3108 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
3109 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
3110 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3111 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3112 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3114 return SDValue(); // No mulhu or equivalent
3116 Created->push_back(Q.getNode());
3118 if (magics.a == 0) {
3119 assert(magics.s < Divisor.getBitWidth() &&
3120 "We shouldn't generate an undefined shift!");
3122 ISD::SRL, dl, VT, Q,
3123 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3125 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3126 Created->push_back(NPQ.getNode());
3128 ISD::SRL, dl, VT, NPQ,
3129 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
3130 Created->push_back(NPQ.getNode());
3131 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3132 Created->push_back(NPQ.getNode());
3134 ISD::SRL, dl, VT, NPQ,
3135 DAG.getConstant(magics.s - 1, dl,
3136 getShiftAmountTy(NPQ.getValueType(), DL)));
3140 bool TargetLowering::
3141 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
3142 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
3143 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
3144 "be a constant integer");
3151 //===----------------------------------------------------------------------===//
3152 // Legalization Utilities
3153 //===----------------------------------------------------------------------===//
3155 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
3156 SDValue LHS, SDValue RHS,
3157 SmallVectorImpl<SDValue> &Result,
3158 EVT HiLoVT, SelectionDAG &DAG,
3159 MulExpansionKind Kind, SDValue LL,
3160 SDValue LH, SDValue RL, SDValue RH) const {
3161 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
3162 Opcode == ISD::SMUL_LOHI);
3164 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
3165 isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
3166 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
3167 isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
3168 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3169 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
3170 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3171 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3173 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
3176 unsigned OuterBitSize = VT.getScalarSizeInBits();
3177 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
3178 unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
3179 unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
3181 // LL, LH, RL, and RH must be either all NULL or all set to a value.
3182 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3183 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3185 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
3186 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
3187 bool Signed) -> bool {
3188 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
3189 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
3190 Hi = SDValue(Lo.getNode(), 1);
3193 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
3194 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
3195 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
3203 if (!LL.getNode() && !RL.getNode() &&
3204 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3205 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
3206 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
3212 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3213 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
3214 DAG.MaskedValueIsZero(RHS, HighMask)) {
3215 // The inputs are both zero-extended.
3216 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
3217 Result.push_back(Lo);
3218 Result.push_back(Hi);
3219 if (Opcode != ISD::MUL) {
3220 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3221 Result.push_back(Zero);
3222 Result.push_back(Zero);
3228 if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
3229 RHSSB > InnerBitSize) {
3230 // The input values are both sign-extended.
3231 // TODO non-MUL case?
3232 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
3233 Result.push_back(Lo);
3234 Result.push_back(Hi);
3239 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
3240 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
3241 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
3242 // FIXME getShiftAmountTy does not always return a sensible result when VT
3243 // is an illegal type, and so the type may be too small to fit the shift
3244 // amount. Override it with i32. The shift will have to be legalized.
3245 ShiftAmountTy = MVT::i32;
3247 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
3249 if (!LH.getNode() && !RH.getNode() &&
3250 isOperationLegalOrCustom(ISD::SRL, VT) &&
3251 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3252 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
3253 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3254 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
3255 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3261 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
3264 Result.push_back(Lo);
3266 if (Opcode == ISD::MUL) {
3267 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3268 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3269 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3270 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3271 Result.push_back(Hi);
3275 // Compute the full width result.
3276 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
3277 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3278 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3279 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3280 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
3283 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3284 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
3287 // This is effectively the add part of a multiply-add of half-sized operands,
3288 // so it cannot overflow.
3289 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3291 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
3294 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
3297 SDValue Carry = Next.getValue(1);
3298 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3299 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3301 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
3304 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3305 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
3307 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3309 if (Opcode == ISD::SMUL_LOHI) {
3310 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3311 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
3312 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
3314 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3315 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
3316 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
3319 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3320 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3321 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3325 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3326 SelectionDAG &DAG, MulExpansionKind Kind,
3327 SDValue LL, SDValue LH, SDValue RL,
3329 SmallVector<SDValue, 2> Result;
3330 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
3331 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
3332 DAG, Kind, LL, LH, RL, RH);
3334 assert(Result.size() == 2);
3341 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3342 SelectionDAG &DAG) const {
3343 EVT VT = Node->getOperand(0).getValueType();
3344 EVT NVT = Node->getValueType(0);
3345 SDLoc dl(SDValue(Node, 0));
3347 // FIXME: Only f32 to i64 conversions are supported.
3348 if (VT != MVT::f32 || NVT != MVT::i64)
3351 // Expand f32 -> i64 conversion
3352 // This algorithm comes from compiler-rt's implementation of fixsfdi:
3353 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3354 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3355 VT.getSizeInBits());
3356 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3357 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3358 SDValue Bias = DAG.getConstant(127, dl, IntVT);
3359 SDValue SignMask = DAG.getConstant(APInt::getSignMask(VT.getSizeInBits()), dl,
3361 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3362 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
3364 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3366 auto &DL = DAG.getDataLayout();
3367 SDValue ExponentBits = DAG.getNode(
3368 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3369 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
3370 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3372 SDValue Sign = DAG.getNode(
3373 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3374 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
3375 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3377 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3378 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3379 DAG.getConstant(0x00800000, dl, IntVT));
3381 R = DAG.getZExtOrTrunc(R, dl, NVT);
3383 R = DAG.getSelectCC(
3384 dl, Exponent, ExponentLoBit,
3385 DAG.getNode(ISD::SHL, dl, NVT, R,
3387 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3388 dl, getShiftAmountTy(IntVT, DL))),
3389 DAG.getNode(ISD::SRL, dl, NVT, R,
3391 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3392 dl, getShiftAmountTy(IntVT, DL))),
3395 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3396 DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3399 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3400 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3404 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3405 SelectionDAG &DAG) const {
3407 SDValue Chain = LD->getChain();
3408 SDValue BasePTR = LD->getBasePtr();
3409 EVT SrcVT = LD->getMemoryVT();
3410 ISD::LoadExtType ExtType = LD->getExtensionType();
3412 unsigned NumElem = SrcVT.getVectorNumElements();
3414 EVT SrcEltVT = SrcVT.getScalarType();
3415 EVT DstEltVT = LD->getValueType(0).getScalarType();
3417 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3418 assert(SrcEltVT.isByteSized());
3420 EVT PtrVT = BasePTR.getValueType();
3422 SmallVector<SDValue, 8> Vals;
3423 SmallVector<SDValue, 8> LoadChains;
3425 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3426 SDValue ScalarLoad =
3427 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3428 LD->getPointerInfo().getWithOffset(Idx * Stride),
3429 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3430 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3432 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3433 DAG.getConstant(Stride, SL, PtrVT));
3435 Vals.push_back(ScalarLoad.getValue(0));
3436 LoadChains.push_back(ScalarLoad.getValue(1));
3439 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3440 SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
3442 return DAG.getMergeValues({ Value, NewChain }, SL);
3445 // FIXME: This relies on each element having a byte size, otherwise the stride
3446 // is 0 and just overwrites the same location. ExpandStore currently expects
3447 // this broken behavior.
3448 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3449 SelectionDAG &DAG) const {
3452 SDValue Chain = ST->getChain();
3453 SDValue BasePtr = ST->getBasePtr();
3454 SDValue Value = ST->getValue();
3455 EVT StVT = ST->getMemoryVT();
3457 // The type of the data we want to save
3458 EVT RegVT = Value.getValueType();
3459 EVT RegSclVT = RegVT.getScalarType();
3461 // The type of data as saved in memory.
3462 EVT MemSclVT = StVT.getScalarType();
3464 EVT PtrVT = BasePtr.getValueType();
3466 // Store Stride in bytes
3467 unsigned Stride = MemSclVT.getSizeInBits() / 8;
3468 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3469 unsigned NumElem = StVT.getVectorNumElements();
3471 // Extract each of the elements from the original vector and save them into
3472 // memory individually.
3473 SmallVector<SDValue, 8> Stores;
3474 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3475 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3476 DAG.getConstant(Idx, SL, IdxVT));
3478 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3479 DAG.getConstant(Idx * Stride, SL, PtrVT));
3481 // This scalar TruncStore may be illegal, but we legalize it later.
3482 SDValue Store = DAG.getTruncStore(
3483 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3484 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3485 ST->getMemOperand()->getFlags(), ST->getAAInfo());
3487 Stores.push_back(Store);
3490 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3493 std::pair<SDValue, SDValue>
3494 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3495 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3496 "unaligned indexed loads not implemented!");
3497 SDValue Chain = LD->getChain();
3498 SDValue Ptr = LD->getBasePtr();
3499 EVT VT = LD->getValueType(0);
3500 EVT LoadedVT = LD->getMemoryVT();
3502 if (VT.isFloatingPoint() || VT.isVector()) {
3503 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3504 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3505 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3506 // Scalarize the load and let the individual components be handled.
3507 SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3508 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3511 // Expand to a (misaligned) integer load of the same size,
3512 // then bitconvert to floating point or vector.
3513 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3514 LD->getMemOperand());
3515 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3517 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3518 ISD::ANY_EXTEND, dl, VT, Result);
3520 return std::make_pair(Result, newLoad.getValue(1));
3523 // Copy the value to a (aligned) stack slot using (unaligned) integer
3524 // loads and stores, then do a (aligned) load from the stack slot.
3525 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3526 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3527 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3528 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3530 // Make sure the stack slot is also aligned for the register type.
3531 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3533 SmallVector<SDValue, 8> Stores;
3534 SDValue StackPtr = StackBase;
3535 unsigned Offset = 0;
3537 EVT PtrVT = Ptr.getValueType();
3538 EVT StackPtrVT = StackPtr.getValueType();
3540 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3541 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3543 // Do all but one copies using the full register width.
3544 for (unsigned i = 1; i < NumRegs; i++) {
3545 // Load one integer register's worth from the original location.
3546 SDValue Load = DAG.getLoad(
3547 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3548 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3550 // Follow the load with a store to the stack slot. Remember the store.
3551 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3552 MachinePointerInfo()));
3553 // Increment the pointers.
3555 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3556 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3560 // The last copy may be partial. Do an extending load.
3561 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3562 8 * (LoadedBytes - Offset));
3564 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3565 LD->getPointerInfo().getWithOffset(Offset), MemVT,
3566 MinAlign(LD->getAlignment(), Offset),
3567 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3568 // Follow the load with a store to the stack slot. Remember the store.
3569 // On big-endian machines this requires a truncating store to ensure
3570 // that the bits end up in the right place.
3571 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3572 MachinePointerInfo(), MemVT));
3574 // The order of the stores doesn't matter - say it with a TokenFactor.
3575 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3577 // Finally, perform the original load only redirected to the stack slot.
3578 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3579 MachinePointerInfo(), LoadedVT);
3581 // Callers expect a MERGE_VALUES node.
3582 return std::make_pair(Load, TF);
3585 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3586 "Unaligned load of unsupported type.");
3588 // Compute the new VT that is half the size of the old one. This is an
3590 unsigned NumBits = LoadedVT.getSizeInBits();
3592 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3595 unsigned Alignment = LD->getAlignment();
3596 unsigned IncrementSize = NumBits / 8;
3597 ISD::LoadExtType HiExtType = LD->getExtensionType();
3599 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3600 if (HiExtType == ISD::NON_EXTLOAD)
3601 HiExtType = ISD::ZEXTLOAD;
3603 // Load the value in two parts
3605 if (DAG.getDataLayout().isLittleEndian()) {
3606 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3607 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3609 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3610 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3611 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3612 LD->getPointerInfo().getWithOffset(IncrementSize),
3613 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3614 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3616 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3617 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3619 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3620 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3621 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3622 LD->getPointerInfo().getWithOffset(IncrementSize),
3623 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3624 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3627 // aggregate the two parts
3628 SDValue ShiftAmount =
3629 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3630 DAG.getDataLayout()));
3631 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3632 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3634 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3637 return std::make_pair(Result, TF);
3640 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3641 SelectionDAG &DAG) const {
3642 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3643 "unaligned indexed stores not implemented!");
3644 SDValue Chain = ST->getChain();
3645 SDValue Ptr = ST->getBasePtr();
3646 SDValue Val = ST->getValue();
3647 EVT VT = Val.getValueType();
3648 int Alignment = ST->getAlignment();
3651 if (ST->getMemoryVT().isFloatingPoint() ||
3652 ST->getMemoryVT().isVector()) {
3653 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3654 if (isTypeLegal(intVT)) {
3655 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3656 // Scalarize the store and let the individual components be handled.
3657 SDValue Result = scalarizeVectorStore(ST, DAG);
3661 // Expand to a bitconvert of the value to the integer type of the
3662 // same size, then a (misaligned) int store.
3663 // FIXME: Does not handle truncating floating point stores!
3664 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3665 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3666 Alignment, ST->getMemOperand()->getFlags());
3669 // Do a (aligned) store to a stack slot, then copy from the stack slot
3670 // to the final destination using (unaligned) integer loads and stores.
3671 EVT StoredVT = ST->getMemoryVT();
3673 getRegisterType(*DAG.getContext(),
3674 EVT::getIntegerVT(*DAG.getContext(),
3675 StoredVT.getSizeInBits()));
3676 EVT PtrVT = Ptr.getValueType();
3677 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3678 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3679 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3681 // Make sure the stack slot is also aligned for the register type.
3682 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3684 // Perform the original store, only redirected to the stack slot.
3685 SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
3686 MachinePointerInfo(), StoredVT);
3688 EVT StackPtrVT = StackPtr.getValueType();
3690 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3691 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3692 SmallVector<SDValue, 8> Stores;
3693 unsigned Offset = 0;
3695 // Do all but one copies using the full register width.
3696 for (unsigned i = 1; i < NumRegs; i++) {
3697 // Load one integer register's worth from the stack slot.
3699 DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
3700 // Store it to the final location. Remember the store.
3701 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3702 ST->getPointerInfo().getWithOffset(Offset),
3703 MinAlign(ST->getAlignment(), Offset),
3704 ST->getMemOperand()->getFlags()));
3705 // Increment the pointers.
3707 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3708 StackPtr, StackPtrIncrement);
3709 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3712 // The last store may be partial. Do a truncating store. On big-endian
3713 // machines this requires an extending load from the stack slot to ensure
3714 // that the bits are in the right place.
3715 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3716 8 * (StoredBytes - Offset));
3718 // Load from the stack slot.
3719 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3720 MachinePointerInfo(), MemVT);
3723 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3724 ST->getPointerInfo().getWithOffset(Offset), MemVT,
3725 MinAlign(ST->getAlignment(), Offset),
3726 ST->getMemOperand()->getFlags(), ST->getAAInfo()));
3727 // The order of the stores doesn't matter - say it with a TokenFactor.
3728 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3732 assert(ST->getMemoryVT().isInteger() &&
3733 !ST->getMemoryVT().isVector() &&
3734 "Unaligned store of unknown type.");
3735 // Get the half-size VT
3736 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3737 int NumBits = NewStoredVT.getSizeInBits();
3738 int IncrementSize = NumBits / 8;
3740 // Divide the stored value in two parts.
3741 SDValue ShiftAmount =
3742 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3743 DAG.getDataLayout()));
3745 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3747 // Store the two parts
3748 SDValue Store1, Store2;
3749 Store1 = DAG.getTruncStore(Chain, dl,
3750 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3751 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
3752 ST->getMemOperand()->getFlags());
3754 EVT PtrVT = Ptr.getValueType();
3755 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3756 DAG.getConstant(IncrementSize, dl, PtrVT));
3757 Alignment = MinAlign(Alignment, IncrementSize);
3758 Store2 = DAG.getTruncStore(
3759 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3760 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
3761 ST->getMemOperand()->getFlags(), ST->getAAInfo());
3764 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3769 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
3770 const SDLoc &DL, EVT DataVT,
3772 bool IsCompressedMemory) const {
3774 EVT AddrVT = Addr.getValueType();
3775 EVT MaskVT = Mask.getValueType();
3776 assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
3777 "Incompatible types of Data and Mask");
3778 if (IsCompressedMemory) {
3779 // Incrementing the pointer according to number of '1's in the mask.
3780 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
3781 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
3782 if (MaskIntVT.getSizeInBits() < 32) {
3783 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
3784 MaskIntVT = MVT::i32;
3787 // Count '1's with POPCNT.
3788 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
3789 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
3790 // Scale is an element size in bytes.
3791 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
3793 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
3795 Increment = DAG.getConstant(DataVT.getSizeInBits() / 8, DL, AddrVT);
3797 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
3800 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
3804 if (isa<ConstantSDNode>(Idx))
3807 EVT IdxVT = Idx.getValueType();
3808 unsigned NElts = VecVT.getVectorNumElements();
3809 if (isPowerOf2_32(NElts)) {
3810 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
3812 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
3813 DAG.getConstant(Imm, dl, IdxVT));
3816 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
3817 DAG.getConstant(NElts - 1, dl, IdxVT));
3820 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
3821 SDValue VecPtr, EVT VecVT,
3822 SDValue Index) const {
3824 // Make sure the index type is big enough to compute in.
3825 Index = DAG.getZExtOrTrunc(Index, dl, getPointerTy(DAG.getDataLayout()));
3827 EVT EltVT = VecVT.getVectorElementType();
3829 // Calculate the element offset and add it to the pointer.
3830 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
3831 assert(EltSize * 8 == EltVT.getSizeInBits() &&
3832 "Converting bits to bytes lost precision");
3834 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
3836 EVT IdxVT = Index.getValueType();
3838 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
3839 DAG.getConstant(EltSize, dl, IdxVT));
3840 return DAG.getNode(ISD::ADD, dl, IdxVT, Index, VecPtr);
3843 //===----------------------------------------------------------------------===//
3844 // Implementation of Emulated TLS Model
3845 //===----------------------------------------------------------------------===//
3847 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3848 SelectionDAG &DAG) const {
3849 // Access to address of TLS varialbe xyz is lowered to a function call:
3850 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3851 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3852 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3857 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3858 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3859 StringRef EmuTlsVarName(NameString);
3860 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
3861 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
3862 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3863 Entry.Ty = VoidPtrType;
3864 Args.push_back(Entry);
3866 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3868 TargetLowering::CallLoweringInfo CLI(DAG);
3869 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3870 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
3871 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3873 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3874 // At last for X86 targets, maybe good for other targets too?
3875 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3876 MFI.setAdjustsStack(true); // Is this only for X86 target?
3877 MFI.setHasCalls(true);
3879 assert((GA->getOffset() == 0) &&
3880 "Emulated TLS must have zero offset in GlobalAddressSDNode");
3881 return CallResult.first;
3884 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
3885 SelectionDAG &DAG) const {
3886 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
3889 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3891 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3892 if (C->isNullValue() && CC == ISD::SETEQ) {
3893 EVT VT = Op.getOperand(0).getValueType();
3894 SDValue Zext = Op.getOperand(0);
3895 if (VT.bitsLT(MVT::i32)) {
3897 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
3899 unsigned Log2b = Log2_32(VT.getSizeInBits());
3900 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
3901 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
3902 DAG.getConstant(Log2b, dl, MVT::i32));
3903 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);