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::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
346 TargetLoweringOpt &TLO) const {
347 SelectionDAG &DAG = TLO.DAG;
349 unsigned Opcode = Op.getOpcode();
351 // Do target-specific constant optimization.
352 if (targetShrinkDemandedConstant(Op, Demanded, TLO))
353 return TLO.New.getNode();
355 // FIXME: ISD::SELECT, ISD::SELECT_CC
362 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
366 // If this is a 'not' op, don't touch it because that's a canonical form.
367 const APInt &C = Op1C->getAPIntValue();
368 if (Opcode == ISD::XOR && (C | ~Demanded).isAllOnesValue())
371 if (C.intersects(~Demanded)) {
372 EVT VT = Op.getValueType();
373 SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
374 SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
375 return TLO.CombineTo(Op, NewOp);
385 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
386 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
387 /// generalized for targets with other types of implicit widening casts.
388 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
389 const APInt &Demanded,
390 TargetLoweringOpt &TLO) const {
391 assert(Op.getNumOperands() == 2 &&
392 "ShrinkDemandedOp only supports binary operators!");
393 assert(Op.getNode()->getNumValues() == 1 &&
394 "ShrinkDemandedOp only supports nodes with one result!");
396 SelectionDAG &DAG = TLO.DAG;
399 // Early return, as this function cannot handle vector types.
400 if (Op.getValueType().isVector())
403 // Don't do this if the node has another user, which may require the
405 if (!Op.getNode()->hasOneUse())
408 // Search for the smallest integer type with free casts to and from
409 // Op's type. For expedience, just check power-of-2 integer types.
410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
411 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
412 unsigned SmallVTBits = DemandedSize;
413 if (!isPowerOf2_32(SmallVTBits))
414 SmallVTBits = NextPowerOf2(SmallVTBits);
415 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
416 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
417 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
418 TLI.isZExtFree(SmallVT, Op.getValueType())) {
419 // We found a type with free casts.
420 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
421 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
422 Op.getNode()->getOperand(0)),
423 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
424 Op.getNode()->getOperand(1)));
425 bool NeedZext = DemandedSize > SmallVTBits;
426 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
427 dl, Op.getValueType(), X);
428 return TLO.CombineTo(Op, Z);
435 TargetLowering::SimplifyDemandedBits(SDNode *User, unsigned OpIdx,
436 const APInt &Demanded,
437 DAGCombinerInfo &DCI,
438 TargetLoweringOpt &TLO) const {
439 SDValue Op = User->getOperand(OpIdx);
440 APInt KnownZero, KnownOne;
442 if (!SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne,
447 // Old will not always be the same as Op. For example:
449 // Demanded = 0xffffff
450 // Op = i64 truncate (i32 and x, 0xffffff)
451 // In this case simplify demand bits will want to replace the 'and' node
452 // with the value 'x', which will give us:
453 // Old = i32 and x, 0xffffff
455 if (TLO.Old.hasOneUse()) {
456 // For the one use case, we just commit the change.
457 DCI.CommitTargetLoweringOpt(TLO);
461 // If Old has more than one use then it must be Op, because the
462 // AssumeSingleUse flag is not propogated to recursive calls of
463 // SimplifyDemanded bits, so the only node with multiple use that
464 // it will attempt to combine will be opt.
465 assert(TLO.Old == Op);
467 SmallVector <SDValue, 4> NewOps;
468 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
470 NewOps.push_back(TLO.New);
473 NewOps.push_back(User->getOperand(i));
475 TLO.DAG.UpdateNodeOperands(User, NewOps);
476 // Op has less users now, so we may be able to perform additional combines
478 DCI.AddToWorklist(Op.getNode());
479 // User's operands have been updated, so we may be able to do new combines
481 DCI.AddToWorklist(User);
485 bool TargetLowering::SimplifyDemandedBits(SDValue Op, APInt &DemandedMask,
486 DAGCombinerInfo &DCI) const {
488 SelectionDAG &DAG = DCI.DAG;
489 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
490 !DCI.isBeforeLegalizeOps());
491 APInt KnownZero, KnownOne;
493 bool Simplified = SimplifyDemandedBits(Op, DemandedMask, KnownZero, KnownOne,
496 DCI.CommitTargetLoweringOpt(TLO);
500 /// Look at Op. At this point, we know that only the DemandedMask bits of the
501 /// result of Op are ever used downstream. If we can use this information to
502 /// simplify Op, create a new simplified DAG node and return true, returning the
503 /// original and new nodes in Old and New. Otherwise, analyze the expression and
504 /// return a mask of KnownOne and KnownZero bits for the expression (used to
505 /// simplify the caller). The KnownZero/One bits may only be accurate for those
506 /// bits in the DemandedMask.
507 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
508 const APInt &DemandedMask,
511 TargetLoweringOpt &TLO,
513 bool AssumeSingleUse) const {
514 unsigned BitWidth = DemandedMask.getBitWidth();
515 assert(Op.getScalarValueSizeInBits() == BitWidth &&
516 "Mask size mismatches value type size!");
517 APInt NewMask = DemandedMask;
519 auto &DL = TLO.DAG.getDataLayout();
521 // Don't know anything.
522 KnownZero = KnownOne = APInt(BitWidth, 0);
524 // Other users may use these bits.
525 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
527 // If not at the root, Just compute the KnownZero/KnownOne bits to
528 // simplify things downstream.
529 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
532 // If this is the root being simplified, allow it to have multiple uses,
533 // just set the NewMask to all bits.
534 NewMask = APInt::getAllOnesValue(BitWidth);
535 } else if (DemandedMask == 0) {
536 // Not demanding any bits from Op.
538 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
540 } else if (Depth == 6) { // Limit search depth.
544 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
545 switch (Op.getOpcode()) {
547 // We know all of the bits for a constant!
548 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
549 KnownZero = ~KnownOne;
550 return false; // Don't fall through, will infinitely loop.
551 case ISD::BUILD_VECTOR:
552 // Collect the known bits that are shared by every constant vector element.
553 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
554 for (SDValue SrcOp : Op->ops()) {
555 if (!isa<ConstantSDNode>(SrcOp)) {
556 // We can only handle all constant values - bail out with no known bits.
557 KnownZero = KnownOne = APInt(BitWidth, 0);
560 KnownOne2 = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
561 KnownZero2 = ~KnownOne2;
563 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
564 if (KnownOne2.getBitWidth() != BitWidth) {
565 assert(KnownOne2.getBitWidth() > BitWidth &&
566 KnownZero2.getBitWidth() > BitWidth &&
567 "Expected BUILD_VECTOR implicit truncation");
568 KnownOne2 = KnownOne2.trunc(BitWidth);
569 KnownZero2 = KnownZero2.trunc(BitWidth);
572 // Known bits are the values that are shared by every element.
573 // TODO: support per-element known bits.
574 KnownOne &= KnownOne2;
575 KnownZero &= KnownZero2;
577 return false; // Don't fall through, will infinitely loop.
579 // If the RHS is a constant, check to see if the LHS would be zero without
580 // using the bits from the RHS. Below, we use knowledge about the RHS to
581 // simplify the LHS, here we're using information from the LHS to simplify
583 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op.getOperand(1))) {
584 SDValue Op0 = Op.getOperand(0);
585 APInt LHSZero, LHSOne;
586 // Do not increment Depth here; that can cause an infinite loop.
587 TLO.DAG.computeKnownBits(Op0, LHSZero, LHSOne, Depth);
588 // If the LHS already has zeros where RHSC does, this and is dead.
589 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
590 return TLO.CombineTo(Op, Op0);
592 // If any of the set bits in the RHS are known zero on the LHS, shrink
594 if (ShrinkDemandedConstant(Op, ~LHSZero & NewMask, TLO))
597 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
598 // constant, but if this 'and' is only clearing bits that were just set by
599 // the xor, then this 'and' can be eliminated by shrinking the mask of
600 // the xor. For example, for a 32-bit X:
601 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
602 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
603 LHSOne == ~RHSC->getAPIntValue()) {
604 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, Op.getValueType(),
605 Op0.getOperand(0), Op.getOperand(1));
606 return TLO.CombineTo(Op, Xor);
610 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
611 KnownOne, TLO, Depth+1))
613 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
614 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
615 KnownZero2, KnownOne2, TLO, Depth+1))
617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
619 // If all of the demanded bits are known one on one side, return the other.
620 // These bits cannot contribute to the result of the 'and'.
621 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
622 return TLO.CombineTo(Op, Op.getOperand(0));
623 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
624 return TLO.CombineTo(Op, Op.getOperand(1));
625 // If all of the demanded bits in the inputs are known zeros, return zero.
626 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
627 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
628 // If the RHS is a constant, see if we can simplify it.
629 if (ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask, TLO))
631 // If the operation can be done in a smaller type, do so.
632 if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
635 // Output known-1 bits are only known if set in both the LHS & RHS.
636 KnownOne &= KnownOne2;
637 // Output known-0 are known to be clear if zero in either the LHS | RHS.
638 KnownZero |= KnownZero2;
641 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
642 KnownOne, TLO, Depth+1))
644 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
645 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
646 KnownZero2, KnownOne2, TLO, Depth+1))
648 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
650 // If all of the demanded bits are known zero on one side, return the other.
651 // These bits cannot contribute to the result of the 'or'.
652 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
653 return TLO.CombineTo(Op, Op.getOperand(0));
654 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
655 return TLO.CombineTo(Op, Op.getOperand(1));
656 // If all of the potentially set bits on one side are known to be set on
657 // the other side, just use the 'other' side.
658 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
659 return TLO.CombineTo(Op, Op.getOperand(0));
660 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
661 return TLO.CombineTo(Op, Op.getOperand(1));
662 // If the RHS is a constant, see if we can simplify it.
663 if (ShrinkDemandedConstant(Op, NewMask, TLO))
665 // If the operation can be done in a smaller type, do so.
666 if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
669 // Output known-0 bits are only known if clear in both the LHS & RHS.
670 KnownZero &= KnownZero2;
671 // Output known-1 are known to be set if set in either the LHS | RHS.
672 KnownOne |= KnownOne2;
675 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
676 KnownOne, TLO, Depth+1))
678 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
679 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
680 KnownOne2, TLO, Depth+1))
682 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
684 // If all of the demanded bits are known zero on one side, return the other.
685 // These bits cannot contribute to the result of the 'xor'.
686 if ((KnownZero & NewMask) == NewMask)
687 return TLO.CombineTo(Op, Op.getOperand(0));
688 if ((KnownZero2 & NewMask) == NewMask)
689 return TLO.CombineTo(Op, Op.getOperand(1));
690 // If the operation can be done in a smaller type, do so.
691 if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
694 // If all of the unknown bits are known to be zero on one side or the other
695 // (but not both) turn this into an *inclusive* or.
696 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
697 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
698 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
702 // Output known-0 bits are known if clear or set in both the LHS & RHS.
703 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
704 // Output known-1 are known to be set if set in only one of the LHS, RHS.
705 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
707 // If all of the demanded bits on one side are known, and all of the set
708 // bits on that side are also known to be set on the other side, turn this
709 // into an AND, as we know the bits will be cleared.
710 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
711 // NB: it is okay if more bits are known than are requested
712 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
713 if (KnownOne == KnownOne2) { // set bits are the same on both sides
714 EVT VT = Op.getValueType();
715 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
716 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
717 Op.getOperand(0), ANDC));
721 // If the RHS is a constant, see if we can simplify it.
722 // for XOR, we prefer to force bits to 1 if they will make a -1.
723 // If we can't force bits, try to shrink the constant.
724 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
725 APInt Expanded = C->getAPIntValue() | (~NewMask);
726 // If we can expand it to have all bits set, do it.
727 if (Expanded.isAllOnesValue()) {
728 if (Expanded != C->getAPIntValue()) {
729 EVT VT = Op.getValueType();
730 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
731 TLO.DAG.getConstant(Expanded, dl, VT));
732 return TLO.CombineTo(Op, New);
734 // If it already has all the bits set, nothing to change
735 // but don't shrink either!
736 } else if (ShrinkDemandedConstant(Op, NewMask, TLO)) {
741 KnownZero = std::move(KnownZeroOut);
742 KnownOne = std::move(KnownOneOut);
745 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
746 KnownOne, TLO, Depth+1))
748 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
749 KnownOne2, TLO, Depth+1))
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
754 // If the operands are constants, see if we can simplify them.
755 if (ShrinkDemandedConstant(Op, NewMask, TLO))
758 // Only known if known in both the LHS and RHS.
759 KnownOne &= KnownOne2;
760 KnownZero &= KnownZero2;
763 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
764 KnownOne, TLO, Depth+1))
766 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
767 KnownOne2, TLO, Depth+1))
769 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
770 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
772 // If the operands are constants, see if we can simplify them.
773 if (ShrinkDemandedConstant(Op, NewMask, TLO))
776 // Only known if known in both the LHS and RHS.
777 KnownOne &= KnownOne2;
778 KnownZero &= KnownZero2;
781 SDValue Op0 = Op.getOperand(0);
782 SDValue Op1 = Op.getOperand(1);
783 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
784 // If (1) we only need the sign-bit, (2) the setcc operands are the same
785 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
786 // -1, we may be able to bypass the setcc.
787 if (NewMask.isSignMask() && Op0.getScalarValueSizeInBits() == BitWidth &&
788 getBooleanContents(Op.getValueType()) ==
789 BooleanContent::ZeroOrNegativeOneBooleanContent) {
790 // If we're testing X < 0, then this compare isn't needed - just use X!
791 // FIXME: We're limiting to integer types here, but this should also work
792 // if we don't care about FP signed-zero. The use of SETLT with FP means
793 // that we don't care about NaNs.
794 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
795 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
796 return TLO.CombineTo(Op, Op0);
798 // TODO: Should we check for other forms of sign-bit comparisons?
799 // Examples: X <= -1, X >= 0
801 if (getBooleanContents(Op0.getValueType()) ==
802 TargetLowering::ZeroOrOneBooleanContent &&
804 KnownZero.setBitsFrom(1);
808 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
809 unsigned ShAmt = SA->getZExtValue();
810 SDValue InOp = Op.getOperand(0);
812 // If the shift count is an invalid immediate, don't do anything.
813 if (ShAmt >= BitWidth)
816 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
817 // single shift. We can do this if the bottom bits (which are shifted
818 // out) are never demanded.
819 if (InOp.getOpcode() == ISD::SRL &&
820 isa<ConstantSDNode>(InOp.getOperand(1))) {
821 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
822 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
823 unsigned Opc = ISD::SHL;
831 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
832 EVT VT = Op.getValueType();
833 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
834 InOp.getOperand(0), NewSA));
838 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
839 KnownZero, KnownOne, TLO, Depth+1))
842 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
843 // are not demanded. This will likely allow the anyext to be folded away.
844 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
845 SDValue InnerOp = InOp.getNode()->getOperand(0);
846 EVT InnerVT = InnerOp.getValueType();
847 unsigned InnerBits = InnerVT.getSizeInBits();
848 if (ShAmt < InnerBits && NewMask.getActiveBits() <= InnerBits &&
849 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
850 EVT ShTy = getShiftAmountTy(InnerVT, DL);
851 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
854 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
855 TLO.DAG.getConstant(ShAmt, dl, ShTy));
858 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
861 // Repeat the SHL optimization above in cases where an extension
862 // intervenes: (shl (anyext (shr x, c1)), c2) to
863 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
864 // aren't demanded (as above) and that the shifted upper c1 bits of
865 // x aren't demanded.
866 if (InOp.hasOneUse() &&
867 InnerOp.getOpcode() == ISD::SRL &&
868 InnerOp.hasOneUse() &&
869 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
870 unsigned InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
872 if (InnerShAmt < ShAmt &&
873 InnerShAmt < InnerBits &&
874 NewMask.getActiveBits() <= (InnerBits - InnerShAmt + ShAmt) &&
875 NewMask.countTrailingZeros() >= ShAmt) {
877 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
878 Op.getOperand(1).getValueType());
879 EVT VT = Op.getValueType();
880 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
881 InnerOp.getOperand(0));
882 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
888 KnownZero <<= SA->getZExtValue();
889 KnownOne <<= SA->getZExtValue();
890 // low bits known zero.
891 KnownZero.setLowBits(SA->getZExtValue());
895 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
896 EVT VT = Op.getValueType();
897 unsigned ShAmt = SA->getZExtValue();
898 unsigned VTSize = VT.getSizeInBits();
899 SDValue InOp = Op.getOperand(0);
901 // If the shift count is an invalid immediate, don't do anything.
902 if (ShAmt >= BitWidth)
905 APInt InDemandedMask = (NewMask << ShAmt);
907 // If the shift is exact, then it does demand the low bits (and knows that
909 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
910 InDemandedMask.setLowBits(ShAmt);
912 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
913 // single shift. We can do this if the top bits (which are shifted out)
914 // are never demanded.
915 if (InOp.getOpcode() == ISD::SHL &&
916 isa<ConstantSDNode>(InOp.getOperand(1))) {
917 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
918 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
919 unsigned Opc = ISD::SRL;
927 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
928 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
929 InOp.getOperand(0), NewSA));
933 // Compute the new bits that are at the top now.
934 if (SimplifyDemandedBits(InOp, InDemandedMask,
935 KnownZero, KnownOne, TLO, Depth+1))
937 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
938 KnownZero.lshrInPlace(ShAmt);
939 KnownOne.lshrInPlace(ShAmt);
941 KnownZero.setHighBits(ShAmt); // High bits known zero.
945 // If this is an arithmetic shift right and only the low-bit is set, we can
946 // always convert this into a logical shr, even if the shift amount is
947 // variable. The low bit of the shift cannot be an input sign bit unless
948 // the shift amount is >= the size of the datatype, which is undefined.
950 return TLO.CombineTo(Op,
951 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
952 Op.getOperand(0), Op.getOperand(1)));
954 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
955 EVT VT = Op.getValueType();
956 unsigned ShAmt = SA->getZExtValue();
958 // If the shift count is an invalid immediate, don't do anything.
959 if (ShAmt >= BitWidth)
962 APInt InDemandedMask = (NewMask << ShAmt);
964 // If the shift is exact, then it does demand the low bits (and knows that
966 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
967 InDemandedMask.setLowBits(ShAmt);
969 // If any of the demanded bits are produced by the sign extension, we also
970 // demand the input sign bit.
971 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
972 if (HighBits.intersects(NewMask))
973 InDemandedMask |= APInt::getSignMask(VT.getScalarSizeInBits());
975 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
976 KnownZero, KnownOne, TLO, Depth+1))
978 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
979 KnownZero.lshrInPlace(ShAmt);
980 KnownOne.lshrInPlace(ShAmt);
982 // Handle the sign bit, adjusted to where it is now in the mask.
983 APInt SignMask = APInt::getSignMask(BitWidth).lshr(ShAmt);
985 // If the input sign bit is known to be zero, or if none of the top bits
986 // are demanded, turn this into an unsigned shift right.
987 if (KnownZero.intersects(SignMask) || (HighBits & ~NewMask) == HighBits) {
989 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
990 return TLO.CombineTo(Op,
991 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
992 Op.getOperand(1), &Flags));
995 int Log2 = NewMask.exactLogBase2();
997 // The bit must come from the sign.
999 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
1000 Op.getOperand(1).getValueType());
1001 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
1002 Op.getOperand(0), NewSA));
1005 if (KnownOne.intersects(SignMask))
1006 // New bits are known one.
1007 KnownOne |= HighBits;
1010 case ISD::SIGN_EXTEND_INREG: {
1011 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1013 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
1014 // If we only care about the highest bit, don't bother shifting right.
1015 if (MsbMask == NewMask) {
1016 unsigned ShAmt = ExVT.getScalarSizeInBits();
1017 SDValue InOp = Op.getOperand(0);
1018 unsigned VTBits = Op->getValueType(0).getScalarSizeInBits();
1019 bool AlreadySignExtended =
1020 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
1021 // However if the input is already sign extended we expect the sign
1022 // extension to be dropped altogether later and do not simplify.
1023 if (!AlreadySignExtended) {
1024 // Compute the correct shift amount type, which must be getShiftAmountTy
1025 // for scalar types after legalization.
1026 EVT ShiftAmtTy = Op.getValueType();
1027 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1028 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1030 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
1032 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1033 Op.getValueType(), InOp,
1038 // Sign extension. Compute the demanded bits in the result that are not
1039 // present in the input.
1041 APInt::getHighBitsSet(BitWidth,
1042 BitWidth - ExVT.getScalarSizeInBits());
1044 // If none of the extended bits are demanded, eliminate the sextinreg.
1045 if ((NewBits & NewMask) == 0)
1046 return TLO.CombineTo(Op, Op.getOperand(0));
1049 APInt::getSignMask(ExVT.getScalarSizeInBits()).zext(BitWidth);
1050 APInt InputDemandedBits =
1051 APInt::getLowBitsSet(BitWidth,
1052 ExVT.getScalarSizeInBits()) &
1055 // Since the sign extended bits are demanded, we know that the sign
1057 InputDemandedBits |= InSignBit;
1059 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1060 KnownZero, KnownOne, TLO, Depth+1))
1062 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1064 // If the sign bit of the input is known set or clear, then we know the
1065 // top bits of the result.
1067 // If the input sign bit is known zero, convert this into a zero extension.
1068 if (KnownZero.intersects(InSignBit))
1069 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(
1070 Op.getOperand(0), dl, ExVT.getScalarType()));
1072 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1073 KnownOne |= NewBits;
1074 KnownZero &= ~NewBits;
1075 } else { // Input sign bit unknown
1076 KnownZero &= ~NewBits;
1077 KnownOne &= ~NewBits;
1081 case ISD::BUILD_PAIR: {
1082 EVT HalfVT = Op.getOperand(0).getValueType();
1083 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1085 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1086 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1088 APInt KnownZeroLo, KnownOneLo;
1089 APInt KnownZeroHi, KnownOneHi;
1091 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
1092 KnownOneLo, TLO, Depth + 1))
1095 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
1096 KnownOneHi, TLO, Depth + 1))
1099 KnownZero = KnownZeroLo.zext(BitWidth) |
1100 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
1102 KnownOne = KnownOneLo.zext(BitWidth) |
1103 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
1106 case ISD::ZERO_EXTEND: {
1107 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1108 APInt InMask = NewMask.trunc(OperandBitWidth);
1110 // If none of the top bits are demanded, convert this into an any_extend.
1112 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1113 if (!NewBits.intersects(NewMask))
1114 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1118 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1119 KnownZero, KnownOne, TLO, Depth+1))
1121 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1122 KnownZero = KnownZero.zext(BitWidth);
1123 KnownOne = KnownOne.zext(BitWidth);
1124 KnownZero |= NewBits;
1127 case ISD::SIGN_EXTEND: {
1128 EVT InVT = Op.getOperand(0).getValueType();
1129 unsigned InBits = InVT.getScalarSizeInBits();
1130 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
1131 APInt InSignBit = APInt::getOneBitSet(BitWidth, InBits - 1);
1132 APInt NewBits = ~InMask & NewMask;
1134 // If none of the top bits are demanded, convert this into an any_extend.
1136 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1140 // Since some of the sign extended bits are demanded, we know that the sign
1142 APInt InDemandedBits = InMask & NewMask;
1143 InDemandedBits |= InSignBit;
1144 InDemandedBits = InDemandedBits.trunc(InBits);
1146 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1147 KnownOne, TLO, Depth+1))
1149 KnownZero = KnownZero.zext(BitWidth);
1150 KnownOne = KnownOne.zext(BitWidth);
1152 // If the sign bit is known zero, convert this to a zero extend.
1153 if (KnownZero.intersects(InSignBit))
1154 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1158 // If the sign bit is known one, the top bits match.
1159 if (KnownOne.intersects(InSignBit)) {
1160 KnownOne |= NewBits;
1161 assert((KnownZero & NewBits) == 0);
1162 } else { // Otherwise, top bits aren't known.
1163 assert((KnownOne & NewBits) == 0);
1164 assert((KnownZero & NewBits) == 0);
1168 case ISD::ANY_EXTEND: {
1169 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1170 APInt InMask = NewMask.trunc(OperandBitWidth);
1171 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1172 KnownZero, KnownOne, TLO, Depth+1))
1174 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1175 KnownZero = KnownZero.zext(BitWidth);
1176 KnownOne = KnownOne.zext(BitWidth);
1179 case ISD::TRUNCATE: {
1180 // Simplify the input, using demanded bit information, and compute the known
1181 // zero/one bits live out.
1182 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1183 APInt TruncMask = NewMask.zext(OperandBitWidth);
1184 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1185 KnownZero, KnownOne, TLO, Depth+1))
1187 KnownZero = KnownZero.trunc(BitWidth);
1188 KnownOne = KnownOne.trunc(BitWidth);
1190 // If the input is only used by this truncate, see if we can shrink it based
1191 // on the known demanded bits.
1192 if (Op.getOperand(0).getNode()->hasOneUse()) {
1193 SDValue In = Op.getOperand(0);
1194 switch (In.getOpcode()) {
1197 // Shrink SRL by a constant if none of the high bits shifted in are
1199 if (TLO.LegalTypes() &&
1200 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1201 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1204 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1207 SDValue Shift = In.getOperand(1);
1208 if (TLO.LegalTypes()) {
1209 uint64_t ShVal = ShAmt->getZExtValue();
1210 Shift = TLO.DAG.getConstant(ShVal, dl,
1211 getShiftAmountTy(Op.getValueType(), DL));
1214 if (ShAmt->getZExtValue() < BitWidth) {
1215 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1216 OperandBitWidth - BitWidth);
1217 HighBits.lshrInPlace(ShAmt->getZExtValue());
1218 HighBits = HighBits.trunc(BitWidth);
1220 if (!(HighBits & NewMask)) {
1221 // None of the shifted in bits are needed. Add a truncate of the
1222 // shift input, then shift it.
1223 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1226 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1236 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1239 case ISD::AssertZext: {
1240 // AssertZext demands all of the high bits, plus any of the low bits
1241 // demanded by its users.
1242 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1243 APInt InMask = APInt::getLowBitsSet(BitWidth,
1244 VT.getSizeInBits());
1245 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1246 KnownZero, KnownOne, TLO, Depth+1))
1248 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1250 KnownZero |= ~InMask;
1254 // If this is an FP->Int bitcast and if the sign bit is the only
1255 // thing demanded, turn this into a FGETSIGN.
1256 if (!TLO.LegalOperations() &&
1257 !Op.getValueType().isVector() &&
1258 !Op.getOperand(0).getValueType().isVector() &&
1259 NewMask == APInt::getSignMask(Op.getValueSizeInBits()) &&
1260 Op.getOperand(0).getValueType().isFloatingPoint()) {
1261 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1262 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1263 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1264 Op.getOperand(0).getValueType() != MVT::f128) {
1265 // Cannot eliminate/lower SHL for f128 yet.
1266 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1267 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1268 // place. We expect the SHL to be eliminated by other optimizations.
1269 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1270 unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1271 if (!OpVTLegal && OpVTSizeInBits > 32)
1272 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1273 unsigned ShVal = Op.getValueSizeInBits() - 1;
1274 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
1275 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1284 // Add, Sub, and Mul don't demand any bits in positions beyond that
1285 // of the highest bit demanded of them.
1286 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1287 BitWidth - NewMask.countLeadingZeros());
1288 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1289 KnownOne2, TLO, Depth+1) ||
1290 SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1291 KnownOne2, TLO, Depth+1) ||
1292 // See if the operation should be performed at a smaller bit width.
1293 ShrinkDemandedOp(Op, BitWidth, NewMask, TLO)) {
1294 const SDNodeFlags *Flags = Op.getNode()->getFlags();
1295 if (Flags->hasNoSignedWrap() || Flags->hasNoUnsignedWrap()) {
1296 // Disable the nsw and nuw flags. We can no longer guarantee that we
1297 // won't wrap after simplification.
1298 SDNodeFlags NewFlags = *Flags;
1299 NewFlags.setNoSignedWrap(false);
1300 NewFlags.setNoUnsignedWrap(false);
1301 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, Op.getValueType(),
1302 Op.getOperand(0), Op.getOperand(1),
1304 return TLO.CombineTo(Op, NewOp);
1311 // Just use computeKnownBits to compute output bits.
1312 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1316 // If we know the value of all of the demanded bits, return this as a
1318 if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1319 // Avoid folding to a constant if any OpaqueConstant is involved.
1320 const SDNode *N = Op.getNode();
1321 for (SDNodeIterator I = SDNodeIterator::begin(N),
1322 E = SDNodeIterator::end(N); I != E; ++I) {
1324 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1328 return TLO.CombineTo(Op,
1329 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
1335 /// Determine which of the bits specified in Mask are known to be either zero or
1336 /// one and return them in the KnownZero/KnownOne bitsets.
1337 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1340 const APInt &DemandedElts,
1341 const SelectionDAG &DAG,
1342 unsigned Depth) const {
1343 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1344 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1345 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1346 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1347 "Should use MaskedValueIsZero if you don't know whether Op"
1348 " is a target node!");
1349 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1352 /// This method can be implemented by targets that want to expose additional
1353 /// information about sign bits to the DAG Combiner.
1354 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1356 const SelectionDAG &,
1357 unsigned Depth) const {
1358 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1359 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1360 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1361 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1362 "Should use ComputeNumSignBits if you don't know whether Op"
1363 " is a target node!");
1367 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
1368 // work with truncating build vectors and vectors with elements of less than
1370 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1375 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1376 CVal = CN->getAPIntValue();
1377 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
1378 auto *CN = BV->getConstantSplatNode();
1382 // If this is a truncating build vector, truncate the splat value.
1383 // Otherwise, we may fail to match the expected values below.
1384 unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
1385 CVal = CN->getAPIntValue();
1386 if (BVEltWidth < CVal.getBitWidth())
1387 CVal = CVal.trunc(BVEltWidth);
1392 switch (getBooleanContents(N->getValueType(0))) {
1393 case UndefinedBooleanContent:
1395 case ZeroOrOneBooleanContent:
1397 case ZeroOrNegativeOneBooleanContent:
1398 return CVal.isAllOnesValue();
1401 llvm_unreachable("Invalid boolean contents");
1404 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
1405 const SDLoc &DL) const {
1406 unsigned ElementWidth = VT.getScalarSizeInBits();
1408 getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
1409 ? APInt(ElementWidth, 1)
1410 : APInt::getAllOnesValue(ElementWidth);
1411 return DAG.getConstant(TrueInt, DL, VT);
1414 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1418 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1420 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1424 // Only interested in constant splats, we don't care about undef
1425 // elements in identifying boolean constants and getConstantSplatNode
1426 // returns NULL if all ops are undef;
1427 CN = BV->getConstantSplatNode();
1432 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1433 return !CN->getAPIntValue()[0];
1435 return CN->isNullValue();
1438 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1443 TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1445 case TargetLowering::ZeroOrOneBooleanContent:
1446 // An extended value of 1 is always true, unless its original type is i1,
1447 // in which case it will be sign extended to -1.
1448 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1449 case TargetLowering::UndefinedBooleanContent:
1450 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1451 return N->isAllOnesValue() && SExt;
1453 llvm_unreachable("Unexpected enumeration.");
1456 /// This helper function of SimplifySetCC tries to optimize the comparison when
1457 /// either operand of the SetCC node is a bitwise-and instruction.
1458 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1460 DAGCombinerInfo &DCI,
1461 const SDLoc &DL) const {
1462 // Match these patterns in any of their permutations:
1465 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1468 EVT OpVT = N0.getValueType();
1469 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
1470 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1474 if (N0.getOperand(0) == N1) {
1475 X = N0.getOperand(1);
1476 Y = N0.getOperand(0);
1477 } else if (N0.getOperand(1) == N1) {
1478 X = N0.getOperand(0);
1479 Y = N0.getOperand(1);
1484 SelectionDAG &DAG = DCI.DAG;
1485 SDValue Zero = DAG.getConstant(0, DL, OpVT);
1486 if (DAG.isKnownToBeAPowerOfTwo(Y)) {
1487 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1488 // Note that where Y is variable and is known to have at most one bit set
1489 // (for example, if it is Z & 1) we cannot do this; the expressions are not
1490 // equivalent when Y == 0.
1491 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1492 if (DCI.isBeforeLegalizeOps() ||
1493 isCondCodeLegal(Cond, N0.getSimpleValueType()))
1494 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1495 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1496 // If the target supports an 'and-not' or 'and-complement' logic operation,
1497 // try to use that to make a comparison operation more efficient.
1498 // But don't do this transform if the mask is a single bit because there are
1499 // more efficient ways to deal with that case (for example, 'bt' on x86 or
1500 // 'rlwinm' on PPC).
1502 // Bail out if the compare operand that we want to turn into a zero is
1503 // already a zero (otherwise, infinite loop).
1504 auto *YConst = dyn_cast<ConstantSDNode>(Y);
1505 if (YConst && YConst->isNullValue())
1508 // Transform this into: ~X & Y == 0.
1509 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1510 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1511 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1517 /// Try to simplify a setcc built with the specified operands and cc. If it is
1518 /// unable to simplify it, return a null SDValue.
1519 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1520 ISD::CondCode Cond, bool foldBooleans,
1521 DAGCombinerInfo &DCI,
1522 const SDLoc &dl) const {
1523 SelectionDAG &DAG = DCI.DAG;
1525 // These setcc operations always fold.
1529 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
1531 case ISD::SETTRUE2: {
1532 TargetLowering::BooleanContent Cnt =
1533 getBooleanContents(N0->getValueType(0));
1534 return DAG.getConstant(
1535 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1540 // Ensure that the constant occurs on the RHS, and fold constant
1542 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1543 if (isa<ConstantSDNode>(N0.getNode()) &&
1544 (DCI.isBeforeLegalizeOps() ||
1545 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1546 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1548 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1549 const APInt &C1 = N1C->getAPIntValue();
1551 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1552 // equality comparison, then we're just comparing whether X itself is
1554 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1555 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1556 N0.getOperand(1).getOpcode() == ISD::Constant) {
1558 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1559 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1560 ShAmt == Log2_32(N0.getValueSizeInBits())) {
1561 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1562 // (srl (ctlz x), 5) == 0 -> X != 0
1563 // (srl (ctlz x), 5) != 1 -> X != 0
1566 // (srl (ctlz x), 5) != 0 -> X == 0
1567 // (srl (ctlz x), 5) == 1 -> X == 0
1570 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1571 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1577 // Look through truncs that don't change the value of a ctpop.
1578 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1579 CTPOP = N0.getOperand(0);
1581 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1583 N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
1584 EVT CTVT = CTPOP.getValueType();
1585 SDValue CTOp = CTPOP.getOperand(0);
1587 // (ctpop x) u< 2 -> (x & x-1) == 0
1588 // (ctpop x) u> 1 -> (x & x-1) != 0
1589 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1590 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1591 DAG.getConstant(1, dl, CTVT));
1592 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1593 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1594 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1597 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1600 // (zext x) == C --> x == (trunc C)
1601 // (sext x) == C --> x == (trunc C)
1602 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1603 DCI.isBeforeLegalize() && N0->hasOneUse()) {
1604 unsigned MinBits = N0.getValueSizeInBits();
1606 bool Signed = false;
1607 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1609 MinBits = N0->getOperand(0).getValueSizeInBits();
1610 PreExt = N0->getOperand(0);
1611 } else if (N0->getOpcode() == ISD::AND) {
1612 // DAGCombine turns costly ZExts into ANDs
1613 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1614 if ((C->getAPIntValue()+1).isPowerOf2()) {
1615 MinBits = C->getAPIntValue().countTrailingOnes();
1616 PreExt = N0->getOperand(0);
1618 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1620 MinBits = N0->getOperand(0).getValueSizeInBits();
1621 PreExt = N0->getOperand(0);
1623 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
1624 // ZEXTLOAD / SEXTLOAD
1625 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1626 MinBits = LN0->getMemoryVT().getSizeInBits();
1628 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1630 MinBits = LN0->getMemoryVT().getSizeInBits();
1635 // Figure out how many bits we need to preserve this constant.
1636 unsigned ReqdBits = Signed ?
1637 C1.getBitWidth() - C1.getNumSignBits() + 1 :
1640 // Make sure we're not losing bits from the constant.
1642 MinBits < C1.getBitWidth() &&
1643 MinBits >= ReqdBits) {
1644 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1645 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1646 // Will get folded away.
1647 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1648 if (MinBits == 1 && C1 == 1)
1649 // Invert the condition.
1650 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
1651 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1652 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1653 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1656 // If truncating the setcc operands is not desirable, we can still
1657 // simplify the expression in some cases:
1658 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1659 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1660 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1661 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1662 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1663 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1664 SDValue TopSetCC = N0->getOperand(0);
1665 unsigned N0Opc = N0->getOpcode();
1666 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1667 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1668 TopSetCC.getOpcode() == ISD::SETCC &&
1669 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1670 (isConstFalseVal(N1C) ||
1671 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1673 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1674 (!N1C->isNullValue() && Cond == ISD::SETNE);
1679 ISD::CondCode InvCond = ISD::getSetCCInverse(
1680 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1681 TopSetCC.getOperand(0).getValueType().isInteger());
1682 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1683 TopSetCC.getOperand(1),
1690 // If the LHS is '(and load, const)', the RHS is 0,
1691 // the test is for equality or unsigned, and all 1 bits of the const are
1692 // in the same partial word, see if we can shorten the load.
1693 if (DCI.isBeforeLegalize() &&
1694 !ISD::isSignedIntSetCC(Cond) &&
1695 N0.getOpcode() == ISD::AND && C1 == 0 &&
1696 N0.getNode()->hasOneUse() &&
1697 isa<LoadSDNode>(N0.getOperand(0)) &&
1698 N0.getOperand(0).getNode()->hasOneUse() &&
1699 isa<ConstantSDNode>(N0.getOperand(1))) {
1700 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1702 unsigned bestWidth = 0, bestOffset = 0;
1703 if (!Lod->isVolatile() && Lod->isUnindexed()) {
1704 unsigned origWidth = N0.getValueSizeInBits();
1705 unsigned maskWidth = origWidth;
1706 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1707 // 8 bits, but have to be careful...
1708 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1709 origWidth = Lod->getMemoryVT().getSizeInBits();
1711 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1712 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1713 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1714 for (unsigned offset=0; offset<origWidth/width; offset++) {
1715 if ((newMask & Mask) == Mask) {
1716 if (!DAG.getDataLayout().isLittleEndian())
1717 bestOffset = (origWidth/width - offset - 1) * (width/8);
1719 bestOffset = (uint64_t)offset * (width/8);
1720 bestMask = Mask.lshr(offset * (width/8) * 8);
1724 newMask = newMask << width;
1729 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1730 if (newVT.isRound()) {
1731 EVT PtrType = Lod->getOperand(1).getValueType();
1732 SDValue Ptr = Lod->getBasePtr();
1733 if (bestOffset != 0)
1734 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1735 DAG.getConstant(bestOffset, dl, PtrType));
1736 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1737 SDValue NewLoad = DAG.getLoad(
1738 newVT, dl, Lod->getChain(), Ptr,
1739 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
1740 return DAG.getSetCC(dl, VT,
1741 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1742 DAG.getConstant(bestMask.trunc(bestWidth),
1744 DAG.getConstant(0LL, dl, newVT), Cond);
1749 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1750 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1751 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
1753 // If the comparison constant has bits in the upper part, the
1754 // zero-extended value could never match.
1755 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1756 C1.getBitWidth() - InSize))) {
1760 case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
1763 case ISD::SETNE: return DAG.getConstant(1, dl, VT);
1766 // True if the sign bit of C1 is set.
1767 return DAG.getConstant(C1.isNegative(), dl, VT);
1770 // True if the sign bit of C1 isn't set.
1771 return DAG.getConstant(C1.isNonNegative(), dl, VT);
1777 // Otherwise, we can perform the comparison with the low bits.
1785 EVT newVT = N0.getOperand(0).getValueType();
1786 if (DCI.isBeforeLegalizeOps() ||
1787 (isOperationLegal(ISD::SETCC, newVT) &&
1788 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1790 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
1791 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
1793 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1795 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
1800 break; // todo, be more careful with signed comparisons
1802 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1803 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1804 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1805 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1806 EVT ExtDstTy = N0.getValueType();
1807 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1809 // If the constant doesn't fit into the number of bits for the source of
1810 // the sign extension, it is impossible for both sides to be equal.
1811 if (C1.getMinSignedBits() > ExtSrcTyBits)
1812 return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
1815 EVT Op0Ty = N0.getOperand(0).getValueType();
1816 if (Op0Ty == ExtSrcTy) {
1817 ZextOp = N0.getOperand(0);
1819 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1820 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1821 DAG.getConstant(Imm, dl, Op0Ty));
1823 if (!DCI.isCalledByLegalizer())
1824 DCI.AddToWorklist(ZextOp.getNode());
1825 // Otherwise, make this a use of a zext.
1826 return DAG.getSetCC(dl, VT, ZextOp,
1827 DAG.getConstant(C1 & APInt::getLowBitsSet(
1832 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1833 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1834 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1835 if (N0.getOpcode() == ISD::SETCC &&
1836 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1837 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1839 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1840 // Invert the condition.
1841 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1842 CC = ISD::getSetCCInverse(CC,
1843 N0.getOperand(0).getValueType().isInteger());
1844 if (DCI.isBeforeLegalizeOps() ||
1845 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1846 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1849 if ((N0.getOpcode() == ISD::XOR ||
1850 (N0.getOpcode() == ISD::AND &&
1851 N0.getOperand(0).getOpcode() == ISD::XOR &&
1852 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1853 isa<ConstantSDNode>(N0.getOperand(1)) &&
1854 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1855 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1856 // can only do this if the top bits are known zero.
1857 unsigned BitWidth = N0.getValueSizeInBits();
1858 if (DAG.MaskedValueIsZero(N0,
1859 APInt::getHighBitsSet(BitWidth,
1861 // Okay, get the un-inverted input value.
1863 if (N0.getOpcode() == ISD::XOR)
1864 Val = N0.getOperand(0);
1866 assert(N0.getOpcode() == ISD::AND &&
1867 N0.getOperand(0).getOpcode() == ISD::XOR);
1868 // ((X^1)&1)^1 -> X & 1
1869 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1870 N0.getOperand(0).getOperand(0),
1874 return DAG.getSetCC(dl, VT, Val, N1,
1875 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1877 } else if (N1C->getAPIntValue() == 1 &&
1879 getBooleanContents(N0->getValueType(0)) ==
1880 ZeroOrOneBooleanContent)) {
1882 if (Op0.getOpcode() == ISD::TRUNCATE)
1883 Op0 = Op0.getOperand(0);
1885 if ((Op0.getOpcode() == ISD::XOR) &&
1886 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1887 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1888 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1889 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1890 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1893 if (Op0.getOpcode() == ISD::AND &&
1894 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1895 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1896 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1897 if (Op0.getValueType().bitsGT(VT))
1898 Op0 = DAG.getNode(ISD::AND, dl, VT,
1899 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1900 DAG.getConstant(1, dl, VT));
1901 else if (Op0.getValueType().bitsLT(VT))
1902 Op0 = DAG.getNode(ISD::AND, dl, VT,
1903 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1904 DAG.getConstant(1, dl, VT));
1906 return DAG.getSetCC(dl, VT, Op0,
1907 DAG.getConstant(0, dl, Op0.getValueType()),
1908 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1910 if (Op0.getOpcode() == ISD::AssertZext &&
1911 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1912 return DAG.getSetCC(dl, VT, Op0,
1913 DAG.getConstant(0, dl, Op0.getValueType()),
1914 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1918 APInt MinVal, MaxVal;
1919 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1920 if (ISD::isSignedIntSetCC(Cond)) {
1921 MinVal = APInt::getSignedMinValue(OperandBitSize);
1922 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1924 MinVal = APInt::getMinValue(OperandBitSize);
1925 MaxVal = APInt::getMaxValue(OperandBitSize);
1928 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1929 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1930 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true
1931 // X >= C0 --> X > (C0 - 1)
1933 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1934 if ((DCI.isBeforeLegalizeOps() ||
1935 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1936 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1937 isLegalICmpImmediate(C.getSExtValue())))) {
1938 return DAG.getSetCC(dl, VT, N0,
1939 DAG.getConstant(C, dl, N1.getValueType()),
1944 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1945 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true
1946 // X <= C0 --> X < (C0 + 1)
1948 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1949 if ((DCI.isBeforeLegalizeOps() ||
1950 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1951 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1952 isLegalICmpImmediate(C.getSExtValue())))) {
1953 return DAG.getSetCC(dl, VT, N0,
1954 DAG.getConstant(C, dl, N1.getValueType()),
1959 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1960 return DAG.getConstant(0, dl, VT); // X < MIN --> false
1961 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1962 return DAG.getConstant(1, dl, VT); // X >= MIN --> true
1963 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1964 return DAG.getConstant(0, dl, VT); // X > MAX --> false
1965 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1966 return DAG.getConstant(1, dl, VT); // X <= MAX --> true
1968 // Canonicalize setgt X, Min --> setne X, Min
1969 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1970 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1971 // Canonicalize setlt X, Max --> setne X, Max
1972 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1973 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1975 // If we have setult X, 1, turn it into seteq X, 0
1976 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1977 return DAG.getSetCC(dl, VT, N0,
1978 DAG.getConstant(MinVal, dl, N0.getValueType()),
1980 // If we have setugt X, Max-1, turn it into seteq X, Max
1981 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1982 return DAG.getSetCC(dl, VT, N0,
1983 DAG.getConstant(MaxVal, dl, N0.getValueType()),
1986 // If we have "setcc X, C0", check to see if we can shrink the immediate
1989 // SETUGT X, SINTMAX -> SETLT X, 0
1990 if (Cond == ISD::SETUGT &&
1991 C1 == APInt::getSignedMaxValue(OperandBitSize))
1992 return DAG.getSetCC(dl, VT, N0,
1993 DAG.getConstant(0, dl, N1.getValueType()),
1996 // SETULT X, SINTMIN -> SETGT X, -1
1997 if (Cond == ISD::SETULT &&
1998 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1999 SDValue ConstMinusOne =
2000 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
2002 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
2005 // Fold bit comparisons when we can.
2006 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2007 (VT == N0.getValueType() ||
2008 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
2009 N0.getOpcode() == ISD::AND) {
2010 auto &DL = DAG.getDataLayout();
2011 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2012 EVT ShiftTy = DCI.isBeforeLegalize()
2014 : getShiftAmountTy(N0.getValueType(), DL);
2015 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
2016 // Perform the xform if the AND RHS is a single bit.
2017 if (AndRHS->getAPIntValue().isPowerOf2()) {
2018 return DAG.getNode(ISD::TRUNCATE, dl, VT,
2019 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2020 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
2023 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2024 // (X & 8) == 8 --> (X & 8) >> 3
2025 // Perform the xform if C1 is a single bit.
2026 if (C1.isPowerOf2()) {
2027 return DAG.getNode(ISD::TRUNCATE, dl, VT,
2028 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2029 DAG.getConstant(C1.logBase2(), dl,
2036 if (C1.getMinSignedBits() <= 64 &&
2037 !isLegalICmpImmediate(C1.getSExtValue())) {
2038 // (X & -256) == 256 -> (X >> 8) == 1
2039 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2040 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2041 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2042 const APInt &AndRHSC = AndRHS->getAPIntValue();
2043 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2044 unsigned ShiftBits = AndRHSC.countTrailingZeros();
2045 auto &DL = DAG.getDataLayout();
2046 EVT ShiftTy = DCI.isBeforeLegalize()
2048 : getShiftAmountTy(N0.getValueType(), DL);
2049 EVT CmpTy = N0.getValueType();
2050 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2051 DAG.getConstant(ShiftBits, dl,
2053 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
2054 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2057 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2058 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2059 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2060 // X < 0x100000000 -> (X >> 32) < 1
2061 // X >= 0x100000000 -> (X >> 32) >= 1
2062 // X <= 0x0ffffffff -> (X >> 32) < 1
2063 // X > 0x0ffffffff -> (X >> 32) >= 1
2066 ISD::CondCode NewCond = Cond;
2068 ShiftBits = C1.countTrailingOnes();
2070 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2072 ShiftBits = C1.countTrailingZeros();
2074 NewC.lshrInPlace(ShiftBits);
2075 if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
2076 isLegalICmpImmediate(NewC.getSExtValue())) {
2077 auto &DL = DAG.getDataLayout();
2078 EVT ShiftTy = DCI.isBeforeLegalize()
2080 : getShiftAmountTy(N0.getValueType(), DL);
2081 EVT CmpTy = N0.getValueType();
2082 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2083 DAG.getConstant(ShiftBits, dl, ShiftTy));
2084 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
2085 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2091 if (isa<ConstantFPSDNode>(N0.getNode())) {
2092 // Constant fold or commute setcc.
2093 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2094 if (O.getNode()) return O;
2095 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2096 // If the RHS of an FP comparison is a constant, simplify it away in
2098 if (CFP->getValueAPF().isNaN()) {
2099 // If an operand is known to be a nan, we can fold it.
2100 switch (ISD::getUnorderedFlavor(Cond)) {
2101 default: llvm_unreachable("Unknown flavor!");
2102 case 0: // Known false.
2103 return DAG.getConstant(0, dl, VT);
2104 case 1: // Known true.
2105 return DAG.getConstant(1, dl, VT);
2106 case 2: // Undefined.
2107 return DAG.getUNDEF(VT);
2111 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
2112 // constant if knowing that the operand is non-nan is enough. We prefer to
2113 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2115 if (Cond == ISD::SETO || Cond == ISD::SETUO)
2116 return DAG.getSetCC(dl, VT, N0, N0, Cond);
2118 // setcc (fneg x), C -> setcc swap(pred) x, -C
2119 if (N0.getOpcode() == ISD::FNEG) {
2120 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
2121 if (DCI.isBeforeLegalizeOps() ||
2122 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
2123 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
2124 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
2128 // If the condition is not legal, see if we can find an equivalent one
2130 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2131 // If the comparison was an awkward floating-point == or != and one of
2132 // the comparison operands is infinity or negative infinity, convert the
2133 // condition to a less-awkward <= or >=.
2134 if (CFP->getValueAPF().isInfinity()) {
2135 if (CFP->getValueAPF().isNegative()) {
2136 if (Cond == ISD::SETOEQ &&
2137 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2138 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2139 if (Cond == ISD::SETUEQ &&
2140 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2141 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2142 if (Cond == ISD::SETUNE &&
2143 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2144 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2145 if (Cond == ISD::SETONE &&
2146 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2147 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2149 if (Cond == ISD::SETOEQ &&
2150 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2151 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2152 if (Cond == ISD::SETUEQ &&
2153 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2154 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2155 if (Cond == ISD::SETUNE &&
2156 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2157 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2158 if (Cond == ISD::SETONE &&
2159 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2160 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2167 // The sext(setcc()) => setcc() optimization relies on the appropriate
2168 // constant being emitted.
2170 switch (getBooleanContents(N0.getValueType())) {
2171 case UndefinedBooleanContent:
2172 case ZeroOrOneBooleanContent:
2173 EqVal = ISD::isTrueWhenEqual(Cond);
2175 case ZeroOrNegativeOneBooleanContent:
2176 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2180 // We can always fold X == X for integer setcc's.
2181 if (N0.getValueType().isInteger()) {
2182 return DAG.getConstant(EqVal, dl, VT);
2184 unsigned UOF = ISD::getUnorderedFlavor(Cond);
2185 if (UOF == 2) // FP operators that are undefined on NaNs.
2186 return DAG.getConstant(EqVal, dl, VT);
2187 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2188 return DAG.getConstant(EqVal, dl, VT);
2189 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2190 // if it is not already.
2191 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2192 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2193 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2194 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2197 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2198 N0.getValueType().isInteger()) {
2199 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2200 N0.getOpcode() == ISD::XOR) {
2201 // Simplify (X+Y) == (X+Z) --> Y == Z
2202 if (N0.getOpcode() == N1.getOpcode()) {
2203 if (N0.getOperand(0) == N1.getOperand(0))
2204 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2205 if (N0.getOperand(1) == N1.getOperand(1))
2206 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2207 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2208 // If X op Y == Y op X, try other combinations.
2209 if (N0.getOperand(0) == N1.getOperand(1))
2210 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2212 if (N0.getOperand(1) == N1.getOperand(0))
2213 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2218 // If RHS is a legal immediate value for a compare instruction, we need
2219 // to be careful about increasing register pressure needlessly.
2220 bool LegalRHSImm = false;
2222 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2223 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2224 // Turn (X+C1) == C2 --> X == C2-C1
2225 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2226 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2227 DAG.getConstant(RHSC->getAPIntValue()-
2228 LHSR->getAPIntValue(),
2229 dl, N0.getValueType()), Cond);
2232 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2233 if (N0.getOpcode() == ISD::XOR)
2234 // If we know that all of the inverted bits are zero, don't bother
2235 // performing the inversion.
2236 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2238 DAG.getSetCC(dl, VT, N0.getOperand(0),
2239 DAG.getConstant(LHSR->getAPIntValue() ^
2240 RHSC->getAPIntValue(),
2241 dl, N0.getValueType()),
2245 // Turn (C1-X) == C2 --> X == C1-C2
2246 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2247 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2249 DAG.getSetCC(dl, VT, N0.getOperand(1),
2250 DAG.getConstant(SUBC->getAPIntValue() -
2251 RHSC->getAPIntValue(),
2252 dl, N0.getValueType()),
2257 // Could RHSC fold directly into a compare?
2258 if (RHSC->getValueType(0).getSizeInBits() <= 64)
2259 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2262 // Simplify (X+Z) == X --> Z == 0
2263 // Don't do this if X is an immediate that can fold into a cmp
2264 // instruction and X+Z has other uses. It could be an induction variable
2265 // chain, and the transform would increase register pressure.
2266 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2267 if (N0.getOperand(0) == N1)
2268 return DAG.getSetCC(dl, VT, N0.getOperand(1),
2269 DAG.getConstant(0, dl, N0.getValueType()), Cond);
2270 if (N0.getOperand(1) == N1) {
2271 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2272 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2273 DAG.getConstant(0, dl, N0.getValueType()),
2275 if (N0.getNode()->hasOneUse()) {
2276 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2277 auto &DL = DAG.getDataLayout();
2278 // (Z-X) == X --> Z == X<<1
2279 SDValue SH = DAG.getNode(
2280 ISD::SHL, dl, N1.getValueType(), N1,
2281 DAG.getConstant(1, dl,
2282 getShiftAmountTy(N1.getValueType(), DL)));
2283 if (!DCI.isCalledByLegalizer())
2284 DCI.AddToWorklist(SH.getNode());
2285 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2291 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2292 N1.getOpcode() == ISD::XOR) {
2293 // Simplify X == (X+Z) --> Z == 0
2294 if (N1.getOperand(0) == N0)
2295 return DAG.getSetCC(dl, VT, N1.getOperand(1),
2296 DAG.getConstant(0, dl, N1.getValueType()), Cond);
2297 if (N1.getOperand(1) == N0) {
2298 if (DAG.isCommutativeBinOp(N1.getOpcode()))
2299 return DAG.getSetCC(dl, VT, N1.getOperand(0),
2300 DAG.getConstant(0, dl, N1.getValueType()), Cond);
2301 if (N1.getNode()->hasOneUse()) {
2302 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2303 auto &DL = DAG.getDataLayout();
2304 // X == (Z-X) --> X<<1 == Z
2305 SDValue SH = DAG.getNode(
2306 ISD::SHL, dl, N1.getValueType(), N0,
2307 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
2308 if (!DCI.isCalledByLegalizer())
2309 DCI.AddToWorklist(SH.getNode());
2310 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2315 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2319 // Fold away ALL boolean setcc's.
2321 if (N0.getValueType() == MVT::i1 && foldBooleans) {
2323 default: llvm_unreachable("Unknown integer setcc!");
2324 case ISD::SETEQ: // X == Y -> ~(X^Y)
2325 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2326 N0 = DAG.getNOT(dl, Temp, MVT::i1);
2327 if (!DCI.isCalledByLegalizer())
2328 DCI.AddToWorklist(Temp.getNode());
2330 case ISD::SETNE: // X != Y --> (X^Y)
2331 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2333 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2334 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
2335 Temp = DAG.getNOT(dl, N0, MVT::i1);
2336 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2337 if (!DCI.isCalledByLegalizer())
2338 DCI.AddToWorklist(Temp.getNode());
2340 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2341 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
2342 Temp = DAG.getNOT(dl, N1, MVT::i1);
2343 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2344 if (!DCI.isCalledByLegalizer())
2345 DCI.AddToWorklist(Temp.getNode());
2347 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2348 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
2349 Temp = DAG.getNOT(dl, N0, MVT::i1);
2350 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2351 if (!DCI.isCalledByLegalizer())
2352 DCI.AddToWorklist(Temp.getNode());
2354 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2355 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
2356 Temp = DAG.getNOT(dl, N1, MVT::i1);
2357 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2360 if (VT != MVT::i1) {
2361 if (!DCI.isCalledByLegalizer())
2362 DCI.AddToWorklist(N0.getNode());
2363 // FIXME: If running after legalize, we probably can't do this.
2364 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2369 // Could not fold it.
2373 /// Returns true (and the GlobalValue and the offset) if the node is a
2374 /// GlobalAddress + offset.
2375 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2376 int64_t &Offset) const {
2377 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
2378 GA = GASD->getGlobal();
2379 Offset += GASD->getOffset();
2383 if (N->getOpcode() == ISD::ADD) {
2384 SDValue N1 = N->getOperand(0);
2385 SDValue N2 = N->getOperand(1);
2386 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2387 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
2388 Offset += V->getSExtValue();
2391 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2392 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
2393 Offset += V->getSExtValue();
2402 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2403 DAGCombinerInfo &DCI) const {
2404 // Default implementation: no optimization.
2408 //===----------------------------------------------------------------------===//
2409 // Inline Assembler Implementation Methods
2410 //===----------------------------------------------------------------------===//
2412 TargetLowering::ConstraintType
2413 TargetLowering::getConstraintType(StringRef Constraint) const {
2414 unsigned S = Constraint.size();
2417 switch (Constraint[0]) {
2419 case 'r': return C_RegisterClass;
2421 case 'o': // offsetable
2422 case 'V': // not offsetable
2424 case 'i': // Simple Integer or Relocatable Constant
2425 case 'n': // Simple Integer
2426 case 'E': // Floating Point Constant
2427 case 'F': // Floating Point Constant
2428 case 's': // Relocatable Constant
2429 case 'p': // Address.
2430 case 'X': // Allow ANY value.
2431 case 'I': // Target registers.
2445 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2446 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2453 /// Try to replace an X constraint, which matches anything, with another that
2454 /// has more specific requirements based on the type of the corresponding
2456 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2457 if (ConstraintVT.isInteger())
2459 if (ConstraintVT.isFloatingPoint())
2460 return "f"; // works for many targets
2464 /// Lower the specified operand into the Ops vector.
2465 /// If it is invalid, don't add anything to Ops.
2466 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2467 std::string &Constraint,
2468 std::vector<SDValue> &Ops,
2469 SelectionDAG &DAG) const {
2471 if (Constraint.length() > 1) return;
2473 char ConstraintLetter = Constraint[0];
2474 switch (ConstraintLetter) {
2476 case 'X': // Allows any operand; labels (basic block) use this.
2477 if (Op.getOpcode() == ISD::BasicBlock) {
2482 case 'i': // Simple Integer or Relocatable Constant
2483 case 'n': // Simple Integer
2484 case 's': { // Relocatable Constant
2485 // These operands are interested in values of the form (GV+C), where C may
2486 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2487 // is possible and fine if either GV or C are missing.
2488 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2489 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2491 // If we have "(add GV, C)", pull out GV/C
2492 if (Op.getOpcode() == ISD::ADD) {
2493 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2494 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2496 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2497 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2505 // If we find a valid operand, map to the TargetXXX version so that the
2506 // value itself doesn't get selected.
2507 if (GA) { // Either &GV or &GV+C
2508 if (ConstraintLetter != 'n') {
2509 int64_t Offs = GA->getOffset();
2510 if (C) Offs += C->getZExtValue();
2511 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2512 C ? SDLoc(C) : SDLoc(),
2513 Op.getValueType(), Offs));
2517 if (C) { // just C, no GV.
2518 // Simple constants are not allowed for 's'.
2519 if (ConstraintLetter != 's') {
2520 // gcc prints these as sign extended. Sign extend value to 64 bits
2521 // now; without this it would get ZExt'd later in
2522 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2523 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2524 SDLoc(C), MVT::i64));
2533 std::pair<unsigned, const TargetRegisterClass *>
2534 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2535 StringRef Constraint,
2537 if (Constraint.empty() || Constraint[0] != '{')
2538 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2539 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2541 // Remove the braces from around the name.
2542 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2544 std::pair<unsigned, const TargetRegisterClass*> R =
2545 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2547 // Figure out which register class contains this reg.
2548 for (const TargetRegisterClass *RC : RI->regclasses()) {
2549 // If none of the value types for this register class are valid, we
2550 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2551 if (!isLegalRC(*RI, *RC))
2554 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2556 if (RegName.equals_lower(RI->getRegAsmName(*I))) {
2557 std::pair<unsigned, const TargetRegisterClass*> S =
2558 std::make_pair(*I, RC);
2560 // If this register class has the requested value type, return it,
2561 // otherwise keep searching and return the first class found
2562 // if no other is found which explicitly has the requested type.
2563 if (RI->isTypeLegalForClass(*RC, VT))
2574 //===----------------------------------------------------------------------===//
2575 // Constraint Selection.
2577 /// Return true of this is an input operand that is a matching constraint like
2579 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2580 assert(!ConstraintCode.empty() && "No known constraint!");
2581 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2584 /// If this is an input matching constraint, this method returns the output
2585 /// operand it matches.
2586 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2587 assert(!ConstraintCode.empty() && "No known constraint!");
2588 return atoi(ConstraintCode.c_str());
2591 /// Split up the constraint string from the inline assembly value into the
2592 /// specific constraints and their prefixes, and also tie in the associated
2594 /// If this returns an empty vector, and if the constraint string itself
2595 /// isn't empty, there was an error parsing.
2596 TargetLowering::AsmOperandInfoVector
2597 TargetLowering::ParseConstraints(const DataLayout &DL,
2598 const TargetRegisterInfo *TRI,
2599 ImmutableCallSite CS) const {
2600 /// Information about all of the constraints.
2601 AsmOperandInfoVector ConstraintOperands;
2602 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2603 unsigned maCount = 0; // Largest number of multiple alternative constraints.
2605 // Do a prepass over the constraints, canonicalizing them, and building up the
2606 // ConstraintOperands list.
2607 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2608 unsigned ResNo = 0; // ResNo - The result number of the next output.
2610 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2611 ConstraintOperands.emplace_back(std::move(CI));
2612 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2614 // Update multiple alternative constraint count.
2615 if (OpInfo.multipleAlternatives.size() > maCount)
2616 maCount = OpInfo.multipleAlternatives.size();
2618 OpInfo.ConstraintVT = MVT::Other;
2620 // Compute the value type for each operand.
2621 switch (OpInfo.Type) {
2622 case InlineAsm::isOutput:
2623 // Indirect outputs just consume an argument.
2624 if (OpInfo.isIndirect) {
2625 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2629 // The return value of the call is this value. As such, there is no
2630 // corresponding argument.
2631 assert(!CS.getType()->isVoidTy() &&
2633 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2634 OpInfo.ConstraintVT =
2635 getSimpleValueType(DL, STy->getElementType(ResNo));
2637 assert(ResNo == 0 && "Asm only has one result!");
2638 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2642 case InlineAsm::isInput:
2643 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2645 case InlineAsm::isClobber:
2650 if (OpInfo.CallOperandVal) {
2651 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2652 if (OpInfo.isIndirect) {
2653 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2655 report_fatal_error("Indirect operand for inline asm not a pointer!");
2656 OpTy = PtrTy->getElementType();
2659 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2660 if (StructType *STy = dyn_cast<StructType>(OpTy))
2661 if (STy->getNumElements() == 1)
2662 OpTy = STy->getElementType(0);
2664 // If OpTy is not a single value, it may be a struct/union that we
2665 // can tile with integers.
2666 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2667 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2676 OpInfo.ConstraintVT =
2677 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2680 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2681 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2682 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2684 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2689 // If we have multiple alternative constraints, select the best alternative.
2690 if (!ConstraintOperands.empty()) {
2692 unsigned bestMAIndex = 0;
2693 int bestWeight = -1;
2694 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2697 // Compute the sums of the weights for each alternative, keeping track
2698 // of the best (highest weight) one so far.
2699 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2701 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2702 cIndex != eIndex; ++cIndex) {
2703 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2704 if (OpInfo.Type == InlineAsm::isClobber)
2707 // If this is an output operand with a matching input operand,
2708 // look up the matching input. If their types mismatch, e.g. one
2709 // is an integer, the other is floating point, or their sizes are
2710 // different, flag it as an maCantMatch.
2711 if (OpInfo.hasMatchingInput()) {
2712 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2713 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2714 if ((OpInfo.ConstraintVT.isInteger() !=
2715 Input.ConstraintVT.isInteger()) ||
2716 (OpInfo.ConstraintVT.getSizeInBits() !=
2717 Input.ConstraintVT.getSizeInBits())) {
2718 weightSum = -1; // Can't match.
2723 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2728 weightSum += weight;
2731 if (weightSum > bestWeight) {
2732 bestWeight = weightSum;
2733 bestMAIndex = maIndex;
2737 // Now select chosen alternative in each constraint.
2738 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2739 cIndex != eIndex; ++cIndex) {
2740 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2741 if (cInfo.Type == InlineAsm::isClobber)
2743 cInfo.selectAlternative(bestMAIndex);
2748 // Check and hook up tied operands, choose constraint code to use.
2749 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2750 cIndex != eIndex; ++cIndex) {
2751 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2753 // If this is an output operand with a matching input operand, look up the
2754 // matching input. If their types mismatch, e.g. one is an integer, the
2755 // other is floating point, or their sizes are different, flag it as an
2757 if (OpInfo.hasMatchingInput()) {
2758 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2760 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2761 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2762 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2763 OpInfo.ConstraintVT);
2764 std::pair<unsigned, const TargetRegisterClass *> InputRC =
2765 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2766 Input.ConstraintVT);
2767 if ((OpInfo.ConstraintVT.isInteger() !=
2768 Input.ConstraintVT.isInteger()) ||
2769 (MatchRC.second != InputRC.second)) {
2770 report_fatal_error("Unsupported asm: input constraint"
2771 " with a matching output constraint of"
2772 " incompatible type!");
2778 return ConstraintOperands;
2781 /// Return an integer indicating how general CT is.
2782 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2784 case TargetLowering::C_Other:
2785 case TargetLowering::C_Unknown:
2787 case TargetLowering::C_Register:
2789 case TargetLowering::C_RegisterClass:
2791 case TargetLowering::C_Memory:
2794 llvm_unreachable("Invalid constraint type");
2797 /// Examine constraint type and operand type and determine a weight value.
2798 /// This object must already have been set up with the operand type
2799 /// and the current alternative constraint selected.
2800 TargetLowering::ConstraintWeight
2801 TargetLowering::getMultipleConstraintMatchWeight(
2802 AsmOperandInfo &info, int maIndex) const {
2803 InlineAsm::ConstraintCodeVector *rCodes;
2804 if (maIndex >= (int)info.multipleAlternatives.size())
2805 rCodes = &info.Codes;
2807 rCodes = &info.multipleAlternatives[maIndex].Codes;
2808 ConstraintWeight BestWeight = CW_Invalid;
2810 // Loop over the options, keeping track of the most general one.
2811 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2812 ConstraintWeight weight =
2813 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2814 if (weight > BestWeight)
2815 BestWeight = weight;
2821 /// Examine constraint type and operand type and determine a weight value.
2822 /// This object must already have been set up with the operand type
2823 /// and the current alternative constraint selected.
2824 TargetLowering::ConstraintWeight
2825 TargetLowering::getSingleConstraintMatchWeight(
2826 AsmOperandInfo &info, const char *constraint) const {
2827 ConstraintWeight weight = CW_Invalid;
2828 Value *CallOperandVal = info.CallOperandVal;
2829 // If we don't have a value, we can't do a match,
2830 // but allow it at the lowest weight.
2831 if (!CallOperandVal)
2833 // Look at the constraint type.
2834 switch (*constraint) {
2835 case 'i': // immediate integer.
2836 case 'n': // immediate integer with a known value.
2837 if (isa<ConstantInt>(CallOperandVal))
2838 weight = CW_Constant;
2840 case 's': // non-explicit intregal immediate.
2841 if (isa<GlobalValue>(CallOperandVal))
2842 weight = CW_Constant;
2844 case 'E': // immediate float if host format.
2845 case 'F': // immediate float.
2846 if (isa<ConstantFP>(CallOperandVal))
2847 weight = CW_Constant;
2849 case '<': // memory operand with autodecrement.
2850 case '>': // memory operand with autoincrement.
2851 case 'm': // memory operand.
2852 case 'o': // offsettable memory operand
2853 case 'V': // non-offsettable memory operand
2856 case 'r': // general register.
2857 case 'g': // general register, memory operand or immediate integer.
2858 // note: Clang converts "g" to "imr".
2859 if (CallOperandVal->getType()->isIntegerTy())
2860 weight = CW_Register;
2862 case 'X': // any operand.
2864 weight = CW_Default;
2870 /// If there are multiple different constraints that we could pick for this
2871 /// operand (e.g. "imr") try to pick the 'best' one.
2872 /// This is somewhat tricky: constraints fall into four classes:
2873 /// Other -> immediates and magic values
2874 /// Register -> one specific register
2875 /// RegisterClass -> a group of regs
2876 /// Memory -> memory
2877 /// Ideally, we would pick the most specific constraint possible: if we have
2878 /// something that fits into a register, we would pick it. The problem here
2879 /// is that if we have something that could either be in a register or in
2880 /// memory that use of the register could cause selection of *other*
2881 /// operands to fail: they might only succeed if we pick memory. Because of
2882 /// this the heuristic we use is:
2884 /// 1) If there is an 'other' constraint, and if the operand is valid for
2885 /// that constraint, use it. This makes us take advantage of 'i'
2886 /// constraints when available.
2887 /// 2) Otherwise, pick the most general constraint present. This prefers
2888 /// 'm' over 'r', for example.
2890 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2891 const TargetLowering &TLI,
2892 SDValue Op, SelectionDAG *DAG) {
2893 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2894 unsigned BestIdx = 0;
2895 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2896 int BestGenerality = -1;
2898 // Loop over the options, keeping track of the most general one.
2899 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2900 TargetLowering::ConstraintType CType =
2901 TLI.getConstraintType(OpInfo.Codes[i]);
2903 // If this is an 'other' constraint, see if the operand is valid for it.
2904 // For example, on X86 we might have an 'rI' constraint. If the operand
2905 // is an integer in the range [0..31] we want to use I (saving a load
2906 // of a register), otherwise we must use 'r'.
2907 if (CType == TargetLowering::C_Other && Op.getNode()) {
2908 assert(OpInfo.Codes[i].size() == 1 &&
2909 "Unhandled multi-letter 'other' constraint");
2910 std::vector<SDValue> ResultOps;
2911 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2913 if (!ResultOps.empty()) {
2920 // Things with matching constraints can only be registers, per gcc
2921 // documentation. This mainly affects "g" constraints.
2922 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2925 // This constraint letter is more general than the previous one, use it.
2926 int Generality = getConstraintGenerality(CType);
2927 if (Generality > BestGenerality) {
2930 BestGenerality = Generality;
2934 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2935 OpInfo.ConstraintType = BestType;
2938 /// Determines the constraint code and constraint type to use for the specific
2939 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2940 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2942 SelectionDAG *DAG) const {
2943 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2945 // Single-letter constraints ('r') are very common.
2946 if (OpInfo.Codes.size() == 1) {
2947 OpInfo.ConstraintCode = OpInfo.Codes[0];
2948 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2950 ChooseConstraint(OpInfo, *this, Op, DAG);
2953 // 'X' matches anything.
2954 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2955 // Labels and constants are handled elsewhere ('X' is the only thing
2956 // that matches labels). For Functions, the type here is the type of
2957 // the result, which is not what we want to look at; leave them alone.
2958 Value *v = OpInfo.CallOperandVal;
2959 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2960 OpInfo.CallOperandVal = v;
2964 // Otherwise, try to resolve it to something we know about by looking at
2965 // the actual operand type.
2966 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2967 OpInfo.ConstraintCode = Repl;
2968 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2973 /// \brief Given an exact SDIV by a constant, create a multiplication
2974 /// with the multiplicative inverse of the constant.
2975 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2976 const SDLoc &dl, SelectionDAG &DAG,
2977 std::vector<SDNode *> &Created) {
2978 assert(d != 0 && "Division by zero!");
2980 // Shift the value upfront if it is even, so the LSB is one.
2981 unsigned ShAmt = d.countTrailingZeros();
2983 // TODO: For UDIV use SRL instead of SRA.
2985 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2986 DAG.getDataLayout()));
2988 Flags.setExact(true);
2989 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
2990 Created.push_back(Op1.getNode());
2994 // Calculate the multiplicative inverse, using Newton's method.
2996 while ((t = d*xn) != 1)
2997 xn *= APInt(d.getBitWidth(), 2) - t;
2999 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
3000 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
3001 Created.push_back(Mul.getNode());
3005 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3007 std::vector<SDNode *> *Created) const {
3008 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
3009 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3010 if (TLI.isIntDivCheap(N->getValueType(0), Attr))
3011 return SDValue(N,0); // Lower SDIV as SDIV
3015 /// \brief Given an ISD::SDIV node expressing a divide by constant,
3016 /// return a DAG expression to select that will generate the same value by
3017 /// multiplying by a magic number.
3018 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3019 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
3020 SelectionDAG &DAG, bool IsAfterLegalization,
3021 std::vector<SDNode *> *Created) const {
3022 assert(Created && "No vector to hold sdiv ops.");
3024 EVT VT = N->getValueType(0);
3027 // Check to see if we can do this.
3028 // FIXME: We should be more aggressive here.
3029 if (!isTypeLegal(VT))
3032 // If the sdiv has an 'exact' bit we can use a simpler lowering.
3033 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
3034 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
3036 APInt::ms magics = Divisor.magic();
3038 // Multiply the numerator (operand 0) by the magic value
3039 // FIXME: We should support doing a MUL in a wider type
3041 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
3042 isOperationLegalOrCustom(ISD::MULHS, VT))
3043 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3044 DAG.getConstant(magics.m, dl, VT));
3045 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
3046 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3047 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3049 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3051 return SDValue(); // No mulhs or equvialent
3052 // If d > 0 and m < 0, add the numerator
3053 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
3054 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3055 Created->push_back(Q.getNode());
3057 // If d < 0 and m > 0, subtract the numerator.
3058 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
3059 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3060 Created->push_back(Q.getNode());
3062 auto &DL = DAG.getDataLayout();
3063 // Shift right algebraic if shift value is nonzero
3066 ISD::SRA, dl, VT, Q,
3067 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3068 Created->push_back(Q.getNode());
3070 // Extract the sign bit and add it to the quotient
3072 DAG.getNode(ISD::SRL, dl, VT, Q,
3073 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
3074 getShiftAmountTy(Q.getValueType(), DL)));
3075 Created->push_back(T.getNode());
3076 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3079 /// \brief Given an ISD::UDIV node expressing a divide by constant,
3080 /// return a DAG expression to select that will generate the same value by
3081 /// multiplying by a magic number.
3082 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3083 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
3084 SelectionDAG &DAG, bool IsAfterLegalization,
3085 std::vector<SDNode *> *Created) const {
3086 assert(Created && "No vector to hold udiv ops.");
3088 EVT VT = N->getValueType(0);
3090 auto &DL = DAG.getDataLayout();
3092 // Check to see if we can do this.
3093 // FIXME: We should be more aggressive here.
3094 if (!isTypeLegal(VT))
3097 // FIXME: We should use a narrower constant when the upper
3098 // bits are known to be zero.
3099 APInt::mu magics = Divisor.magicu();
3101 SDValue Q = N->getOperand(0);
3103 // If the divisor is even, we can avoid using the expensive fixup by shifting
3104 // the divided value upfront.
3105 if (magics.a != 0 && !Divisor[0]) {
3106 unsigned Shift = Divisor.countTrailingZeros();
3108 ISD::SRL, dl, VT, Q,
3109 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
3110 Created->push_back(Q.getNode());
3112 // Get magic number for the shifted divisor.
3113 magics = Divisor.lshr(Shift).magicu(Shift);
3114 assert(magics.a == 0 && "Should use cheap fixup now");
3117 // Multiply the numerator (operand 0) by the magic value
3118 // FIXME: We should support doing a MUL in a wider type
3119 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
3120 isOperationLegalOrCustom(ISD::MULHU, VT))
3121 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
3122 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
3123 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3124 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3125 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3127 return SDValue(); // No mulhu or equivalent
3129 Created->push_back(Q.getNode());
3131 if (magics.a == 0) {
3132 assert(magics.s < Divisor.getBitWidth() &&
3133 "We shouldn't generate an undefined shift!");
3135 ISD::SRL, dl, VT, Q,
3136 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3138 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3139 Created->push_back(NPQ.getNode());
3141 ISD::SRL, dl, VT, NPQ,
3142 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
3143 Created->push_back(NPQ.getNode());
3144 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3145 Created->push_back(NPQ.getNode());
3147 ISD::SRL, dl, VT, NPQ,
3148 DAG.getConstant(magics.s - 1, dl,
3149 getShiftAmountTy(NPQ.getValueType(), DL)));
3153 bool TargetLowering::
3154 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
3155 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
3156 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
3157 "be a constant integer");
3164 //===----------------------------------------------------------------------===//
3165 // Legalization Utilities
3166 //===----------------------------------------------------------------------===//
3168 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
3169 SDValue LHS, SDValue RHS,
3170 SmallVectorImpl<SDValue> &Result,
3171 EVT HiLoVT, SelectionDAG &DAG,
3172 MulExpansionKind Kind, SDValue LL,
3173 SDValue LH, SDValue RL, SDValue RH) const {
3174 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
3175 Opcode == ISD::SMUL_LOHI);
3177 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
3178 isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
3179 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
3180 isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
3181 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3182 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
3183 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3184 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3186 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
3189 unsigned OuterBitSize = VT.getScalarSizeInBits();
3190 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
3191 unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
3192 unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
3194 // LL, LH, RL, and RH must be either all NULL or all set to a value.
3195 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3196 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3198 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
3199 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
3200 bool Signed) -> bool {
3201 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
3202 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
3203 Hi = SDValue(Lo.getNode(), 1);
3206 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
3207 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
3208 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
3216 if (!LL.getNode() && !RL.getNode() &&
3217 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3218 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
3219 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
3225 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3226 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
3227 DAG.MaskedValueIsZero(RHS, HighMask)) {
3228 // The inputs are both zero-extended.
3229 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
3230 Result.push_back(Lo);
3231 Result.push_back(Hi);
3232 if (Opcode != ISD::MUL) {
3233 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3234 Result.push_back(Zero);
3235 Result.push_back(Zero);
3241 if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
3242 RHSSB > InnerBitSize) {
3243 // The input values are both sign-extended.
3244 // TODO non-MUL case?
3245 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
3246 Result.push_back(Lo);
3247 Result.push_back(Hi);
3252 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
3253 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
3254 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
3255 // FIXME getShiftAmountTy does not always return a sensible result when VT
3256 // is an illegal type, and so the type may be too small to fit the shift
3257 // amount. Override it with i32. The shift will have to be legalized.
3258 ShiftAmountTy = MVT::i32;
3260 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
3262 if (!LH.getNode() && !RH.getNode() &&
3263 isOperationLegalOrCustom(ISD::SRL, VT) &&
3264 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3265 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
3266 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3267 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
3268 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3274 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
3277 Result.push_back(Lo);
3279 if (Opcode == ISD::MUL) {
3280 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3281 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3282 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3283 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3284 Result.push_back(Hi);
3288 // Compute the full width result.
3289 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
3290 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3291 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3292 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3293 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
3296 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3297 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
3300 // This is effectively the add part of a multiply-add of half-sized operands,
3301 // so it cannot overflow.
3302 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3304 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
3307 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
3310 SDValue Carry = Next.getValue(1);
3311 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3312 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3314 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
3317 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3318 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
3320 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3322 if (Opcode == ISD::SMUL_LOHI) {
3323 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3324 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
3325 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
3327 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3328 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
3329 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
3332 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3333 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3334 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3338 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3339 SelectionDAG &DAG, MulExpansionKind Kind,
3340 SDValue LL, SDValue LH, SDValue RL,
3342 SmallVector<SDValue, 2> Result;
3343 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
3344 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
3345 DAG, Kind, LL, LH, RL, RH);
3347 assert(Result.size() == 2);
3354 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3355 SelectionDAG &DAG) const {
3356 EVT VT = Node->getOperand(0).getValueType();
3357 EVT NVT = Node->getValueType(0);
3358 SDLoc dl(SDValue(Node, 0));
3360 // FIXME: Only f32 to i64 conversions are supported.
3361 if (VT != MVT::f32 || NVT != MVT::i64)
3364 // Expand f32 -> i64 conversion
3365 // This algorithm comes from compiler-rt's implementation of fixsfdi:
3366 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3367 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3368 VT.getSizeInBits());
3369 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3370 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3371 SDValue Bias = DAG.getConstant(127, dl, IntVT);
3372 SDValue SignMask = DAG.getConstant(APInt::getSignMask(VT.getSizeInBits()), dl,
3374 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3375 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
3377 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3379 auto &DL = DAG.getDataLayout();
3380 SDValue ExponentBits = DAG.getNode(
3381 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3382 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
3383 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3385 SDValue Sign = DAG.getNode(
3386 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3387 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
3388 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3390 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3391 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3392 DAG.getConstant(0x00800000, dl, IntVT));
3394 R = DAG.getZExtOrTrunc(R, dl, NVT);
3396 R = DAG.getSelectCC(
3397 dl, Exponent, ExponentLoBit,
3398 DAG.getNode(ISD::SHL, dl, NVT, R,
3400 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3401 dl, getShiftAmountTy(IntVT, DL))),
3402 DAG.getNode(ISD::SRL, dl, NVT, R,
3404 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3405 dl, getShiftAmountTy(IntVT, DL))),
3408 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3409 DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3412 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3413 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3417 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3418 SelectionDAG &DAG) const {
3420 SDValue Chain = LD->getChain();
3421 SDValue BasePTR = LD->getBasePtr();
3422 EVT SrcVT = LD->getMemoryVT();
3423 ISD::LoadExtType ExtType = LD->getExtensionType();
3425 unsigned NumElem = SrcVT.getVectorNumElements();
3427 EVT SrcEltVT = SrcVT.getScalarType();
3428 EVT DstEltVT = LD->getValueType(0).getScalarType();
3430 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3431 assert(SrcEltVT.isByteSized());
3433 EVT PtrVT = BasePTR.getValueType();
3435 SmallVector<SDValue, 8> Vals;
3436 SmallVector<SDValue, 8> LoadChains;
3438 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3439 SDValue ScalarLoad =
3440 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3441 LD->getPointerInfo().getWithOffset(Idx * Stride),
3442 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3443 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3445 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3446 DAG.getConstant(Stride, SL, PtrVT));
3448 Vals.push_back(ScalarLoad.getValue(0));
3449 LoadChains.push_back(ScalarLoad.getValue(1));
3452 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3453 SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
3455 return DAG.getMergeValues({ Value, NewChain }, SL);
3458 // FIXME: This relies on each element having a byte size, otherwise the stride
3459 // is 0 and just overwrites the same location. ExpandStore currently expects
3460 // this broken behavior.
3461 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3462 SelectionDAG &DAG) const {
3465 SDValue Chain = ST->getChain();
3466 SDValue BasePtr = ST->getBasePtr();
3467 SDValue Value = ST->getValue();
3468 EVT StVT = ST->getMemoryVT();
3470 // The type of the data we want to save
3471 EVT RegVT = Value.getValueType();
3472 EVT RegSclVT = RegVT.getScalarType();
3474 // The type of data as saved in memory.
3475 EVT MemSclVT = StVT.getScalarType();
3477 EVT PtrVT = BasePtr.getValueType();
3479 // Store Stride in bytes
3480 unsigned Stride = MemSclVT.getSizeInBits() / 8;
3481 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3482 unsigned NumElem = StVT.getVectorNumElements();
3484 // Extract each of the elements from the original vector and save them into
3485 // memory individually.
3486 SmallVector<SDValue, 8> Stores;
3487 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3488 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3489 DAG.getConstant(Idx, SL, IdxVT));
3491 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3492 DAG.getConstant(Idx * Stride, SL, PtrVT));
3494 // This scalar TruncStore may be illegal, but we legalize it later.
3495 SDValue Store = DAG.getTruncStore(
3496 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3497 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3498 ST->getMemOperand()->getFlags(), ST->getAAInfo());
3500 Stores.push_back(Store);
3503 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3506 std::pair<SDValue, SDValue>
3507 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3508 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3509 "unaligned indexed loads not implemented!");
3510 SDValue Chain = LD->getChain();
3511 SDValue Ptr = LD->getBasePtr();
3512 EVT VT = LD->getValueType(0);
3513 EVT LoadedVT = LD->getMemoryVT();
3515 if (VT.isFloatingPoint() || VT.isVector()) {
3516 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3517 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3518 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3519 // Scalarize the load and let the individual components be handled.
3520 SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3521 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3524 // Expand to a (misaligned) integer load of the same size,
3525 // then bitconvert to floating point or vector.
3526 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3527 LD->getMemOperand());
3528 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3530 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3531 ISD::ANY_EXTEND, dl, VT, Result);
3533 return std::make_pair(Result, newLoad.getValue(1));
3536 // Copy the value to a (aligned) stack slot using (unaligned) integer
3537 // loads and stores, then do a (aligned) load from the stack slot.
3538 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3539 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3540 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3541 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3543 // Make sure the stack slot is also aligned for the register type.
3544 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3546 SmallVector<SDValue, 8> Stores;
3547 SDValue StackPtr = StackBase;
3548 unsigned Offset = 0;
3550 EVT PtrVT = Ptr.getValueType();
3551 EVT StackPtrVT = StackPtr.getValueType();
3553 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3554 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3556 // Do all but one copies using the full register width.
3557 for (unsigned i = 1; i < NumRegs; i++) {
3558 // Load one integer register's worth from the original location.
3559 SDValue Load = DAG.getLoad(
3560 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3561 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3563 // Follow the load with a store to the stack slot. Remember the store.
3564 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3565 MachinePointerInfo()));
3566 // Increment the pointers.
3568 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3569 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3573 // The last copy may be partial. Do an extending load.
3574 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3575 8 * (LoadedBytes - Offset));
3577 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3578 LD->getPointerInfo().getWithOffset(Offset), MemVT,
3579 MinAlign(LD->getAlignment(), Offset),
3580 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3581 // Follow the load with a store to the stack slot. Remember the store.
3582 // On big-endian machines this requires a truncating store to ensure
3583 // that the bits end up in the right place.
3584 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3585 MachinePointerInfo(), MemVT));
3587 // The order of the stores doesn't matter - say it with a TokenFactor.
3588 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3590 // Finally, perform the original load only redirected to the stack slot.
3591 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3592 MachinePointerInfo(), LoadedVT);
3594 // Callers expect a MERGE_VALUES node.
3595 return std::make_pair(Load, TF);
3598 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3599 "Unaligned load of unsupported type.");
3601 // Compute the new VT that is half the size of the old one. This is an
3603 unsigned NumBits = LoadedVT.getSizeInBits();
3605 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3608 unsigned Alignment = LD->getAlignment();
3609 unsigned IncrementSize = NumBits / 8;
3610 ISD::LoadExtType HiExtType = LD->getExtensionType();
3612 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3613 if (HiExtType == ISD::NON_EXTLOAD)
3614 HiExtType = ISD::ZEXTLOAD;
3616 // Load the value in two parts
3618 if (DAG.getDataLayout().isLittleEndian()) {
3619 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3620 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3622 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3623 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3624 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3625 LD->getPointerInfo().getWithOffset(IncrementSize),
3626 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3627 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3629 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3630 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3632 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3633 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3634 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3635 LD->getPointerInfo().getWithOffset(IncrementSize),
3636 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3637 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3640 // aggregate the two parts
3641 SDValue ShiftAmount =
3642 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3643 DAG.getDataLayout()));
3644 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3645 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3647 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3650 return std::make_pair(Result, TF);
3653 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3654 SelectionDAG &DAG) const {
3655 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3656 "unaligned indexed stores not implemented!");
3657 SDValue Chain = ST->getChain();
3658 SDValue Ptr = ST->getBasePtr();
3659 SDValue Val = ST->getValue();
3660 EVT VT = Val.getValueType();
3661 int Alignment = ST->getAlignment();
3664 if (ST->getMemoryVT().isFloatingPoint() ||
3665 ST->getMemoryVT().isVector()) {
3666 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3667 if (isTypeLegal(intVT)) {
3668 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3669 // Scalarize the store and let the individual components be handled.
3670 SDValue Result = scalarizeVectorStore(ST, DAG);
3674 // Expand to a bitconvert of the value to the integer type of the
3675 // same size, then a (misaligned) int store.
3676 // FIXME: Does not handle truncating floating point stores!
3677 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3678 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3679 Alignment, ST->getMemOperand()->getFlags());
3682 // Do a (aligned) store to a stack slot, then copy from the stack slot
3683 // to the final destination using (unaligned) integer loads and stores.
3684 EVT StoredVT = ST->getMemoryVT();
3686 getRegisterType(*DAG.getContext(),
3687 EVT::getIntegerVT(*DAG.getContext(),
3688 StoredVT.getSizeInBits()));
3689 EVT PtrVT = Ptr.getValueType();
3690 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3691 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3692 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3694 // Make sure the stack slot is also aligned for the register type.
3695 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3697 // Perform the original store, only redirected to the stack slot.
3698 SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
3699 MachinePointerInfo(), StoredVT);
3701 EVT StackPtrVT = StackPtr.getValueType();
3703 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3704 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3705 SmallVector<SDValue, 8> Stores;
3706 unsigned Offset = 0;
3708 // Do all but one copies using the full register width.
3709 for (unsigned i = 1; i < NumRegs; i++) {
3710 // Load one integer register's worth from the stack slot.
3712 DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
3713 // Store it to the final location. Remember the store.
3714 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3715 ST->getPointerInfo().getWithOffset(Offset),
3716 MinAlign(ST->getAlignment(), Offset),
3717 ST->getMemOperand()->getFlags()));
3718 // Increment the pointers.
3720 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3721 StackPtr, StackPtrIncrement);
3722 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3725 // The last store may be partial. Do a truncating store. On big-endian
3726 // machines this requires an extending load from the stack slot to ensure
3727 // that the bits are in the right place.
3728 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3729 8 * (StoredBytes - Offset));
3731 // Load from the stack slot.
3732 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3733 MachinePointerInfo(), MemVT);
3736 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3737 ST->getPointerInfo().getWithOffset(Offset), MemVT,
3738 MinAlign(ST->getAlignment(), Offset),
3739 ST->getMemOperand()->getFlags(), ST->getAAInfo()));
3740 // The order of the stores doesn't matter - say it with a TokenFactor.
3741 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3745 assert(ST->getMemoryVT().isInteger() &&
3746 !ST->getMemoryVT().isVector() &&
3747 "Unaligned store of unknown type.");
3748 // Get the half-size VT
3749 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3750 int NumBits = NewStoredVT.getSizeInBits();
3751 int IncrementSize = NumBits / 8;
3753 // Divide the stored value in two parts.
3754 SDValue ShiftAmount =
3755 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3756 DAG.getDataLayout()));
3758 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3760 // Store the two parts
3761 SDValue Store1, Store2;
3762 Store1 = DAG.getTruncStore(Chain, dl,
3763 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3764 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
3765 ST->getMemOperand()->getFlags());
3767 EVT PtrVT = Ptr.getValueType();
3768 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3769 DAG.getConstant(IncrementSize, dl, PtrVT));
3770 Alignment = MinAlign(Alignment, IncrementSize);
3771 Store2 = DAG.getTruncStore(
3772 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3773 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
3774 ST->getMemOperand()->getFlags(), ST->getAAInfo());
3777 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3782 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
3783 const SDLoc &DL, EVT DataVT,
3785 bool IsCompressedMemory) const {
3787 EVT AddrVT = Addr.getValueType();
3788 EVT MaskVT = Mask.getValueType();
3789 assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
3790 "Incompatible types of Data and Mask");
3791 if (IsCompressedMemory) {
3792 // Incrementing the pointer according to number of '1's in the mask.
3793 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
3794 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
3795 if (MaskIntVT.getSizeInBits() < 32) {
3796 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
3797 MaskIntVT = MVT::i32;
3800 // Count '1's with POPCNT.
3801 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
3802 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
3803 // Scale is an element size in bytes.
3804 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
3806 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
3808 Increment = DAG.getConstant(DataVT.getSizeInBits() / 8, DL, AddrVT);
3810 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
3813 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
3817 if (isa<ConstantSDNode>(Idx))
3820 EVT IdxVT = Idx.getValueType();
3821 unsigned NElts = VecVT.getVectorNumElements();
3822 if (isPowerOf2_32(NElts)) {
3823 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
3825 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
3826 DAG.getConstant(Imm, dl, IdxVT));
3829 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
3830 DAG.getConstant(NElts - 1, dl, IdxVT));
3833 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
3834 SDValue VecPtr, EVT VecVT,
3835 SDValue Index) const {
3837 // Make sure the index type is big enough to compute in.
3838 Index = DAG.getZExtOrTrunc(Index, dl, getPointerTy(DAG.getDataLayout()));
3840 EVT EltVT = VecVT.getVectorElementType();
3842 // Calculate the element offset and add it to the pointer.
3843 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
3844 assert(EltSize * 8 == EltVT.getSizeInBits() &&
3845 "Converting bits to bytes lost precision");
3847 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
3849 EVT IdxVT = Index.getValueType();
3851 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
3852 DAG.getConstant(EltSize, dl, IdxVT));
3853 return DAG.getNode(ISD::ADD, dl, IdxVT, Index, VecPtr);
3856 //===----------------------------------------------------------------------===//
3857 // Implementation of Emulated TLS Model
3858 //===----------------------------------------------------------------------===//
3860 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3861 SelectionDAG &DAG) const {
3862 // Access to address of TLS varialbe xyz is lowered to a function call:
3863 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3864 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3865 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3870 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3871 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3872 StringRef EmuTlsVarName(NameString);
3873 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
3874 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
3875 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3876 Entry.Ty = VoidPtrType;
3877 Args.push_back(Entry);
3879 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3881 TargetLowering::CallLoweringInfo CLI(DAG);
3882 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3883 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
3884 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3886 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3887 // At last for X86 targets, maybe good for other targets too?
3888 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3889 MFI.setAdjustsStack(true); // Is this only for X86 target?
3890 MFI.setHasCalls(true);
3892 assert((GA->getOffset() == 0) &&
3893 "Emulated TLS must have zero offset in GlobalAddressSDNode");
3894 return CallResult.first;
3897 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
3898 SelectionDAG &DAG) const {
3899 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
3902 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3905 if (C->isNullValue() && CC == ISD::SETEQ) {
3906 EVT VT = Op.getOperand(0).getValueType();
3907 SDValue Zext = Op.getOperand(0);
3908 if (VT.bitsLT(MVT::i32)) {
3910 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
3912 unsigned Log2b = Log2_32(VT.getSizeInBits());
3913 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
3914 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
3915 DAG.getConstant(Log2b, dl, MVT::i32));
3916 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);