blob: c64d882d69a462a7c6fb110f0db589f8fe71c25c [file] [log] [blame]
Chris Lattner3a4d1b22005-01-07 07:44:53 +00001//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Chris Lattner3a4d1b22005-01-07 07:44:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Chris Lattner3a4d1b22005-01-07 07:44:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Target/TargetLowering.h"
Jakob Stoklund Olesen75fbe902012-05-04 02:19:22 +000015#include "llvm/ADT/BitVector.h"
Owen Andersone2f23a32007-09-07 04:06:50 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/CodeGen/Analysis.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineJumpTableInfo.h"
21#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalVariable.h"
Bill Wendling908bf812014-01-06 00:43:20 +000025#include "llvm/IR/LLVMContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCExpr.h"
Nadav Rotem8b24a732011-06-01 12:51:46 +000028#include "llvm/Support/CommandLine.h"
Torok Edwin56d06592009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf0b24d22006-01-30 04:09:27 +000030#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetLoweringObjectFile.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000035#include <cctype>
Chris Lattner3a4d1b22005-01-07 07:44:53 +000036using namespace llvm;
37
Aditya Nandakumar30531552014-11-13 21:29:21 +000038/// NOTE: The TargetMachine owns TLOF.
39TargetLowering::TargetLowering(const TargetMachine &tm)
40 : TargetLoweringBase(tm) {}
Chris Lattner6f809792005-01-16 07:28:11 +000041
Evan Cheng6af02632005-12-20 06:22:03 +000042const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
Craig Topperc0196b12014-04-14 00:51:57 +000043 return nullptr;
Evan Cheng6af02632005-12-20 06:22:03 +000044}
Evan Cheng9cdc16c2005-12-21 23:05:39 +000045
Tim Northoverf1450d82013-01-09 13:18:15 +000046/// Check whether a given call node is in tail position within its function. If
47/// so, it sets Chain to the input chain of the tail call.
48bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
49 SDValue &Chain) const {
50 const Function *F = DAG.getMachineFunction().getFunction();
51
52 // Conservatively require the attributes of the call to match those of
53 // the return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +000054 AttributeSet CallerAttrs = F->getAttributes();
55 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
Tim Northoverf1450d82013-01-09 13:18:15 +000056 .removeAttribute(Attribute::NoAlias).hasAttributes())
57 return false;
58
59 // It's not safe to eliminate the sign / zero extension of the return value.
Bill Wendling658d24d2013-01-18 21:53:16 +000060 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
61 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Tim Northoverf1450d82013-01-09 13:18:15 +000062 return false;
63
64 // Check if the only use is a function return node.
65 return isUsedByReturnOnly(Node, Chain);
66}
67
Andrew Trick74f4c742013-10-31 17:18:24 +000068/// \brief Set CallLoweringInfo attribute flags based on a call instruction
69/// and called function attributes.
70void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
71 unsigned AttrIdx) {
72 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
73 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
74 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
75 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
76 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
77 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
Reid Klecknerf5b76512014-01-31 23:50:57 +000078 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
Andrew Trick74f4c742013-10-31 17:18:24 +000079 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
80 Alignment = CS->getParamAlignment(AttrIdx);
81}
Tim Northoverf1450d82013-01-09 13:18:15 +000082
83/// Generate a libcall taking the given operands as arguments and returning a
84/// result of type RetVT.
Michael Gottesman7a801722013-08-13 17:54:56 +000085std::pair<SDValue, SDValue>
86TargetLowering::makeLibCall(SelectionDAG &DAG,
87 RTLIB::Libcall LC, EVT RetVT,
Craig Topper8fe40e02015-10-22 17:05:00 +000088 ArrayRef<SDValue> Ops,
Michael Gottesman7a801722013-08-13 17:54:56 +000089 bool isSigned, SDLoc dl,
90 bool doesNotReturn,
91 bool isReturnValueUsed) const {
Tim Northoverf1450d82013-01-09 13:18:15 +000092 TargetLowering::ArgListTy Args;
Craig Topper8fe40e02015-10-22 17:05:00 +000093 Args.reserve(Ops.size());
Tim Northoverf1450d82013-01-09 13:18:15 +000094
95 TargetLowering::ArgListEntry Entry;
Craig Topper8fe40e02015-10-22 17:05:00 +000096 for (SDValue Op : Ops) {
97 Entry.Node = Op;
Tim Northoverf1450d82013-01-09 13:18:15 +000098 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
Craig Topper8fe40e02015-10-22 17:05:00 +000099 Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
100 Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
Tim Northoverf1450d82013-01-09 13:18:15 +0000101 Args.push_back(Entry);
102 }
Michael Kupersteineaa16002015-10-25 08:14:05 +0000103
Ahmed Bougachae85a2d32015-03-26 22:46:58 +0000104 if (LC == RTLIB::UNKNOWN_LIBCALL)
105 report_fatal_error("Unsupported library call operation!");
Mehdi Amini44ede332015-07-09 02:09:04 +0000106 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
107 getPointerTy(DAG.getDataLayout()));
Tim Northoverf1450d82013-01-09 13:18:15 +0000108
109 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000110 TargetLowering::CallLoweringInfo CLI(DAG);
Petar Jovanovic5b436222015-03-23 12:28:13 +0000111 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000112 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +0000113 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000114 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
Petar Jovanovic5b436222015-03-23 12:28:13 +0000115 .setSExtResult(signExtend).setZExtResult(!signExtend);
Michael Gottesman7a801722013-08-13 17:54:56 +0000116 return LowerCallTo(CLI);
Tim Northoverf1450d82013-01-09 13:18:15 +0000117}
118
Sanjay Patelac6e9102015-12-29 22:11:50 +0000119/// Soften the operands of a comparison. This code is shared among BR_CC,
120/// SELECT_CC, and SETCC handlers.
Tim Northoverf1450d82013-01-09 13:18:15 +0000121void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
122 SDValue &NewLHS, SDValue &NewRHS,
123 ISD::CondCode &CCCode,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000124 SDLoc dl) const {
Tim Northoverf1450d82013-01-09 13:18:15 +0000125 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
126 && "Unsupported setcc type!");
127
128 // Expand into one or more soft-fp libcall(s).
129 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
Alexey Bataevb9288602015-07-15 08:39:35 +0000130 bool ShouldInvertCC = false;
Tim Northoverf1450d82013-01-09 13:18:15 +0000131 switch (CCCode) {
132 case ISD::SETEQ:
133 case ISD::SETOEQ:
134 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
135 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
136 break;
137 case ISD::SETNE:
138 case ISD::SETUNE:
139 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
140 (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
141 break;
142 case ISD::SETGE:
143 case ISD::SETOGE:
144 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
145 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
146 break;
147 case ISD::SETLT:
148 case ISD::SETOLT:
149 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
150 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
151 break;
152 case ISD::SETLE:
153 case ISD::SETOLE:
154 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
155 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
156 break;
157 case ISD::SETGT:
158 case ISD::SETOGT:
159 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
160 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
161 break;
162 case ISD::SETUO:
163 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
164 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
165 break;
166 case ISD::SETO:
167 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
168 (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
169 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000170 case ISD::SETONE:
171 // SETONE = SETOLT | SETOGT
172 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
173 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
174 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
175 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
176 break;
177 case ISD::SETUEQ:
Tim Northoverf1450d82013-01-09 13:18:15 +0000178 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
179 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000180 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
181 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
182 break;
183 default:
184 // Invert CC for unordered comparisons
185 ShouldInvertCC = true;
Tim Northoverf1450d82013-01-09 13:18:15 +0000186 switch (CCCode) {
Alexey Bataevb9288602015-07-15 08:39:35 +0000187 case ISD::SETULT:
188 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
Tim Northoverf1450d82013-01-09 13:18:15 +0000189 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
190 break;
Tim Northoverf1450d82013-01-09 13:18:15 +0000191 case ISD::SETULE:
Alexey Bataevb9288602015-07-15 08:39:35 +0000192 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
193 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
194 break;
195 case ISD::SETUGT:
196 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
Tim Northoverf1450d82013-01-09 13:18:15 +0000197 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
198 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000199 case ISD::SETUGE:
200 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
201 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000202 break;
203 default: llvm_unreachable("Do not know how to soften this setcc!");
204 }
205 }
206
207 // Use the target specific return value for comparions lib calls.
208 EVT RetVT = getCmpLibcallReturnType();
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000209 SDValue Ops[2] = {NewLHS, NewRHS};
Craig Topper8fe40e02015-10-22 17:05:00 +0000210 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
211 dl).first;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000212 NewRHS = DAG.getConstant(0, dl, RetVT);
Alexey Bataevb9288602015-07-15 08:39:35 +0000213
Tim Northoverf1450d82013-01-09 13:18:15 +0000214 CCCode = getCmpLibcallCC(LC1);
Alexey Bataevb9288602015-07-15 08:39:35 +0000215 if (ShouldInvertCC)
216 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
217
Tim Northoverf1450d82013-01-09 13:18:15 +0000218 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000219 SDValue Tmp = DAG.getNode(
220 ISD::SETCC, dl,
221 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
222 NewLHS, NewRHS, DAG.getCondCode(CCCode));
Craig Topper8fe40e02015-10-22 17:05:00 +0000223 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
224 dl).first;
Mehdi Amini44ede332015-07-09 02:09:04 +0000225 NewLHS = DAG.getNode(
226 ISD::SETCC, dl,
227 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
228 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
Tim Northoverf1450d82013-01-09 13:18:15 +0000229 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
230 NewRHS = SDValue();
231 }
232}
233
Sanjay Patelac6e9102015-12-29 22:11:50 +0000234/// Return the entry encoding for a jump table in the current function. The
235/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000236unsigned TargetLowering::getJumpTableEncoding() const {
237 // In non-pic modes, just use the address of a block.
238 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
239 return MachineJumpTableInfo::EK_BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000240
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000241 // In PIC mode, if the target supports a GPRel32 directive, use it.
Craig Topperc0196b12014-04-14 00:51:57 +0000242 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000243 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000244
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000245 // Otherwise, use a label difference.
246 return MachineJumpTableInfo::EK_LabelDifference32;
247}
248
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000249SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
250 SelectionDAG &DAG) const {
Chris Lattner547c7612010-01-26 06:53:37 +0000251 // If our PIC model is GP relative, use the global offset table as the base.
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000252 unsigned JTEncoding = getJumpTableEncoding();
253
254 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
255 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
Mehdi Amini44ede332015-07-09 02:09:04 +0000256 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000257
Evan Cheng797d56f2007-11-09 01:32:10 +0000258 return Table;
259}
260
Sanjay Patelac6e9102015-12-29 22:11:50 +0000261/// This returns the relocation base for the given PIC jumptable, the same as
262/// getPICJumpTableRelocBase, but as an MCExpr.
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000263const MCExpr *
Chris Lattner8a785d72010-01-26 06:28:43 +0000264TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
265 unsigned JTI,MCContext &Ctx) const{
Chris Lattner273735b2010-01-26 05:58:28 +0000266 // The normal PIC reloc base is the label at the start of the jump table.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000267 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000268}
269
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000270bool
271TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
272 // Assume that everything is safe in static mode.
273 if (getTargetMachine().getRelocationModel() == Reloc::Static)
274 return true;
275
276 // In dynamic-no-pic mode, assume that known defined values are safe.
277 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
Peter Collingbourne6a9d1772015-07-05 20:52:35 +0000278 GA && GA->getGlobal()->isStrongDefinitionForLinker())
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000279 return true;
280
281 // Otherwise assume nothing is safe.
282 return false;
283}
284
Chris Lattneree1dadb2006-02-04 02:13:02 +0000285//===----------------------------------------------------------------------===//
286// Optimization Methods
287//===----------------------------------------------------------------------===//
288
Sanjay Patelac6e9102015-12-29 22:11:50 +0000289/// Check to see if the specified operand of the specified instruction is a
290/// constant integer. If so, check to see if there are any bits set in the
291/// constant that are not demanded. If so, shrink the constant and return true.
Wesley Peck527da1b2010-11-23 03:31:01 +0000292bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000293 const APInt &Demanded) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000294 SDLoc dl(Op);
Bill Wendling6d271472009-03-04 00:18:06 +0000295
Chris Lattner118ddba2006-02-26 23:36:02 +0000296 // FIXME: ISD::SELECT, ISD::SELECT_CC
Dan Gohmane58ab792009-01-29 01:59:02 +0000297 switch (Op.getOpcode()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000298 default: break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000299 case ISD::XOR:
Bill Wendling6d271472009-03-04 00:18:06 +0000300 case ISD::AND:
301 case ISD::OR: {
302 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
303 if (!C) return false;
304
305 if (Op.getOpcode() == ISD::XOR &&
306 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
307 return false;
308
309 // if we can expand it to have all bits set, do it
310 if (C->getAPIntValue().intersects(~Demanded)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000311 EVT VT = Op.getValueType();
Bill Wendling6d271472009-03-04 00:18:06 +0000312 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
313 DAG.getConstant(Demanded &
Wesley Peck527da1b2010-11-23 03:31:01 +0000314 C->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000315 dl, VT));
Bill Wendling6d271472009-03-04 00:18:06 +0000316 return CombineTo(Op, New);
317 }
318
Nate Begemandc7bba92006-02-03 22:24:05 +0000319 break;
320 }
Bill Wendling6d271472009-03-04 00:18:06 +0000321 }
322
Nate Begemandc7bba92006-02-03 22:24:05 +0000323 return false;
324}
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000325
Sanjay Patelac6e9102015-12-29 22:11:50 +0000326/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
327/// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
328/// generalized for targets with other types of implicit widening casts.
Dan Gohmanad3e5492009-04-08 00:15:30 +0000329bool
330TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
331 unsigned BitWidth,
332 const APInt &Demanded,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000333 SDLoc dl) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000334 assert(Op.getNumOperands() == 2 &&
335 "ShrinkDemandedOp only supports binary operators!");
336 assert(Op.getNode()->getNumValues() == 1 &&
337 "ShrinkDemandedOp only supports nodes with one result!");
338
Hao Liu40914502014-05-29 09:19:07 +0000339 // Early return, as this function cannot handle vector types.
340 if (Op.getValueType().isVector())
341 return false;
342
Dan Gohmanad3e5492009-04-08 00:15:30 +0000343 // Don't do this if the node has another user, which may require the
344 // full value.
345 if (!Op.getNode()->hasOneUse())
346 return false;
347
348 // Search for the smallest integer type with free casts to and from
349 // Op's type. For expedience, just check power-of-2 integer types.
350 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Nadav Rotem33360d82012-12-19 07:39:08 +0000351 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
352 unsigned SmallVTBits = DemandedSize;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000353 if (!isPowerOf2_32(SmallVTBits))
354 SmallVTBits = NextPowerOf2(SmallVTBits);
355 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
Owen Anderson117c9e82009-08-12 00:36:31 +0000356 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000357 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
358 TLI.isZExtFree(SmallVT, Op.getValueType())) {
359 // We found a type with free casts.
360 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
361 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
362 Op.getNode()->getOperand(0)),
363 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
364 Op.getNode()->getOperand(1)));
Nadav Rotem33360d82012-12-19 07:39:08 +0000365 bool NeedZext = DemandedSize > SmallVTBits;
366 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
367 dl, Op.getValueType(), X);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000368 return CombineTo(Op, Z);
369 }
370 }
371 return false;
372}
373
Sanjay Patelac6e9102015-12-29 22:11:50 +0000374/// Look at Op. At this point, we know that only the DemandedMask bits of the
375/// result of Op are ever used downstream. If we can use this information to
376/// simplify Op, create a new simplified DAG node and return true, returning the
377/// original and new nodes in Old and New. Otherwise, analyze the expression and
378/// return a mask of KnownOne and KnownZero bits for the expression (used to
379/// simplify the caller). The KnownZero/One bits may only be accurate for those
380/// bits in the DemandedMask.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000381bool TargetLowering::SimplifyDemandedBits(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000382 const APInt &DemandedMask,
383 APInt &KnownZero,
384 APInt &KnownOne,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000385 TargetLoweringOpt &TLO,
386 unsigned Depth) const {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000387 unsigned BitWidth = DemandedMask.getBitWidth();
Dan Gohman1d459e42009-12-11 21:31:27 +0000388 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000389 "Mask size mismatches value type size!");
390 APInt NewMask = DemandedMask;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000391 SDLoc dl(Op);
Mehdi Amini9639d652015-07-09 02:09:20 +0000392 auto &DL = TLO.DAG.getDataLayout();
Chris Lattner0184f882007-05-17 18:19:23 +0000393
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000394 // Don't know anything.
395 KnownZero = KnownOne = APInt(BitWidth, 0);
396
Nate Begeman8a77efe2006-02-16 21:11:51 +0000397 // Other users may use these bits.
Wesley Peck527da1b2010-11-23 03:31:01 +0000398 if (!Op.getNode()->hasOneUse()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000399 if (Depth != 0) {
Wesley Peck527da1b2010-11-23 03:31:01 +0000400 // If not at the root, Just compute the KnownZero/KnownOne bits to
Nate Begeman8a77efe2006-02-16 21:11:51 +0000401 // simplify things downstream.
Jay Foada0653a32014-05-14 21:14:37 +0000402 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Nate Begeman8a77efe2006-02-16 21:11:51 +0000403 return false;
404 }
405 // If this is the root being simplified, allow it to have multiple uses,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000406 // just set the NewMask to all bits.
407 NewMask = APInt::getAllOnesValue(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000408 } else if (DemandedMask == 0) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000409 // Not demanding any bits from Op.
410 if (Op.getOpcode() != ISD::UNDEF)
Dale Johannesen84935752009-02-06 23:05:02 +0000411 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000412 return false;
413 } else if (Depth == 6) { // Limit search depth.
414 return false;
415 }
416
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000417 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000418 switch (Op.getOpcode()) {
419 case ISD::Constant:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000420 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000421 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
422 KnownZero = ~KnownOne;
Chris Lattner118ddba2006-02-26 23:36:02 +0000423 return false; // Don't fall through, will infinitely loop.
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000424 case ISD::AND:
Chris Lattnera60751d2006-02-27 00:36:27 +0000425 // If the RHS is a constant, check to see if the LHS would be zero without
426 // using the bits from the RHS. Below, we use knowledge about the RHS to
427 // simplify the LHS, here we're using information from the LHS to simplify
428 // the RHS.
429 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000430 APInt LHSZero, LHSOne;
Dale Johannesend2b48112011-01-10 21:53:07 +0000431 // Do not increment Depth here; that can cause an infinite loop.
Jay Foada0653a32014-05-14 21:14:37 +0000432 TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
Chris Lattnera60751d2006-02-27 00:36:27 +0000433 // If the LHS already has zeros where RHSC does, this and is dead.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000434 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000435 return TLO.CombineTo(Op, Op.getOperand(0));
436 // If any of the set bits in the RHS are known zero on the LHS, shrink
437 // the constant.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000438 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000439 return true;
440 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000441
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000442 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000443 KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000444 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000445 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000446 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000447 KnownZero2, KnownOne2, TLO, Depth+1))
448 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000449 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
450
Nate Begeman8a77efe2006-02-16 21:11:51 +0000451 // If all of the demanded bits are known one on one side, return the other.
452 // These bits cannot contribute to the result of the 'and'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000453 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000454 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000455 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000456 return TLO.CombineTo(Op, Op.getOperand(1));
457 // If all of the demanded bits in the inputs are known zeros, return zero.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000458 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000459 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000460 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000461 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000462 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000463 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000464 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000465 return true;
466
Nate Begeman8a77efe2006-02-16 21:11:51 +0000467 // Output known-1 bits are only known if set in both the LHS & RHS.
468 KnownOne &= KnownOne2;
469 // Output known-0 are known to be clear if zero in either the LHS | RHS.
470 KnownZero |= KnownZero2;
471 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000472 case ISD::OR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000473 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000474 KnownOne, TLO, Depth+1))
475 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000476 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000477 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000478 KnownZero2, KnownOne2, TLO, Depth+1))
479 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000480 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
481
Nate Begeman8a77efe2006-02-16 21:11:51 +0000482 // If all of the demanded bits are known zero on one side, return the other.
483 // These bits cannot contribute to the result of the 'or'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000484 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000485 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000486 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000487 return TLO.CombineTo(Op, Op.getOperand(1));
488 // If all of the potentially set bits on one side are known to be set on
489 // the other side, just use the 'other' side.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000490 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000491 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000492 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000493 return TLO.CombineTo(Op, Op.getOperand(1));
494 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000495 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000496 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000497 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000498 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000499 return true;
500
Nate Begeman8a77efe2006-02-16 21:11:51 +0000501 // Output known-0 bits are only known if clear in both the LHS & RHS.
502 KnownZero &= KnownZero2;
503 // Output known-1 are known to be set if set in either the LHS | RHS.
504 KnownOne |= KnownOne2;
505 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000506 case ISD::XOR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000507 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000508 KnownOne, TLO, Depth+1))
509 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000510 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000511 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000512 KnownOne2, TLO, Depth+1))
513 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000514 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
515
Nate Begeman8a77efe2006-02-16 21:11:51 +0000516 // If all of the demanded bits are known zero on one side, return the other.
517 // These bits cannot contribute to the result of the 'xor'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000518 if ((KnownZero & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000519 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000520 if ((KnownZero2 & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000521 return TLO.CombineTo(Op, Op.getOperand(1));
Dan Gohmanad3e5492009-04-08 00:15:30 +0000522 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000523 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000524 return true;
525
Chris Lattner5d5916b2006-11-27 21:50:02 +0000526 // If all of the unknown bits are known to be zero on one side or the other
527 // (but not both) turn this into an *inclusive* or.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000528 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000529 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
Dale Johannesen400dc2e2009-02-06 21:50:26 +0000530 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
Chris Lattner5d5916b2006-11-27 21:50:02 +0000531 Op.getOperand(0),
532 Op.getOperand(1)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000533
Nate Begeman8a77efe2006-02-16 21:11:51 +0000534 // Output known-0 bits are known if clear or set in both the LHS & RHS.
535 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
536 // Output known-1 are known to be set if set in only one of the LHS, RHS.
537 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
Wesley Peck527da1b2010-11-23 03:31:01 +0000538
Nate Begeman8a77efe2006-02-16 21:11:51 +0000539 // If all of the demanded bits on one side are known, and all of the set
540 // bits on that side are also known to be set on the other side, turn this
541 // into an AND, as we know the bits will be cleared.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000542 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Joel Jones828531f2012-04-17 22:23:10 +0000543 // NB: it is okay if more bits are known than are requested
Stephen Lincfe7f352013-07-08 00:37:03 +0000544 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
Joel Jones828531f2012-04-17 22:23:10 +0000545 if (KnownOne == KnownOne2) { // set bits are the same on both sides
Owen Anderson53aa7a92009-08-10 22:56:29 +0000546 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000547 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000548 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
Dale Johannesenf1163e92009-02-03 00:47:48 +0000549 Op.getOperand(0), ANDC));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000550 }
551 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000552
Nate Begeman8a77efe2006-02-16 21:11:51 +0000553 // If the RHS is a constant, see if we can simplify it.
Torok Edwin613d7af2008-04-06 21:23:02 +0000554 // for XOR, we prefer to force bits to 1 if they will make a -1.
555 // if we can't force bits, try to shrink constant
556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
557 APInt Expanded = C->getAPIntValue() | (~NewMask);
558 // if we can expand it to have all bits set, do it
559 if (Expanded.isAllOnesValue()) {
560 if (Expanded != C->getAPIntValue()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000561 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000562 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000563 TLO.DAG.getConstant(Expanded, dl, VT));
Torok Edwin613d7af2008-04-06 21:23:02 +0000564 return TLO.CombineTo(Op, New);
565 }
566 // if it already has all the bits set, nothing to change
567 // but don't shrink either!
568 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
569 return true;
570 }
571 }
572
Nate Begeman8a77efe2006-02-16 21:11:51 +0000573 KnownZero = KnownZeroOut;
574 KnownOne = KnownOneOut;
575 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000576 case ISD::SELECT:
Wesley Peck527da1b2010-11-23 03:31:01 +0000577 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000578 KnownOne, TLO, Depth+1))
579 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000580 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000581 KnownOne2, TLO, Depth+1))
582 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000583 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
584 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
585
Nate Begeman8a77efe2006-02-16 21:11:51 +0000586 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000587 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000588 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000589
Nate Begeman8a77efe2006-02-16 21:11:51 +0000590 // Only known if known in both the LHS and RHS.
591 KnownOne &= KnownOne2;
592 KnownZero &= KnownZero2;
593 break;
Chris Lattner118ddba2006-02-26 23:36:02 +0000594 case ISD::SELECT_CC:
Wesley Peck527da1b2010-11-23 03:31:01 +0000595 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +0000596 KnownOne, TLO, Depth+1))
597 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000598 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
Chris Lattner118ddba2006-02-26 23:36:02 +0000599 KnownOne2, TLO, Depth+1))
600 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000601 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
602 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
603
Chris Lattner118ddba2006-02-26 23:36:02 +0000604 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000605 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Chris Lattner118ddba2006-02-26 23:36:02 +0000606 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000607
Chris Lattner118ddba2006-02-26 23:36:02 +0000608 // Only known if known in both the LHS and RHS.
609 KnownOne &= KnownOne2;
610 KnownZero &= KnownZero2;
611 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000612 case ISD::SHL:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000613 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000614 unsigned ShAmt = SA->getZExtValue();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000615 SDValue InOp = Op.getOperand(0);
Chris Lattner9a861a82007-04-17 21:14:16 +0000616
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000617 // If the shift count is an invalid immediate, don't do anything.
618 if (ShAmt >= BitWidth)
619 break;
620
Chris Lattner9a861a82007-04-17 21:14:16 +0000621 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
622 // single shift. We can do this if the bottom bits (which are shifted
623 // out) are never demanded.
624 if (InOp.getOpcode() == ISD::SRL &&
625 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000626 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000627 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000628 unsigned Opc = ISD::SHL;
629 int Diff = ShAmt-C1;
630 if (Diff < 0) {
631 Diff = -Diff;
632 Opc = ISD::SRL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000633 }
634
635 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000636 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Owen Anderson53aa7a92009-08-10 22:56:29 +0000637 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000638 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000639 InOp.getOperand(0), NewSA));
640 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000641 }
642
Dan Gohman08186842010-07-23 18:03:30 +0000643 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
Nate Begeman8a77efe2006-02-16 21:11:51 +0000644 KnownZero, KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000645 return true;
Dan Gohman08186842010-07-23 18:03:30 +0000646
647 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
648 // are not demanded. This will likely allow the anyext to be folded away.
649 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
650 SDValue InnerOp = InOp.getNode()->getOperand(0);
651 EVT InnerVT = InnerOp.getValueType();
Eli Friedman053a7242011-12-09 01:16:26 +0000652 unsigned InnerBits = InnerVT.getSizeInBits();
653 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
Dan Gohman08186842010-07-23 18:03:30 +0000654 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +0000655 EVT ShTy = getShiftAmountTy(InnerVT, DL);
Dan Gohman55e24462010-07-23 21:08:12 +0000656 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
657 ShTy = InnerVT;
Dan Gohman08186842010-07-23 18:03:30 +0000658 SDValue NarrowShl =
659 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000660 TLO.DAG.getConstant(ShAmt, dl, ShTy));
Dan Gohman08186842010-07-23 18:03:30 +0000661 return
662 TLO.CombineTo(Op,
663 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
664 NarrowShl));
665 }
Richard Sandiford374a0e52013-10-16 10:26:19 +0000666 // Repeat the SHL optimization above in cases where an extension
667 // intervenes: (shl (anyext (shr x, c1)), c2) to
668 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
669 // aren't demanded (as above) and that the shifted upper c1 bits of
670 // x aren't demanded.
671 if (InOp.hasOneUse() &&
672 InnerOp.getOpcode() == ISD::SRL &&
673 InnerOp.hasOneUse() &&
674 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
675 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
676 ->getZExtValue();
677 if (InnerShAmt < ShAmt &&
678 InnerShAmt < InnerBits &&
679 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
680 NewMask.trunc(ShAmt) == 0) {
681 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000682 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
Richard Sandiford374a0e52013-10-16 10:26:19 +0000683 Op.getOperand(1).getValueType());
684 EVT VT = Op.getValueType();
685 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
686 InnerOp.getOperand(0));
687 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
688 NewExt, NewSA));
689 }
690 }
Dan Gohman08186842010-07-23 18:03:30 +0000691 }
692
Dan Gohmaneffb8942008-09-12 16:56:44 +0000693 KnownZero <<= SA->getZExtValue();
694 KnownOne <<= SA->getZExtValue();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000695 // low bits known zero.
Dan Gohmaneffb8942008-09-12 16:56:44 +0000696 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000697 }
698 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000699 case ISD::SRL:
700 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000701 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000702 unsigned ShAmt = SA->getZExtValue();
Duncan Sands13237ac2008-06-06 12:08:01 +0000703 unsigned VTSize = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000704 SDValue InOp = Op.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +0000705
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000706 // If the shift count is an invalid immediate, don't do anything.
707 if (ShAmt >= BitWidth)
708 break;
709
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000710 APInt InDemandedMask = (NewMask << ShAmt);
711
712 // If the shift is exact, then it does demand the low bits (and knows that
713 // they are zero).
714 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
715 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
716
Chris Lattner9a861a82007-04-17 21:14:16 +0000717 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
718 // single shift. We can do this if the top bits (which are shifted out)
719 // are never demanded.
720 if (InOp.getOpcode() == ISD::SHL &&
721 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000722 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000723 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000724 unsigned Opc = ISD::SRL;
725 int Diff = ShAmt-C1;
726 if (Diff < 0) {
727 Diff = -Diff;
728 Opc = ISD::SHL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000729 }
730
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000731 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000732 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Dale Johannesenf1163e92009-02-03 00:47:48 +0000733 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000734 InOp.getOperand(0), NewSA));
735 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000736 }
737
Nate Begeman8a77efe2006-02-16 21:11:51 +0000738 // Compute the new bits that are at the top now.
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000739 if (SimplifyDemandedBits(InOp, InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000740 KnownZero, KnownOne, TLO, Depth+1))
741 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000743 KnownZero = KnownZero.lshr(ShAmt);
744 KnownOne = KnownOne.lshr(ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000745
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000746 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000747 KnownZero |= HighBits; // High bits known zero.
Nate Begeman8a77efe2006-02-16 21:11:51 +0000748 }
749 break;
750 case ISD::SRA:
Dan Gohmane58ab792009-01-29 01:59:02 +0000751 // If this is an arithmetic shift right and only the low-bit is set, we can
752 // always convert this into a logical shr, even if the shift amount is
753 // variable. The low bit of the shift cannot be an input sign bit unless
754 // the shift amount is >= the size of the datatype, which is undefined.
Eli Friedman053a7242011-12-09 01:16:26 +0000755 if (NewMask == 1)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000756 return TLO.CombineTo(Op,
757 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
758 Op.getOperand(0), Op.getOperand(1)));
Dan Gohmane58ab792009-01-29 01:59:02 +0000759
Nate Begeman8a77efe2006-02-16 21:11:51 +0000760 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000761 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000762 unsigned ShAmt = SA->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +0000763
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000764 // If the shift count is an invalid immediate, don't do anything.
765 if (ShAmt >= BitWidth)
766 break;
767
768 APInt InDemandedMask = (NewMask << ShAmt);
Chris Lattner10c65372006-05-08 17:22:53 +0000769
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000770 // If the shift is exact, then it does demand the low bits (and knows that
771 // they are zero).
772 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
773 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
774
Chris Lattner10c65372006-05-08 17:22:53 +0000775 // If any of the demanded bits are produced by the sign extension, we also
776 // demand the input sign bit.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000777 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
778 if (HighBits.intersects(NewMask))
Dan Gohman1d459e42009-12-11 21:31:27 +0000779 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000780
Chris Lattner10c65372006-05-08 17:22:53 +0000781 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000782 KnownZero, KnownOne, TLO, Depth+1))
783 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000784 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000785 KnownZero = KnownZero.lshr(ShAmt);
786 KnownOne = KnownOne.lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000787
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000788 // Handle the sign bit, adjusted to where it is now in the mask.
789 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000790
Nate Begeman8a77efe2006-02-16 21:11:51 +0000791 // If the input sign bit is known to be zero, or if none of the top bits
792 // are demanded, turn this into an unsigned shift right.
Benjamin Kramerc2ae7672015-06-26 14:51:49 +0000793 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
794 SDNodeFlags Flags;
795 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
796 return TLO.CombineTo(Op,
797 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
798 Op.getOperand(1), &Flags));
799 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000800
801 int Log2 = NewMask.exactLogBase2();
802 if (Log2 >= 0) {
803 // The bit must come from the sign.
804 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000805 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000806 Op.getOperand(1).getValueType());
807 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
808 Op.getOperand(0), NewSA));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000809 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000810
811 if (KnownOne.intersects(SignBit))
812 // New bits are known one.
813 KnownOne |= HighBits;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000814 }
815 break;
816 case ISD::SIGN_EXTEND_INREG: {
Nadav Rotem57935242012-01-15 19:27:55 +0000817 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
818
819 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
820 // If we only care about the highest bit, don't bother shifting right.
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000821 if (MsbMask == NewMask) {
Nadav Rotem57935242012-01-15 19:27:55 +0000822 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
823 SDValue InOp = Op.getOperand(0);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000824 unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
825 bool AlreadySignExtended =
826 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
827 // However if the input is already sign extended we expect the sign
828 // extension to be dropped altogether later and do not simplify.
829 if (!AlreadySignExtended) {
830 // Compute the correct shift amount type, which must be getShiftAmountTy
831 // for scalar types after legalization.
832 EVT ShiftAmtTy = Op.getValueType();
833 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
Mehdi Amini9639d652015-07-09 02:09:20 +0000834 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
Eli Friedman18a4c312012-01-31 01:08:03 +0000835
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000836 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
837 ShiftAmtTy);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000838 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
839 Op.getValueType(), InOp,
840 ShiftAmt));
841 }
Nadav Rotem57935242012-01-15 19:27:55 +0000842 }
Nate Begeman8a77efe2006-02-16 21:11:51 +0000843
Wesley Peck527da1b2010-11-23 03:31:01 +0000844 // Sign extension. Compute the demanded bits in the result that are not
Nate Begeman8a77efe2006-02-16 21:11:51 +0000845 // present in the input.
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000846 APInt NewBits =
847 APInt::getHighBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000848 BitWidth - ExVT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000849
Chris Lattner118ddba2006-02-26 23:36:02 +0000850 // If none of the extended bits are demanded, eliminate the sextinreg.
Eli Friedman460ad412010-08-02 04:42:25 +0000851 if ((NewBits & NewMask) == 0)
Chris Lattner118ddba2006-02-26 23:36:02 +0000852 return TLO.CombineTo(Op, Op.getOperand(0));
853
Jay Foad583abbc2010-12-07 08:25:19 +0000854 APInt InSignBit =
Nadav Rotem57935242012-01-15 19:27:55 +0000855 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000856 APInt InputDemandedBits =
857 APInt::getLowBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000858 ExVT.getScalarType().getSizeInBits()) &
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000859 NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +0000860
Chris Lattner118ddba2006-02-26 23:36:02 +0000861 // Since the sign extended bits are demanded, we know that the sign
Nate Begeman8a77efe2006-02-16 21:11:51 +0000862 // bit is demanded.
Chris Lattner118ddba2006-02-26 23:36:02 +0000863 InputDemandedBits |= InSignBit;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000864
865 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
866 KnownZero, KnownOne, TLO, Depth+1))
867 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000868 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Nate Begeman8a77efe2006-02-16 21:11:51 +0000869
870 // If the sign bit of the input is known set or clear, then we know the
871 // top bits of the result.
Wesley Peck527da1b2010-11-23 03:31:01 +0000872
Chris Lattner118ddba2006-02-26 23:36:02 +0000873 // If the input sign bit is known zero, convert this into a zero extension.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000874 if (KnownZero.intersects(InSignBit))
Wesley Peck527da1b2010-11-23 03:31:01 +0000875 return TLO.CombineTo(Op,
Nadav Rotem57935242012-01-15 19:27:55 +0000876 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
Wesley Peck527da1b2010-11-23 03:31:01 +0000877
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000878 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
Nate Begeman8a77efe2006-02-16 21:11:51 +0000879 KnownOne |= NewBits;
880 KnownZero &= ~NewBits;
Chris Lattner118ddba2006-02-26 23:36:02 +0000881 } else { // Input sign bit unknown
Nate Begeman8a77efe2006-02-16 21:11:51 +0000882 KnownZero &= ~NewBits;
883 KnownOne &= ~NewBits;
884 }
885 break;
886 }
Matt Arsenault2adca602014-05-12 17:14:48 +0000887 case ISD::BUILD_PAIR: {
888 EVT HalfVT = Op.getOperand(0).getValueType();
889 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
890
891 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
892 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
893
894 APInt KnownZeroLo, KnownOneLo;
895 APInt KnownZeroHi, KnownOneHi;
896
897 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
898 KnownOneLo, TLO, Depth + 1))
899 return true;
900
901 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
902 KnownOneHi, TLO, Depth + 1))
903 return true;
904
905 KnownZero = KnownZeroLo.zext(BitWidth) |
906 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
907
908 KnownOne = KnownOneLo.zext(BitWidth) |
909 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
910 break;
911 }
Chris Lattner118ddba2006-02-26 23:36:02 +0000912 case ISD::ZERO_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000913 unsigned OperandBitWidth =
914 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000915 APInt InMask = NewMask.trunc(OperandBitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000916
Chris Lattner118ddba2006-02-26 23:36:02 +0000917 // If none of the top bits are demanded, convert this into an any_extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000918 APInt NewBits =
919 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
920 if (!NewBits.intersects(NewMask))
Dale Johannesenf1163e92009-02-03 00:47:48 +0000921 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +0000922 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +0000923 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000924
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000925 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +0000926 KnownZero, KnownOne, TLO, Depth+1))
927 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000928 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +0000929 KnownZero = KnownZero.zext(BitWidth);
930 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +0000931 KnownZero |= NewBits;
932 break;
933 }
934 case ISD::SIGN_EXTEND: {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000935 EVT InVT = Op.getOperand(0).getValueType();
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000936 unsigned InBits = InVT.getScalarType().getSizeInBits();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000937 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
Dan Gohman44b4c072008-03-11 21:29:43 +0000938 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000939 APInt NewBits = ~InMask & NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +0000940
Chris Lattner118ddba2006-02-26 23:36:02 +0000941 // If none of the top bits are demanded, convert this into an any_extend.
942 if (NewBits == 0)
Dale Johannesenf1163e92009-02-03 00:47:48 +0000943 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
944 Op.getValueType(),
945 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000946
Chris Lattner118ddba2006-02-26 23:36:02 +0000947 // Since some of the sign extended bits are demanded, we know that the sign
948 // bit is demanded.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000949 APInt InDemandedBits = InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +0000950 InDemandedBits |= InSignBit;
Jay Foad583abbc2010-12-07 08:25:19 +0000951 InDemandedBits = InDemandedBits.trunc(InBits);
Wesley Peck527da1b2010-11-23 03:31:01 +0000952
953 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +0000954 KnownOne, TLO, Depth+1))
955 return true;
Jay Foad583abbc2010-12-07 08:25:19 +0000956 KnownZero = KnownZero.zext(BitWidth);
957 KnownOne = KnownOne.zext(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000958
Chris Lattner118ddba2006-02-26 23:36:02 +0000959 // If the sign bit is known zero, convert this to a zero extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000960 if (KnownZero.intersects(InSignBit))
Dale Johannesenf1163e92009-02-03 00:47:48 +0000961 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +0000962 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +0000963 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000964
Chris Lattner118ddba2006-02-26 23:36:02 +0000965 // If the sign bit is known one, the top bits match.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000966 if (KnownOne.intersects(InSignBit)) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000967 KnownOne |= NewBits;
968 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +0000969 } else { // Otherwise, top bits aren't known.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000970 assert((KnownOne & NewBits) == 0);
971 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +0000972 }
973 break;
974 }
975 case ISD::ANY_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000976 unsigned OperandBitWidth =
977 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000978 APInt InMask = NewMask.trunc(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000979 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +0000980 KnownZero, KnownOne, TLO, Depth+1))
981 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000982 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +0000983 KnownZero = KnownZero.zext(BitWidth);
984 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +0000985 break;
986 }
Chris Lattner0f649322006-05-05 22:32:12 +0000987 case ISD::TRUNCATE: {
Chris Lattner86a14672006-05-06 00:11:52 +0000988 // Simplify the input, using demanded bit information, and compute the known
989 // zero/one bits live out.
Dan Gohmanc3c3c682010-03-01 17:59:21 +0000990 unsigned OperandBitWidth =
991 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000992 APInt TruncMask = NewMask.zext(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000993 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
Chris Lattner0f649322006-05-05 22:32:12 +0000994 KnownZero, KnownOne, TLO, Depth+1))
995 return true;
Jay Foad583abbc2010-12-07 08:25:19 +0000996 KnownZero = KnownZero.trunc(BitWidth);
997 KnownOne = KnownOne.trunc(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000998
Chris Lattner86a14672006-05-06 00:11:52 +0000999 // If the input is only used by this truncate, see if we can shrink it based
1000 // on the known demanded bits.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001001 if (Op.getOperand(0).getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001002 SDValue In = Op.getOperand(0);
Chris Lattner86a14672006-05-06 00:11:52 +00001003 switch (In.getOpcode()) {
1004 default: break;
1005 case ISD::SRL:
1006 // Shrink SRL by a constant if none of the high bits shifted in are
1007 // demanded.
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001008 if (TLO.LegalTypes() &&
1009 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1010 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1011 // undesirable.
1012 break;
1013 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1014 if (!ShAmt)
1015 break;
Owen Anderson9c128342011-04-13 23:22:23 +00001016 SDValue Shift = In.getOperand(1);
1017 if (TLO.LegalTypes()) {
1018 uint64_t ShVal = ShAmt->getZExtValue();
Mehdi Amini9639d652015-07-09 02:09:20 +00001019 Shift = TLO.DAG.getConstant(ShVal, dl,
1020 getShiftAmountTy(Op.getValueType(), DL));
Owen Anderson9c128342011-04-13 23:22:23 +00001021 }
1022
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001023 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1024 OperandBitWidth - BitWidth);
Jay Foad583abbc2010-12-07 08:25:19 +00001025 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001026
1027 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1028 // None of the shifted in bits are needed. Add a truncate of the
1029 // shift input, then shift it.
1030 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +00001031 Op.getValueType(),
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001032 In.getOperand(0));
1033 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1034 Op.getValueType(),
Wesley Peck527da1b2010-11-23 03:31:01 +00001035 NewTrunc,
Owen Anderson9c128342011-04-13 23:22:23 +00001036 Shift));
Chris Lattner86a14672006-05-06 00:11:52 +00001037 }
1038 break;
1039 }
1040 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001041
1042 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0f649322006-05-05 22:32:12 +00001043 break;
1044 }
Chris Lattner118ddba2006-02-26 23:36:02 +00001045 case ISD::AssertZext: {
Owen Anderson40d756e2011-09-03 00:26:49 +00001046 // AssertZext demands all of the high bits, plus any of the low bits
1047 // demanded by its users.
1048 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1049 APInt InMask = APInt::getLowBitsSet(BitWidth,
1050 VT.getSizeInBits());
1051 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001052 KnownZero, KnownOne, TLO, Depth+1))
1053 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001054 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmand83e3e72010-06-03 20:21:33 +00001055
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001056 KnownZero |= ~InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +00001057 break;
1058 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001059 case ISD::BITCAST:
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001060 // If this is an FP->Int bitcast and if the sign bit is the only
1061 // thing demanded, turn this into a FGETSIGN.
Eli Friedman2ec82492011-12-15 02:07:20 +00001062 if (!TLO.LegalOperations() &&
1063 !Op.getValueType().isVector() &&
Eli Friedman53218b62011-11-09 22:25:12 +00001064 !Op.getOperand(0).getValueType().isVector() &&
Nadav Rotem504cf0c2011-06-12 14:56:55 +00001065 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1066 Op.getOperand(0).getValueType().isFloatingPoint()) {
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001067 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1068 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
Chih-Hung Hsiehed7d81e2015-12-03 22:02:40 +00001069 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1070 Op.getOperand(0).getValueType() != MVT::f128) {
1071 // Cannot eliminate/lower SHL for f128 yet.
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001072 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
Chris Lattnerde272b12007-12-22 21:35:38 +00001073 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1074 // place. We expect the SHL to be eliminated by other optimizations.
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001075 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001076 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1077 if (!OpVTLegal && OpVTSizeInBits > 32)
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001078 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
Duncan Sands13237ac2008-06-06 12:08:01 +00001079 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001080 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
Stuart Hastings4a4e5a22011-05-19 18:48:20 +00001081 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1082 Op.getValueType(),
Chris Lattnerde272b12007-12-22 21:35:38 +00001083 Sign, ShAmt));
1084 }
1085 }
Chris Lattnerde272b12007-12-22 21:35:38 +00001086 break;
Dan Gohmanad3e5492009-04-08 00:15:30 +00001087 case ISD::ADD:
1088 case ISD::MUL:
1089 case ISD::SUB: {
1090 // Add, Sub, and Mul don't demand any bits in positions beyond that
1091 // of the highest bit demanded of them.
1092 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1093 BitWidth - NewMask.countLeadingZeros());
1094 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1095 KnownOne2, TLO, Depth+1))
1096 return true;
1097 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1098 KnownOne2, TLO, Depth+1))
1099 return true;
1100 // See if the operation should be performed at a smaller bit width.
Dan Gohman600f62b2010-06-24 14:30:44 +00001101 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +00001102 return true;
1103 }
1104 // FALL THROUGH
Dan Gohman38dc08f2008-05-06 00:53:29 +00001105 default:
Jay Foada0653a32014-05-14 21:14:37 +00001106 // Just use computeKnownBits to compute output bits.
1107 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Chris Lattnerab816402006-02-27 01:00:42 +00001108 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +00001109 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001110
Chris Lattner118ddba2006-02-26 23:36:02 +00001111 // If we know the value of all of the demanded bits, return this as a
1112 // constant.
Matthias Braun56a78142015-05-20 18:54:02 +00001113 if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1114 // Avoid folding to a constant if any OpaqueConstant is involved.
1115 const SDNode *N = Op.getNode();
1116 for (SDNodeIterator I = SDNodeIterator::begin(N),
1117 E = SDNodeIterator::end(N); I != E; ++I) {
1118 SDNode *Op = *I;
1119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1120 if (C->isOpaque())
1121 return false;
1122 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001123 return TLO.CombineTo(Op,
1124 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
Matthias Braun56a78142015-05-20 18:54:02 +00001125 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001126
Nate Begeman8a77efe2006-02-16 21:11:51 +00001127 return false;
1128}
1129
Sanjay Patelac6e9102015-12-29 22:11:50 +00001130/// Determine which of the bits specified in Mask are known to be either zero or
1131/// one and return them in the KnownZero/KnownOne bitsets.
Jay Foada0653a32014-05-14 21:14:37 +00001132void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1133 APInt &KnownZero,
1134 APInt &KnownOne,
1135 const SelectionDAG &DAG,
1136 unsigned Depth) const {
Chris Lattner6c1321c2006-04-02 06:19:46 +00001137 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1138 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1139 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1140 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
Chris Lattnerf0b24d22006-01-30 04:09:27 +00001141 "Should use MaskedValueIsZero if you don't know whether Op"
1142 " is a target node!");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001143 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
Evan Cheng9cdc16c2005-12-21 23:05:39 +00001144}
Chris Lattner32fef532006-01-26 20:37:03 +00001145
Sanjay Patelac6e9102015-12-29 22:11:50 +00001146/// This method can be implemented by targets that want to expose additional
1147/// information about sign bits to the DAG Combiner.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001148unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
Matt Arsenaultcf6f6882014-04-04 20:13:13 +00001149 const SelectionDAG &,
Chris Lattner7206d742006-05-06 09:27:13 +00001150 unsigned Depth) const {
1151 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1152 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1153 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1154 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1155 "Should use ComputeNumSignBits if you don't know whether Op"
1156 " is a target node!");
1157 return 1;
1158}
1159
Sanjay Patelac6e9102015-12-29 22:11:50 +00001160/// Test if the given value is known to have exactly one bit set. This differs
1161/// from computeKnownBits in that it doesn't need to determine which bit is set.
Dale Johannesencc5fc442009-02-11 19:19:41 +00001162static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
Dan Gohmanaaee6c92009-02-15 23:59:32 +00001163 // A left-shift of a constant one will have exactly one bit set, because
1164 // shifting the bit off the end is undefined.
1165 if (Val.getOpcode() == ISD::SHL)
1166 if (ConstantSDNode *C =
1167 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1168 if (C->getAPIntValue() == 1)
1169 return true;
Dan Gohmane58ab792009-01-29 01:59:02 +00001170
Dan Gohmanaaee6c92009-02-15 23:59:32 +00001171 // Similarly, a right-shift of a constant sign-bit will have exactly
1172 // one bit set.
1173 if (Val.getOpcode() == ISD::SRL)
1174 if (ConstantSDNode *C =
1175 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1176 if (C->getAPIntValue().isSignBit())
1177 return true;
1178
1179 // More could be done here, though the above checks are enough
1180 // to handle some common cases.
1181
Jay Foada0653a32014-05-14 21:14:37 +00001182 // Fall back to computeKnownBits to catch other known cases.
Owen Anderson53aa7a92009-08-10 22:56:29 +00001183 EVT OpVT = Val.getValueType();
Dan Gohman4cec5432010-03-02 02:14:38 +00001184 unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
Dan Gohmane58ab792009-01-29 01:59:02 +00001185 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00001186 DAG.computeKnownBits(Val, KnownZero, KnownOne);
Dale Johannesencc5fc442009-02-11 19:19:41 +00001187 return (KnownZero.countPopulation() == BitWidth - 1) &&
1188 (KnownOne.countPopulation() == 1);
Dan Gohmane58ab792009-01-29 01:59:02 +00001189}
Chris Lattner7206d742006-05-06 09:27:13 +00001190
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001191bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1192 if (!N)
1193 return false;
1194
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001195 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001196 if (!CN) {
1197 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1198 if (!BV)
1199 return false;
1200
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001201 BitVector UndefElements;
1202 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001203 // Only interested in constant splats, and we don't try to handle undef
1204 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001205 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001206 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001207 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001208
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001209 switch (getBooleanContents(N->getValueType(0))) {
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001210 case UndefinedBooleanContent:
1211 return CN->getAPIntValue()[0];
1212 case ZeroOrOneBooleanContent:
1213 return CN->isOne();
1214 case ZeroOrNegativeOneBooleanContent:
1215 return CN->isAllOnesValue();
1216 }
1217
1218 llvm_unreachable("Invalid boolean contents");
1219}
1220
1221bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1222 if (!N)
1223 return false;
1224
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001225 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001226 if (!CN) {
1227 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1228 if (!BV)
1229 return false;
1230
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001231 BitVector UndefElements;
1232 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001233 // Only interested in constant splats, and we don't try to handle undef
1234 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001235 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001236 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001237 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001238
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001239 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001240 return !CN->getAPIntValue()[0];
1241
1242 return CN->isNullValue();
1243}
1244
Sanjay Patelac6e9102015-12-29 22:11:50 +00001245/// Try to simplify a setcc built with the specified operands and cc. If it is
1246/// unable to simplify it, return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001247SDValue
Owen Anderson53aa7a92009-08-10 22:56:29 +00001248TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
Evan Cheng92658d52007-02-08 22:13:59 +00001249 ISD::CondCode Cond, bool foldBooleans,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001250 DAGCombinerInfo &DCI, SDLoc dl) const {
Evan Cheng92658d52007-02-08 22:13:59 +00001251 SelectionDAG &DAG = DCI.DAG;
1252
1253 // These setcc operations always fold.
1254 switch (Cond) {
1255 default: break;
1256 case ISD::SETFALSE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001257 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001258 case ISD::SETTRUE:
Tim Northover950fcc02013-09-06 12:38:12 +00001259 case ISD::SETTRUE2: {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001260 TargetLowering::BooleanContent Cnt =
1261 getBooleanContents(N0->getValueType(0));
Tim Northover950fcc02013-09-06 12:38:12 +00001262 return DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001263 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1264 VT);
Tim Northover950fcc02013-09-06 12:38:12 +00001265 }
Evan Cheng92658d52007-02-08 22:13:59 +00001266 }
1267
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001268 // Ensure that the constant occurs on the RHS, and fold constant
1269 // comparisons.
Tom Stellardcd428182013-09-28 02:50:38 +00001270 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1271 if (isa<ConstantSDNode>(N0.getNode()) &&
1272 (DCI.isBeforeLegalizeOps() ||
1273 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1274 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00001275
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001276 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
Dan Gohman2fa65b72008-03-03 22:22:56 +00001277 const APInt &C1 = N1C->getAPIntValue();
Dale Johannesen7aad5422008-11-07 01:28:02 +00001278
Eli Friedman65919b52009-07-26 23:47:17 +00001279 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1280 // equality comparison, then we're just comparing whether X itself is
1281 // zero.
1282 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1283 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1284 N0.getOperand(1).getOpcode() == ISD::Constant) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001285 const APInt &ShAmt
1286 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001287 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1288 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1289 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1290 // (srl (ctlz x), 5) == 0 -> X != 0
1291 // (srl (ctlz x), 5) != 1 -> X != 0
1292 Cond = ISD::SETNE;
1293 } else {
1294 // (srl (ctlz x), 5) != 0 -> X == 0
1295 // (srl (ctlz x), 5) == 1 -> X == 0
1296 Cond = ISD::SETEQ;
1297 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001298 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
Eli Friedman65919b52009-07-26 23:47:17 +00001299 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1300 Zero, Cond);
1301 }
1302 }
1303
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001304 SDValue CTPOP = N0;
1305 // Look through truncs that don't change the value of a ctpop.
1306 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1307 CTPOP = N0.getOperand(0);
1308
1309 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
Benjamin Kramer45d183c2011-01-17 18:00:28 +00001310 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001311 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1312 EVT CTVT = CTPOP.getValueType();
1313 SDValue CTOp = CTPOP.getOperand(0);
1314
1315 // (ctpop x) u< 2 -> (x & x-1) == 0
1316 // (ctpop x) u> 1 -> (x & x-1) != 0
1317 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1318 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001319 DAG.getConstant(1, dl, CTVT));
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001320 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1321 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001322 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001323 }
1324
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001325 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001326 }
1327
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001328 // (zext x) == C --> x == (trunc C)
Matt Arsenault22b4c252014-12-21 16:48:42 +00001329 // (sext x) == C --> x == (trunc C)
1330 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1331 DCI.isBeforeLegalize() && N0->hasOneUse()) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001332 unsigned MinBits = N0.getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001333 SDValue PreExt;
1334 bool Signed = false;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001335 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1336 // ZExt
1337 MinBits = N0->getOperand(0).getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001338 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001339 } else if (N0->getOpcode() == ISD::AND) {
1340 // DAGCombine turns costly ZExts into ANDs
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001341 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001342 if ((C->getAPIntValue()+1).isPowerOf2()) {
1343 MinBits = C->getAPIntValue().countTrailingOnes();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001344 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001345 }
Matt Arsenault22b4c252014-12-21 16:48:42 +00001346 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1347 // SExt
1348 MinBits = N0->getOperand(0).getValueSizeInBits();
1349 PreExt = N0->getOperand(0);
1350 Signed = true;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001351 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
Matt Arsenault22b4c252014-12-21 16:48:42 +00001352 // ZEXTLOAD / SEXTLOAD
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001353 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1354 MinBits = LN0->getMemoryVT().getSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001355 PreExt = N0;
1356 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1357 Signed = true;
1358 MinBits = LN0->getMemoryVT().getSizeInBits();
1359 PreExt = N0;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001360 }
1361 }
1362
Matt Arsenault22b4c252014-12-21 16:48:42 +00001363 // Figure out how many bits we need to preserve this constant.
1364 unsigned ReqdBits = Signed ?
1365 C1.getBitWidth() - C1.getNumSignBits() + 1 :
1366 C1.getActiveBits();
1367
Benjamin Kramerbde91762012-06-02 10:20:22 +00001368 // Make sure we're not losing bits from the constant.
Benjamin Kramer8aaf1972013-05-21 08:51:09 +00001369 if (MinBits > 0 &&
Matt Arsenault22b4c252014-12-21 16:48:42 +00001370 MinBits < C1.getBitWidth() &&
1371 MinBits >= ReqdBits) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001372 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1373 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1374 // Will get folded away.
Matt Arsenault22b4c252014-12-21 16:48:42 +00001375 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001376 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001377 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1378 }
1379 }
1380 }
1381
Eli Friedman65919b52009-07-26 23:47:17 +00001382 // If the LHS is '(and load, const)', the RHS is 0,
1383 // the test is for equality or unsigned, and all 1 bits of the const are
1384 // in the same partial word, see if we can shorten the load.
1385 if (DCI.isBeforeLegalize() &&
Eli Friedmana961d692013-09-24 22:50:14 +00001386 !ISD::isSignedIntSetCC(Cond) &&
Eli Friedman65919b52009-07-26 23:47:17 +00001387 N0.getOpcode() == ISD::AND && C1 == 0 &&
1388 N0.getNode()->hasOneUse() &&
1389 isa<LoadSDNode>(N0.getOperand(0)) &&
1390 N0.getOperand(0).getNode()->hasOneUse() &&
1391 isa<ConstantSDNode>(N0.getOperand(1))) {
1392 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
Evan Cheng16b75ce2010-01-07 20:58:44 +00001393 APInt bestMask;
Eli Friedman65919b52009-07-26 23:47:17 +00001394 unsigned bestWidth = 0, bestOffset = 0;
Evan Cheng16b75ce2010-01-07 20:58:44 +00001395 if (!Lod->isVolatile() && Lod->isUnindexed()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001396 unsigned origWidth = N0.getValueType().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001397 unsigned maskWidth = origWidth;
Wesley Peck527da1b2010-11-23 03:31:01 +00001398 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
Eli Friedman65919b52009-07-26 23:47:17 +00001399 // 8 bits, but have to be careful...
1400 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1401 origWidth = Lod->getMemoryVT().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001402 const APInt &Mask =
1403 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001404 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001405 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
Eli Friedman65919b52009-07-26 23:47:17 +00001406 for (unsigned offset=0; offset<origWidth/width; offset++) {
1407 if ((newMask & Mask) == Mask) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00001408 if (!DAG.getDataLayout().isLittleEndian())
Eli Friedman65919b52009-07-26 23:47:17 +00001409 bestOffset = (origWidth/width - offset - 1) * (width/8);
1410 else
1411 bestOffset = (uint64_t)offset * (width/8);
Evan Cheng16b75ce2010-01-07 20:58:44 +00001412 bestMask = Mask.lshr(offset * (width/8) * 8);
Eli Friedman65919b52009-07-26 23:47:17 +00001413 bestWidth = width;
1414 break;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001415 }
Eli Friedman65919b52009-07-26 23:47:17 +00001416 newMask = newMask << width;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001417 }
1418 }
1419 }
Eli Friedman65919b52009-07-26 23:47:17 +00001420 if (bestWidth) {
Chris Lattner493b3e72011-04-14 04:12:47 +00001421 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
Eli Friedman65919b52009-07-26 23:47:17 +00001422 if (newVT.isRound()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001423 EVT PtrType = Lod->getOperand(1).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001424 SDValue Ptr = Lod->getBasePtr();
1425 if (bestOffset != 0)
1426 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001427 DAG.getConstant(bestOffset, dl, PtrType));
Eli Friedman65919b52009-07-26 23:47:17 +00001428 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1429 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
Chris Lattner1ffcf522010-09-21 16:36:31 +00001430 Lod->getPointerInfo().getWithOffset(bestOffset),
Pete Cooper82cd9e82011-11-08 18:42:53 +00001431 false, false, false, NewAlign);
Wesley Peck527da1b2010-11-23 03:31:01 +00001432 return DAG.getSetCC(dl, VT,
Eli Friedman65919b52009-07-26 23:47:17 +00001433 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
Evan Cheng16b75ce2010-01-07 20:58:44 +00001434 DAG.getConstant(bestMask.trunc(bestWidth),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001435 dl, newVT)),
1436 DAG.getConstant(0LL, dl, newVT), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001437 }
Eli Friedman65919b52009-07-26 23:47:17 +00001438 }
1439 }
Evan Cheng92658d52007-02-08 22:13:59 +00001440
Eli Friedman65919b52009-07-26 23:47:17 +00001441 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1442 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1443 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1444
1445 // If the comparison constant has bits in the upper part, the
1446 // zero-extended value could never match.
1447 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1448 C1.getBitWidth() - InSize))) {
Evan Cheng92658d52007-02-08 22:13:59 +00001449 switch (Cond) {
Evan Cheng92658d52007-02-08 22:13:59 +00001450 case ISD::SETUGT:
1451 case ISD::SETUGE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001452 case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001453 case ISD::SETULT:
Eli Friedman65919b52009-07-26 23:47:17 +00001454 case ISD::SETULE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001455 case ISD::SETNE: return DAG.getConstant(1, dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001456 case ISD::SETGT:
1457 case ISD::SETGE:
1458 // True if the sign bit of C1 is set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001459 return DAG.getConstant(C1.isNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001460 case ISD::SETLT:
1461 case ISD::SETLE:
1462 // True if the sign bit of C1 isn't set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001463 return DAG.getConstant(C1.isNonNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001464 default:
Jakob Stoklund Olesen1ae07362009-07-24 18:22:59 +00001465 break;
1466 }
Eli Friedman65919b52009-07-26 23:47:17 +00001467 }
Evan Cheng92658d52007-02-08 22:13:59 +00001468
Eli Friedman65919b52009-07-26 23:47:17 +00001469 // Otherwise, we can perform the comparison with the low bits.
1470 switch (Cond) {
1471 case ISD::SETEQ:
1472 case ISD::SETNE:
1473 case ISD::SETUGT:
1474 case ISD::SETUGE:
1475 case ISD::SETULT:
1476 case ISD::SETULE: {
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001477 EVT newVT = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001478 if (DCI.isBeforeLegalizeOps() ||
1479 (isOperationLegal(ISD::SETCC, newVT) &&
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001480 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001481 EVT NewSetCCVT =
1482 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001483 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001484
1485 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1486 NewConst, Cond);
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001487 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001488 }
Eli Friedman65919b52009-07-26 23:47:17 +00001489 break;
1490 }
1491 default:
1492 break; // todo, be more careful with signed comparisons
1493 }
1494 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Evan Cheng228c31f2010-02-27 07:36:59 +00001495 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001496 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
Eli Friedman65919b52009-07-26 23:47:17 +00001497 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
Owen Anderson53aa7a92009-08-10 22:56:29 +00001498 EVT ExtDstTy = N0.getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001499 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1500
Eli Friedmanffe64c02010-07-30 06:44:31 +00001501 // If the constant doesn't fit into the number of bits for the source of
1502 // the sign extension, it is impossible for both sides to be equal.
1503 if (C1.getMinSignedBits() > ExtSrcTyBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001504 return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +00001505
Eli Friedman65919b52009-07-26 23:47:17 +00001506 SDValue ZextOp;
Owen Anderson53aa7a92009-08-10 22:56:29 +00001507 EVT Op0Ty = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001508 if (Op0Ty == ExtSrcTy) {
1509 ZextOp = N0.getOperand(0);
1510 } else {
1511 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1512 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001513 DAG.getConstant(Imm, dl, Op0Ty));
Eli Friedman65919b52009-07-26 23:47:17 +00001514 }
1515 if (!DCI.isCalledByLegalizer())
1516 DCI.AddToWorklist(ZextOp.getNode());
1517 // Otherwise, make this a use of a zext.
Wesley Peck527da1b2010-11-23 03:31:01 +00001518 return DAG.getSetCC(dl, VT, ZextOp,
Eli Friedman65919b52009-07-26 23:47:17 +00001519 DAG.getConstant(C1 & APInt::getLowBitsSet(
1520 ExtDstTyBits,
Wesley Peck527da1b2010-11-23 03:31:01 +00001521 ExtSrcTyBits),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001522 dl, ExtDstTy),
Eli Friedman65919b52009-07-26 23:47:17 +00001523 Cond);
1524 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1525 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Eli Friedman65919b52009-07-26 23:47:17 +00001526 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00001527 if (N0.getOpcode() == ISD::SETCC &&
1528 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001529 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
Eli Friedman65919b52009-07-26 23:47:17 +00001530 if (TrueWhenTrue)
Wesley Peck527da1b2010-11-23 03:31:01 +00001531 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
Eli Friedman65919b52009-07-26 23:47:17 +00001532 // Invert the condition.
1533 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Wesley Peck527da1b2010-11-23 03:31:01 +00001534 CC = ISD::getSetCCInverse(CC,
Eli Friedman65919b52009-07-26 23:47:17 +00001535 N0.getOperand(0).getValueType().isInteger());
Tom Stellardcd428182013-09-28 02:50:38 +00001536 if (DCI.isBeforeLegalizeOps() ||
1537 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1538 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
Evan Cheng92658d52007-02-08 22:13:59 +00001539 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001540
Eli Friedman65919b52009-07-26 23:47:17 +00001541 if ((N0.getOpcode() == ISD::XOR ||
Wesley Peck527da1b2010-11-23 03:31:01 +00001542 (N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001543 N0.getOperand(0).getOpcode() == ISD::XOR &&
1544 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1545 isa<ConstantSDNode>(N0.getOperand(1)) &&
1546 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1547 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1548 // can only do this if the top bits are known zero.
1549 unsigned BitWidth = N0.getValueSizeInBits();
1550 if (DAG.MaskedValueIsZero(N0,
1551 APInt::getHighBitsSet(BitWidth,
1552 BitWidth-1))) {
1553 // Okay, get the un-inverted input value.
1554 SDValue Val;
1555 if (N0.getOpcode() == ISD::XOR)
1556 Val = N0.getOperand(0);
1557 else {
Wesley Peck527da1b2010-11-23 03:31:01 +00001558 assert(N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001559 N0.getOperand(0).getOpcode() == ISD::XOR);
1560 // ((X^1)&1)^1 -> X & 1
1561 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1562 N0.getOperand(0).getOperand(0),
1563 N0.getOperand(1));
1564 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001565
Eli Friedman65919b52009-07-26 23:47:17 +00001566 return DAG.getSetCC(dl, VT, Val, N1,
1567 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1568 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001569 } else if (N1C->getAPIntValue() == 1 &&
1570 (VT == MVT::i1 ||
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001571 getBooleanContents(N0->getValueType(0)) ==
1572 ZeroOrOneBooleanContent)) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001573 SDValue Op0 = N0;
1574 if (Op0.getOpcode() == ISD::TRUNCATE)
1575 Op0 = Op0.getOperand(0);
1576
1577 if ((Op0.getOpcode() == ISD::XOR) &&
1578 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1579 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1580 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1581 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1582 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1583 Cond);
Craig Topper63f59212012-12-19 06:12:28 +00001584 }
1585 if (Op0.getOpcode() == ISD::AND &&
1586 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1587 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001588 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001589 if (Op0.getValueType().bitsGT(VT))
Evan Cheng228c31f2010-02-27 07:36:59 +00001590 Op0 = DAG.getNode(ISD::AND, dl, VT,
1591 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001592 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001593 else if (Op0.getValueType().bitsLT(VT))
1594 Op0 = DAG.getNode(ISD::AND, dl, VT,
1595 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001596 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001597
Evan Cheng228c31f2010-02-27 07:36:59 +00001598 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001599 DAG.getConstant(0, dl, Op0.getValueType()),
Evan Cheng228c31f2010-02-27 07:36:59 +00001600 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1601 }
Craig Topper63f59212012-12-19 06:12:28 +00001602 if (Op0.getOpcode() == ISD::AssertZext &&
1603 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1604 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001605 DAG.getConstant(0, dl, Op0.getValueType()),
Craig Topper63f59212012-12-19 06:12:28 +00001606 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001607 }
Eli Friedman65919b52009-07-26 23:47:17 +00001608 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001609
Eli Friedman65919b52009-07-26 23:47:17 +00001610 APInt MinVal, MaxVal;
1611 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1612 if (ISD::isSignedIntSetCC(Cond)) {
1613 MinVal = APInt::getSignedMinValue(OperandBitSize);
1614 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1615 } else {
1616 MinVal = APInt::getMinValue(OperandBitSize);
1617 MaxVal = APInt::getMaxValue(OperandBitSize);
1618 }
Evan Cheng92658d52007-02-08 22:13:59 +00001619
Eli Friedman65919b52009-07-26 23:47:17 +00001620 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1621 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001622 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001623 // X >= C0 --> X > (C0 - 1)
1624 APInt C = C1 - 1;
1625 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1626 if ((DCI.isBeforeLegalizeOps() ||
1627 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1628 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1629 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001630 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001631 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001632 NewCC);
1633 }
Eli Friedman65919b52009-07-26 23:47:17 +00001634 }
Evan Cheng92658d52007-02-08 22:13:59 +00001635
Eli Friedman65919b52009-07-26 23:47:17 +00001636 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001637 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001638 // X <= C0 --> X < (C0 + 1)
1639 APInt C = C1 + 1;
1640 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1641 if ((DCI.isBeforeLegalizeOps() ||
1642 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1643 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1644 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001645 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001646 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001647 NewCC);
1648 }
Eli Friedman65919b52009-07-26 23:47:17 +00001649 }
Evan Cheng92658d52007-02-08 22:13:59 +00001650
Eli Friedman65919b52009-07-26 23:47:17 +00001651 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001652 return DAG.getConstant(0, dl, VT); // X < MIN --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001653 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001654 return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Eli Friedman65919b52009-07-26 23:47:17 +00001655 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001656 return DAG.getConstant(0, dl, VT); // X > MAX --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001657 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001658 return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Evan Cheng92658d52007-02-08 22:13:59 +00001659
Eli Friedman65919b52009-07-26 23:47:17 +00001660 // Canonicalize setgt X, Min --> setne X, Min
1661 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1662 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1663 // Canonicalize setlt X, Max --> setne X, Max
1664 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1665 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
Evan Cheng92658d52007-02-08 22:13:59 +00001666
Eli Friedman65919b52009-07-26 23:47:17 +00001667 // If we have setult X, 1, turn it into seteq X, 0
1668 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001669 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001670 DAG.getConstant(MinVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001671 ISD::SETEQ);
1672 // If we have setugt X, Max-1, turn it into seteq X, Max
Craig Topper3f194c82012-12-19 06:43:58 +00001673 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001674 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001675 DAG.getConstant(MaxVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001676 ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001677
Eli Friedman65919b52009-07-26 23:47:17 +00001678 // If we have "setcc X, C0", check to see if we can shrink the immediate
1679 // by changing cc.
Evan Cheng92658d52007-02-08 22:13:59 +00001680
Eli Friedman65919b52009-07-26 23:47:17 +00001681 // SETUGT X, SINTMAX -> SETLT X, 0
Wesley Peck527da1b2010-11-23 03:31:01 +00001682 if (Cond == ISD::SETUGT &&
Eli Friedman65919b52009-07-26 23:47:17 +00001683 C1 == APInt::getSignedMaxValue(OperandBitSize))
Wesley Peck527da1b2010-11-23 03:31:01 +00001684 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001685 DAG.getConstant(0, dl, N1.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001686 ISD::SETLT);
Evan Cheng92658d52007-02-08 22:13:59 +00001687
Eli Friedman65919b52009-07-26 23:47:17 +00001688 // SETULT X, SINTMIN -> SETGT X, -1
1689 if (Cond == ISD::SETULT &&
1690 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1691 SDValue ConstMinusOne =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001692 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
Eli Friedman65919b52009-07-26 23:47:17 +00001693 N1.getValueType());
1694 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1695 }
Evan Cheng92658d52007-02-08 22:13:59 +00001696
Eli Friedman65919b52009-07-26 23:47:17 +00001697 // Fold bit comparisons when we can.
1698 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Evan Cheng166a4e62010-01-06 19:38:29 +00001699 (VT == N0.getValueType() ||
1700 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001701 N0.getOpcode() == ISD::AND) {
1702 auto &DL = DAG.getDataLayout();
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001703 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001704 EVT ShiftTy = DCI.isBeforeLegalize()
1705 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001706 : getShiftAmountTy(N0.getValueType(), DL);
Eli Friedman65919b52009-07-26 23:47:17 +00001707 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1708 // Perform the xform if the AND RHS is a single bit.
Evan Cheng16b75ce2010-01-07 20:58:44 +00001709 if (AndRHS->getAPIntValue().isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001710 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1711 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001712 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1713 ShiftTy)));
Eli Friedman65919b52009-07-26 23:47:17 +00001714 }
Evan Cheng16b75ce2010-01-07 20:58:44 +00001715 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001716 // (X & 8) == 8 --> (X & 8) >> 3
1717 // Perform the xform if C1 is a single bit.
1718 if (C1.isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001719 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1720 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001721 DAG.getConstant(C1.logBase2(), dl,
1722 ShiftTy)));
Evan Cheng92658d52007-02-08 22:13:59 +00001723 }
1724 }
Eli Friedman65919b52009-07-26 23:47:17 +00001725 }
Mehdi Amini44ede332015-07-09 02:09:04 +00001726 }
Evan Chengf579bec2012-07-17 06:53:39 +00001727
Evan Cheng47d7be92012-07-17 07:47:50 +00001728 if (C1.getMinSignedBits() <= 64 &&
1729 !isLegalICmpImmediate(C1.getSExtValue())) {
Evan Chengf579bec2012-07-17 06:53:39 +00001730 // (X & -256) == 256 -> (X >> 8) == 1
1731 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1732 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001733 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Chengf579bec2012-07-17 06:53:39 +00001734 const APInt &AndRHSC = AndRHS->getAPIntValue();
1735 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1736 unsigned ShiftBits = AndRHSC.countTrailingZeros();
Mehdi Amini44ede332015-07-09 02:09:04 +00001737 auto &DL = DAG.getDataLayout();
1738 EVT ShiftTy = DCI.isBeforeLegalize()
1739 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001740 : getShiftAmountTy(N0.getValueType(), DL);
Evan Chengf579bec2012-07-17 06:53:39 +00001741 EVT CmpTy = N0.getValueType();
1742 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001743 DAG.getConstant(ShiftBits, dl,
1744 ShiftTy));
1745 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
Evan Chengf579bec2012-07-17 06:53:39 +00001746 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1747 }
1748 }
Evan Cheng780f9b52012-07-17 08:31:11 +00001749 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1750 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1751 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1752 // X < 0x100000000 -> (X >> 32) < 1
1753 // X >= 0x100000000 -> (X >> 32) >= 1
1754 // X <= 0x0ffffffff -> (X >> 32) < 1
1755 // X > 0x0ffffffff -> (X >> 32) >= 1
1756 unsigned ShiftBits;
1757 APInt NewC = C1;
1758 ISD::CondCode NewCond = Cond;
1759 if (AdjOne) {
1760 ShiftBits = C1.countTrailingOnes();
1761 NewC = NewC + 1;
1762 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1763 } else {
1764 ShiftBits = C1.countTrailingZeros();
1765 }
1766 NewC = NewC.lshr(ShiftBits);
Pawel Bylica8011da92015-05-20 17:21:09 +00001767 if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
1768 isLegalICmpImmediate(NewC.getSExtValue())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001769 auto &DL = DAG.getDataLayout();
1770 EVT ShiftTy = DCI.isBeforeLegalize()
1771 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001772 : getShiftAmountTy(N0.getValueType(), DL);
Evan Cheng780f9b52012-07-17 08:31:11 +00001773 EVT CmpTy = N0.getValueType();
1774 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001775 DAG.getConstant(ShiftBits, dl, ShiftTy));
1776 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
Evan Cheng780f9b52012-07-17 08:31:11 +00001777 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1778 }
Evan Chengf579bec2012-07-17 06:53:39 +00001779 }
1780 }
Evan Cheng92658d52007-02-08 22:13:59 +00001781 }
1782
Gabor Greiff304a7a2008-08-28 21:40:38 +00001783 if (isa<ConstantFPSDNode>(N0.getNode())) {
Evan Cheng92658d52007-02-08 22:13:59 +00001784 // Constant fold or commute setcc.
Dale Johannesenf1163e92009-02-03 00:47:48 +00001785 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001786 if (O.getNode()) return O;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001787 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
Chris Lattner3b6a8212007-12-29 08:37:08 +00001788 // If the RHS of an FP comparison is a constant, simplify it away in
1789 // some cases.
1790 if (CFP->getValueAPF().isNaN()) {
1791 // If an operand is known to be a nan, we can fold it.
1792 switch (ISD::getUnorderedFlavor(Cond)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001793 default: llvm_unreachable("Unknown flavor!");
Chris Lattner3b6a8212007-12-29 08:37:08 +00001794 case 0: // Known false.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001795 return DAG.getConstant(0, dl, VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001796 case 1: // Known true.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001797 return DAG.getConstant(1, dl, VT);
Chris Lattner96317d22007-12-30 21:21:10 +00001798 case 2: // Undefined.
Dale Johannesen84935752009-02-06 23:05:02 +00001799 return DAG.getUNDEF(VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001800 }
1801 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001802
Chris Lattner3b6a8212007-12-29 08:37:08 +00001803 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1804 // constant if knowing that the operand is non-nan is enough. We prefer to
1805 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1806 // materialize 0.0.
1807 if (Cond == ISD::SETO || Cond == ISD::SETUO)
Dale Johannesenf1163e92009-02-03 00:47:48 +00001808 return DAG.getSetCC(dl, VT, N0, N0, Cond);
Dan Gohman832800a2009-09-26 15:24:17 +00001809
1810 // If the condition is not legal, see if we can find an equivalent one
1811 // which is legal.
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001812 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
Dan Gohman832800a2009-09-26 15:24:17 +00001813 // If the comparison was an awkward floating-point == or != and one of
1814 // the comparison operands is infinity or negative infinity, convert the
1815 // condition to a less-awkward <= or >=.
1816 if (CFP->getValueAPF().isInfinity()) {
1817 if (CFP->getValueAPF().isNegative()) {
1818 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001819 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001820 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1821 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001822 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001823 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1824 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001825 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001826 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1827 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001828 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001829 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1830 } else {
1831 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001832 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001833 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1834 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001835 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001836 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1837 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001838 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001839 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1840 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001841 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001842 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1843 }
1844 }
1845 }
Evan Cheng92658d52007-02-08 22:13:59 +00001846 }
1847
1848 if (N0 == N1) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00001849 // The sext(setcc()) => setcc() optimization relies on the appropriate
1850 // constant being emitted.
Nadav Rotema8e15b02012-09-06 11:13:55 +00001851 uint64_t EqVal = 0;
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001852 switch (getBooleanContents(N0.getValueType())) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00001853 case UndefinedBooleanContent:
1854 case ZeroOrOneBooleanContent:
1855 EqVal = ISD::isTrueWhenEqual(Cond);
1856 break;
1857 case ZeroOrNegativeOneBooleanContent:
1858 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1859 break;
1860 }
1861
Evan Cheng92658d52007-02-08 22:13:59 +00001862 // We can always fold X == X for integer setcc's.
Chad Rosier2a02fe12012-04-03 20:11:24 +00001863 if (N0.getValueType().isInteger()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001864 return DAG.getConstant(EqVal, dl, VT);
Chad Rosier2a02fe12012-04-03 20:11:24 +00001865 }
Evan Cheng92658d52007-02-08 22:13:59 +00001866 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1867 if (UOF == 2) // FP operators that are undefined on NaNs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001868 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001869 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001870 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001871 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
1872 // if it is not already.
1873 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
Micah Villmowb67d7a32012-07-31 18:07:43 +00001874 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
Patrik Hagglunddeee9002012-12-19 10:09:26 +00001875 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
Dale Johannesenf1163e92009-02-03 00:47:48 +00001876 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
Evan Cheng92658d52007-02-08 22:13:59 +00001877 }
1878
1879 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00001880 N0.getValueType().isInteger()) {
Evan Cheng92658d52007-02-08 22:13:59 +00001881 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1882 N0.getOpcode() == ISD::XOR) {
1883 // Simplify (X+Y) == (X+Z) --> Y == Z
1884 if (N0.getOpcode() == N1.getOpcode()) {
1885 if (N0.getOperand(0) == N1.getOperand(0))
Dale Johannesenf1163e92009-02-03 00:47:48 +00001886 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001887 if (N0.getOperand(1) == N1.getOperand(1))
Dale Johannesenf1163e92009-02-03 00:47:48 +00001888 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001889 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1890 // If X op Y == Y op X, try other combinations.
1891 if (N0.getOperand(0) == N1.getOperand(1))
Wesley Peck527da1b2010-11-23 03:31:01 +00001892 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
Dale Johannesenf1163e92009-02-03 00:47:48 +00001893 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001894 if (N0.getOperand(1) == N1.getOperand(0))
Wesley Peck527da1b2010-11-23 03:31:01 +00001895 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00001896 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001897 }
1898 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001899
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00001900 // If RHS is a legal immediate value for a compare instruction, we need
1901 // to be careful about increasing register pressure needlessly.
1902 bool LegalRHSImm = false;
1903
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001904 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1905 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Cheng92658d52007-02-08 22:13:59 +00001906 // Turn (X+C1) == C2 --> X == C2-C1
Gabor Greiff304a7a2008-08-28 21:40:38 +00001907 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00001908 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohmaneffb8942008-09-12 16:56:44 +00001909 DAG.getConstant(RHSC->getAPIntValue()-
1910 LHSR->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001911 dl, N0.getValueType()), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001912 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001913
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001914 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
Evan Cheng92658d52007-02-08 22:13:59 +00001915 if (N0.getOpcode() == ISD::XOR)
1916 // If we know that all of the inverted bits are zero, don't bother
1917 // performing the inversion.
Dan Gohman1f372ed2008-02-25 21:11:39 +00001918 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1919 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00001920 DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00001921 DAG.getConstant(LHSR->getAPIntValue() ^
1922 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001923 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00001924 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001925 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001926
Evan Cheng92658d52007-02-08 22:13:59 +00001927 // Turn (C1-X) == C2 --> X == C1-C2
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001928 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001929 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001930 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00001931 DAG.getSetCC(dl, VT, N0.getOperand(1),
Dan Gohman1f372ed2008-02-25 21:11:39 +00001932 DAG.getConstant(SUBC->getAPIntValue() -
1933 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001934 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00001935 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001936 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001937 }
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00001938
1939 // Could RHSC fold directly into a compare?
1940 if (RHSC->getValueType(0).getSizeInBits() <= 64)
1941 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
Evan Cheng92658d52007-02-08 22:13:59 +00001942 }
1943
1944 // Simplify (X+Z) == X --> Z == 0
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00001945 // Don't do this if X is an immediate that can fold into a cmp
1946 // instruction and X+Z has other uses. It could be an induction variable
1947 // chain, and the transform would increase register pressure.
1948 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
1949 if (N0.getOperand(0) == N1)
1950 return DAG.getSetCC(dl, VT, N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001951 DAG.getConstant(0, dl, N0.getValueType()), Cond);
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00001952 if (N0.getOperand(1) == N1) {
1953 if (DAG.isCommutativeBinOp(N0.getOpcode()))
1954 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001955 DAG.getConstant(0, dl, N0.getValueType()),
1956 Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00001957 if (N0.getNode()->hasOneUse()) {
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00001958 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00001959 auto &DL = DAG.getDataLayout();
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00001960 // (Z-X) == X --> Z == X<<1
Mehdi Amini9639d652015-07-09 02:09:20 +00001961 SDValue SH = DAG.getNode(
1962 ISD::SHL, dl, N1.getValueType(), N1,
1963 DAG.getConstant(1, dl,
1964 getShiftAmountTy(N1.getValueType(), DL)));
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00001965 if (!DCI.isCalledByLegalizer())
1966 DCI.AddToWorklist(SH.getNode());
1967 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
1968 }
Evan Cheng92658d52007-02-08 22:13:59 +00001969 }
1970 }
1971 }
1972
1973 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1974 N1.getOpcode() == ISD::XOR) {
1975 // Simplify X == (X+Z) --> Z == 0
Craig Topper3f194c82012-12-19 06:43:58 +00001976 if (N1.getOperand(0) == N0)
Dale Johannesenf1163e92009-02-03 00:47:48 +00001977 return DAG.getSetCC(dl, VT, N1.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001978 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00001979 if (N1.getOperand(1) == N0) {
1980 if (DAG.isCommutativeBinOp(N1.getOpcode()))
Dale Johannesenf1163e92009-02-03 00:47:48 +00001981 return DAG.getSetCC(dl, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001982 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00001983 if (N1.getNode()->hasOneUse()) {
Evan Cheng92658d52007-02-08 22:13:59 +00001984 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00001985 auto &DL = DAG.getDataLayout();
Evan Cheng92658d52007-02-08 22:13:59 +00001986 // X == (Z-X) --> X<<1 == Z
Mehdi Amini9639d652015-07-09 02:09:20 +00001987 SDValue SH = DAG.getNode(
1988 ISD::SHL, dl, N1.getValueType(), N0,
1989 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
Evan Cheng92658d52007-02-08 22:13:59 +00001990 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00001991 DCI.AddToWorklist(SH.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00001992 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001993 }
1994 }
1995 }
Dan Gohmane58ab792009-01-29 01:59:02 +00001996
Dan Gohman8b437cc2009-01-29 16:18:12 +00001997 // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
Dale Johannesencc5fc442009-02-11 19:19:41 +00001998 // Note that where y is variable and is known to have at most
1999 // one bit set (for example, if it is z&1) we cannot do this;
2000 // the expressions are not equivalent when y==0.
Dan Gohmane58ab792009-01-29 01:59:02 +00002001 if (N0.getOpcode() == ISD::AND)
2002 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
Dale Johannesencc5fc442009-02-11 19:19:41 +00002003 if (ValueHasExactlyOneBitSet(N1, DAG)) {
Dan Gohmane58ab792009-01-29 01:59:02 +00002004 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
Tom Stellardcd428182013-09-28 02:50:38 +00002005 if (DCI.isBeforeLegalizeOps() ||
2006 isCondCodeLegal(Cond, N0.getSimpleValueType())) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002007 SDValue Zero = DAG.getConstant(0, dl, N1.getValueType());
Tom Stellardcd428182013-09-28 02:50:38 +00002008 return DAG.getSetCC(dl, VT, N0, Zero, Cond);
2009 }
Dan Gohmane58ab792009-01-29 01:59:02 +00002010 }
2011 }
2012 if (N1.getOpcode() == ISD::AND)
2013 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
Dale Johannesencc5fc442009-02-11 19:19:41 +00002014 if (ValueHasExactlyOneBitSet(N0, DAG)) {
Dan Gohmane58ab792009-01-29 01:59:02 +00002015 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
Tom Stellardcd428182013-09-28 02:50:38 +00002016 if (DCI.isBeforeLegalizeOps() ||
2017 isCondCodeLegal(Cond, N1.getSimpleValueType())) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002018 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
Tom Stellardcd428182013-09-28 02:50:38 +00002019 return DAG.getSetCC(dl, VT, N1, Zero, Cond);
2020 }
Dan Gohmane58ab792009-01-29 01:59:02 +00002021 }
2022 }
Evan Cheng92658d52007-02-08 22:13:59 +00002023 }
2024
2025 // Fold away ALL boolean setcc's.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002026 SDValue Temp;
Owen Anderson9f944592009-08-11 20:47:22 +00002027 if (N0.getValueType() == MVT::i1 && foldBooleans) {
Evan Cheng92658d52007-02-08 22:13:59 +00002028 switch (Cond) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00002029 default: llvm_unreachable("Unknown integer setcc!");
Bob Wilsonc5890052009-01-22 17:39:32 +00002030 case ISD::SETEQ: // X == Y -> ~(X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002031 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2032 N0 = DAG.getNOT(dl, Temp, MVT::i1);
Evan Cheng92658d52007-02-08 22:13:59 +00002033 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002034 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002035 break;
2036 case ISD::SETNE: // X != Y --> (X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002037 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
Evan Cheng92658d52007-02-08 22:13:59 +00002038 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002039 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2040 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
Owen Anderson9f944592009-08-11 20:47:22 +00002041 Temp = DAG.getNOT(dl, N0, MVT::i1);
2042 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002043 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002044 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002045 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002046 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2047 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
Owen Anderson9f944592009-08-11 20:47:22 +00002048 Temp = DAG.getNOT(dl, N1, MVT::i1);
2049 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002050 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002051 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002052 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002053 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2054 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
Owen Anderson9f944592009-08-11 20:47:22 +00002055 Temp = DAG.getNOT(dl, N0, MVT::i1);
2056 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002057 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002058 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002059 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002060 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2061 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
Owen Anderson9f944592009-08-11 20:47:22 +00002062 Temp = DAG.getNOT(dl, N1, MVT::i1);
2063 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002064 break;
2065 }
Owen Anderson9f944592009-08-11 20:47:22 +00002066 if (VT != MVT::i1) {
Evan Cheng92658d52007-02-08 22:13:59 +00002067 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002068 DCI.AddToWorklist(N0.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002069 // FIXME: If running after legalize, we probably can't do this.
Dale Johannesenf1163e92009-02-03 00:47:48 +00002070 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
Evan Cheng92658d52007-02-08 22:13:59 +00002071 }
2072 return N0;
2073 }
2074
2075 // Could not fold it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002076 return SDValue();
Evan Cheng92658d52007-02-08 22:13:59 +00002077}
2078
Sanjay Patelac6e9102015-12-29 22:11:50 +00002079/// Returns true (and the GlobalValue and the offset) if the node is a
2080/// GlobalAddress + offset.
Chris Lattner46c01a32011-02-13 22:25:43 +00002081bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
Evan Cheng2609d5e2008-05-12 19:56:52 +00002082 int64_t &Offset) const {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002083 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
Dan Gohmane38cc012008-06-09 22:05:52 +00002084 GA = GASD->getGlobal();
2085 Offset += GASD->getOffset();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002086 return true;
2087 }
2088
2089 if (N->getOpcode() == ISD::ADD) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002090 SDValue N1 = N->getOperand(0);
2091 SDValue N2 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002092 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002093 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002094 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002095 return true;
2096 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00002097 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002098 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002099 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002100 return true;
2101 }
2102 }
2103 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002104
Evan Cheng2609d5e2008-05-12 19:56:52 +00002105 return false;
2106}
2107
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002108SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2109 DAGCombinerInfo &DCI) const {
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002110 // Default implementation: no optimization.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002111 return SDValue();
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002112}
2113
Chris Lattneree1dadb2006-02-04 02:13:02 +00002114//===----------------------------------------------------------------------===//
2115// Inline Assembler Implementation Methods
2116//===----------------------------------------------------------------------===//
2117
2118TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002119TargetLowering::getConstraintType(StringRef Constraint) const {
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002120 unsigned S = Constraint.size();
2121
2122 if (S == 1) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002123 switch (Constraint[0]) {
2124 default: break;
2125 case 'r': return C_RegisterClass;
2126 case 'm': // memory
2127 case 'o': // offsetable
2128 case 'V': // not offsetable
2129 return C_Memory;
2130 case 'i': // Simple Integer or Relocatable Constant
2131 case 'n': // Simple Integer
John Thompsonc467aa22010-09-21 22:04:54 +00002132 case 'E': // Floating Point Constant
2133 case 'F': // Floating Point Constant
Chris Lattnerd6855142007-03-25 02:14:49 +00002134 case 's': // Relocatable Constant
John Thompsonc467aa22010-09-21 22:04:54 +00002135 case 'p': // Address.
Chris Lattner3d7efa22007-03-25 04:35:41 +00002136 case 'X': // Allow ANY value.
Chris Lattnerd6855142007-03-25 02:14:49 +00002137 case 'I': // Target registers.
2138 case 'J':
2139 case 'K':
2140 case 'L':
2141 case 'M':
2142 case 'N':
2143 case 'O':
2144 case 'P':
John Thompsonc467aa22010-09-21 22:04:54 +00002145 case '<':
2146 case '>':
Chris Lattnerd6855142007-03-25 02:14:49 +00002147 return C_Other;
2148 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002149 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002150
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002151 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002152 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002153 return C_Memory;
Chris Lattner843e4452007-03-25 02:18:14 +00002154 return C_Register;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002155 }
Chris Lattnerd6855142007-03-25 02:14:49 +00002156 return C_Unknown;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002157}
2158
Sanjay Patelac6e9102015-12-29 22:11:50 +00002159/// Try to replace an X constraint, which matches anything, with another that
2160/// has more specific requirements based on the type of the corresponding
2161/// operand.
Owen Anderson53aa7a92009-08-10 22:56:29 +00002162const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
Duncan Sands13237ac2008-06-06 12:08:01 +00002163 if (ConstraintVT.isInteger())
Chris Lattner724539c2008-04-26 23:02:14 +00002164 return "r";
Duncan Sands13237ac2008-06-06 12:08:01 +00002165 if (ConstraintVT.isFloatingPoint())
Chris Lattner724539c2008-04-26 23:02:14 +00002166 return "f"; // works for many targets
Craig Topperc0196b12014-04-14 00:51:57 +00002167 return nullptr;
Dale Johannesen2b3bc302008-01-29 02:21:21 +00002168}
2169
Sanjay Patelac6e9102015-12-29 22:11:50 +00002170/// Lower the specified operand into the Ops vector.
2171/// If it is invalid, don't add anything to Ops.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002172void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
Eric Christopherde9399b2011-06-02 23:16:42 +00002173 std::string &Constraint,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002174 std::vector<SDValue> &Ops,
Chris Lattner724539c2008-04-26 23:02:14 +00002175 SelectionDAG &DAG) const {
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002176
Eric Christopherde9399b2011-06-02 23:16:42 +00002177 if (Constraint.length() > 1) return;
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002178
Eric Christopherde9399b2011-06-02 23:16:42 +00002179 char ConstraintLetter = Constraint[0];
Chris Lattneree1dadb2006-02-04 02:13:02 +00002180 switch (ConstraintLetter) {
Chris Lattnera9f917a2007-02-17 06:00:35 +00002181 default: break;
Dale Johannesen4646aa32007-11-05 21:20:28 +00002182 case 'X': // Allows any operand; labels (basic block) use this.
2183 if (Op.getOpcode() == ISD::BasicBlock) {
2184 Ops.push_back(Op);
2185 return;
2186 }
2187 // fall through
Chris Lattneree1dadb2006-02-04 02:13:02 +00002188 case 'i': // Simple Integer or Relocatable Constant
2189 case 'n': // Simple Integer
Dale Johannesen4646aa32007-11-05 21:20:28 +00002190 case 's': { // Relocatable Constant
Chris Lattner44a2ed62007-05-03 16:54:34 +00002191 // These operands are interested in values of the form (GV+C), where C may
2192 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2193 // is possible and fine if either GV or C are missing.
2194 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2195 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
Wesley Peck527da1b2010-11-23 03:31:01 +00002196
Chris Lattner44a2ed62007-05-03 16:54:34 +00002197 // If we have "(add GV, C)", pull out GV/C
2198 if (Op.getOpcode() == ISD::ADD) {
2199 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2200 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
Craig Topperc0196b12014-04-14 00:51:57 +00002201 if (!C || !GA) {
Chris Lattner44a2ed62007-05-03 16:54:34 +00002202 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2203 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2204 }
Craig Topperc0196b12014-04-14 00:51:57 +00002205 if (!C || !GA)
2206 C = nullptr, GA = nullptr;
Chris Lattner44a2ed62007-05-03 16:54:34 +00002207 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002208
Chris Lattner44a2ed62007-05-03 16:54:34 +00002209 // If we find a valid operand, map to the TargetXXX version so that the
2210 // value itself doesn't get selected.
2211 if (GA) { // Either &GV or &GV+C
2212 if (ConstraintLetter != 'n') {
2213 int64_t Offs = GA->getOffset();
Dan Gohmaneffb8942008-09-12 16:56:44 +00002214 if (C) Offs += C->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002215 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002216 C ? SDLoc(C) : SDLoc(),
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002217 Op.getValueType(), Offs));
Chris Lattner44a2ed62007-05-03 16:54:34 +00002218 }
James Y Knight46f91c82015-07-13 16:36:22 +00002219 return;
Chris Lattner44a2ed62007-05-03 16:54:34 +00002220 }
2221 if (C) { // just C, no GV.
Chris Lattnera9f917a2007-02-17 06:00:35 +00002222 // Simple constants are not allowed for 's'.
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002223 if (ConstraintLetter != 's') {
Dale Johannesen65577522009-02-12 20:58:09 +00002224 // gcc prints these as sign extended. Sign extend value to 64 bits
2225 // now; without this it would get ZExt'd later in
2226 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2227 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002228 SDLoc(C), MVT::i64));
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002229 }
James Y Knight46f91c82015-07-13 16:36:22 +00002230 return;
Chris Lattnera9f917a2007-02-17 06:00:35 +00002231 }
Chris Lattnera9f917a2007-02-17 06:00:35 +00002232 break;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002233 }
Chris Lattner44a2ed62007-05-03 16:54:34 +00002234 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002235}
2236
Eric Christopher11e4df72015-02-26 22:38:43 +00002237std::pair<unsigned, const TargetRegisterClass *>
2238TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002239 StringRef Constraint,
Eric Christopher11e4df72015-02-26 22:38:43 +00002240 MVT VT) const {
Will Dietzae726a92013-10-13 03:08:49 +00002241 if (Constraint.empty() || Constraint[0] != '{')
Craig Topperc0196b12014-04-14 00:51:57 +00002242 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
Chris Lattner7ed31012006-02-01 01:29:47 +00002243 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2244
2245 // Remove the braces from around the name.
Benjamin Kramer68e49452009-11-12 20:36:59 +00002246 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002247
Hal Finkel943f76d2012-12-18 17:50:58 +00002248 std::pair<unsigned, const TargetRegisterClass*> R =
Craig Topperc0196b12014-04-14 00:51:57 +00002249 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
Hal Finkel943f76d2012-12-18 17:50:58 +00002250
Chris Lattner7ad77df2006-02-22 00:56:39 +00002251 // Figure out which register class contains this reg.
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002252 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
Chris Lattner7ad77df2006-02-22 00:56:39 +00002253 E = RI->regclass_end(); RCI != E; ++RCI) {
2254 const TargetRegisterClass *RC = *RCI;
Wesley Peck527da1b2010-11-23 03:31:01 +00002255
2256 // If none of the value types for this register class are valid, we
Chris Lattner2e124af2006-02-22 23:00:51 +00002257 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Jakob Stoklund Olesen35163e22011-10-12 01:24:51 +00002258 if (!isLegalRC(RC))
2259 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002260
2261 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002262 I != E; ++I) {
Hal Finkel943f76d2012-12-18 17:50:58 +00002263 if (RegName.equals_lower(RI->getName(*I))) {
2264 std::pair<unsigned, const TargetRegisterClass*> S =
2265 std::make_pair(*I, RC);
2266
2267 // If this register class has the requested value type, return it,
2268 // otherwise keep searching and return the first class found
2269 // if no other is found which explicitly has the requested type.
2270 if (RC->hasType(VT))
2271 return S;
2272 else if (!R.second)
2273 R = S;
2274 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002275 }
Chris Lattner32fef532006-01-26 20:37:03 +00002276 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002277
Hal Finkel943f76d2012-12-18 17:50:58 +00002278 return R;
Chris Lattner32fef532006-01-26 20:37:03 +00002279}
Evan Chengaf598d22006-03-13 23:18:16 +00002280
2281//===----------------------------------------------------------------------===//
Chris Lattner47935152008-04-27 00:09:47 +00002282// Constraint Selection.
2283
Sanjay Patelac6e9102015-12-29 22:11:50 +00002284/// Return true of this is an input operand that is a matching constraint like
2285/// "4".
Chris Lattner860df6e2008-10-17 16:47:46 +00002286bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
Chris Lattneref890172008-10-17 16:21:11 +00002287 assert(!ConstraintCode.empty() && "No known constraint!");
Guy Benyei83c74e92013-02-12 21:21:59 +00002288 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
Chris Lattneref890172008-10-17 16:21:11 +00002289}
2290
Sanjay Patelac6e9102015-12-29 22:11:50 +00002291/// If this is an input matching constraint, this method returns the output
2292/// operand it matches.
Chris Lattneref890172008-10-17 16:21:11 +00002293unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2294 assert(!ConstraintCode.empty() && "No known constraint!");
2295 return atoi(ConstraintCode.c_str());
2296}
2297
Sanjay Patelac6e9102015-12-29 22:11:50 +00002298/// Split up the constraint string from the inline assembly value into the
2299/// specific constraints and their prefixes, and also tie in the associated
2300/// operand values.
John Thompson1094c802010-09-13 18:15:37 +00002301/// If this returns an empty vector, and if the constraint string itself
2302/// isn't empty, there was an error parsing.
Eric Christopher11e4df72015-02-26 22:38:43 +00002303TargetLowering::AsmOperandInfoVector
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002304TargetLowering::ParseConstraints(const DataLayout &DL,
2305 const TargetRegisterInfo *TRI,
Eric Christopher11e4df72015-02-26 22:38:43 +00002306 ImmutableCallSite CS) const {
Sanjay Patelac6e9102015-12-29 22:11:50 +00002307 /// Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00002308 AsmOperandInfoVector ConstraintOperands;
John Thompson1094c802010-09-13 18:15:37 +00002309 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
John Thompsonc467aa22010-09-21 22:04:54 +00002310 unsigned maCount = 0; // Largest number of multiple alternative constraints.
John Thompson1094c802010-09-13 18:15:37 +00002311
2312 // Do a prepass over the constraints, canonicalizing them, and building up the
2313 // ConstraintOperands list.
John Thompson1094c802010-09-13 18:15:37 +00002314 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2315 unsigned ResNo = 0; // ResNo - The result number of the next output.
2316
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00002317 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2318 ConstraintOperands.emplace_back(std::move(CI));
John Thompson1094c802010-09-13 18:15:37 +00002319 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2320
John Thompsonc467aa22010-09-21 22:04:54 +00002321 // Update multiple alternative constraint count.
2322 if (OpInfo.multipleAlternatives.size() > maCount)
2323 maCount = OpInfo.multipleAlternatives.size();
2324
John Thompsone8360b72010-10-29 17:29:13 +00002325 OpInfo.ConstraintVT = MVT::Other;
John Thompson1094c802010-09-13 18:15:37 +00002326
2327 // Compute the value type for each operand.
2328 switch (OpInfo.Type) {
2329 case InlineAsm::isOutput:
2330 // Indirect outputs just consume an argument.
2331 if (OpInfo.isIndirect) {
2332 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2333 break;
2334 }
2335
2336 // The return value of the call is this value. As such, there is no
2337 // corresponding argument.
2338 assert(!CS.getType()->isVoidTy() &&
2339 "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00002340 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002341 OpInfo.ConstraintVT =
2342 getSimpleValueType(DL, STy->getElementType(ResNo));
John Thompson1094c802010-09-13 18:15:37 +00002343 } else {
2344 assert(ResNo == 0 && "Asm only has one result!");
Mehdi Amini44ede332015-07-09 02:09:04 +00002345 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
John Thompson1094c802010-09-13 18:15:37 +00002346 }
2347 ++ResNo;
2348 break;
2349 case InlineAsm::isInput:
2350 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2351 break;
2352 case InlineAsm::isClobber:
2353 // Nothing to do.
2354 break;
2355 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002356
John Thompsone8360b72010-10-29 17:29:13 +00002357 if (OpInfo.CallOperandVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00002358 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
John Thompsone8360b72010-10-29 17:29:13 +00002359 if (OpInfo.isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00002360 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002361 if (!PtrTy)
2362 report_fatal_error("Indirect operand for inline asm not a pointer!");
2363 OpTy = PtrTy->getElementType();
2364 }
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002365
Eric Christopher44804282011-05-09 20:04:43 +00002366 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00002367 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00002368 if (STy->getNumElements() == 1)
2369 OpTy = STy->getElementType(0);
2370
John Thompsone8360b72010-10-29 17:29:13 +00002371 // If OpTy is not a single value, it may be a struct/union that we
2372 // can tile with integers.
2373 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002374 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002375 switch (BitSize) {
2376 default: break;
2377 case 1:
2378 case 8:
2379 case 16:
2380 case 32:
2381 case 64:
2382 case 128:
Dale Johannesenf11ea9c2010-11-09 01:15:07 +00002383 OpInfo.ConstraintVT =
Patrik Hagglundf9934612012-12-19 15:19:11 +00002384 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
John Thompsone8360b72010-10-29 17:29:13 +00002385 break;
2386 }
Micah Villmow89021e42012-10-09 16:06:12 +00002387 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002388 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
Matt Arsenaulta98c3b12013-10-10 19:09:05 +00002389 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
John Thompsone8360b72010-10-29 17:29:13 +00002390 } else {
Patrik Hagglundf9934612012-12-19 15:19:11 +00002391 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
John Thompsone8360b72010-10-29 17:29:13 +00002392 }
2393 }
John Thompson1094c802010-09-13 18:15:37 +00002394 }
2395
2396 // If we have multiple alternative constraints, select the best alternative.
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002397 if (!ConstraintOperands.empty()) {
John Thompson1094c802010-09-13 18:15:37 +00002398 if (maCount) {
2399 unsigned bestMAIndex = 0;
2400 int bestWeight = -1;
2401 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2402 int weight = -1;
2403 unsigned maIndex;
2404 // Compute the sums of the weights for each alternative, keeping track
2405 // of the best (highest weight) one so far.
2406 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2407 int weightSum = 0;
2408 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2409 cIndex != eIndex; ++cIndex) {
2410 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2411 if (OpInfo.Type == InlineAsm::isClobber)
2412 continue;
John Thompson1094c802010-09-13 18:15:37 +00002413
John Thompsone8360b72010-10-29 17:29:13 +00002414 // If this is an output operand with a matching input operand,
2415 // look up the matching input. If their types mismatch, e.g. one
2416 // is an integer, the other is floating point, or their sizes are
2417 // different, flag it as an maCantMatch.
John Thompson1094c802010-09-13 18:15:37 +00002418 if (OpInfo.hasMatchingInput()) {
2419 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompson1094c802010-09-13 18:15:37 +00002420 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2421 if ((OpInfo.ConstraintVT.isInteger() !=
2422 Input.ConstraintVT.isInteger()) ||
2423 (OpInfo.ConstraintVT.getSizeInBits() !=
2424 Input.ConstraintVT.getSizeInBits())) {
2425 weightSum = -1; // Can't match.
2426 break;
2427 }
John Thompson1094c802010-09-13 18:15:37 +00002428 }
2429 }
John Thompson1094c802010-09-13 18:15:37 +00002430 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2431 if (weight == -1) {
2432 weightSum = -1;
2433 break;
2434 }
2435 weightSum += weight;
2436 }
2437 // Update best.
2438 if (weightSum > bestWeight) {
2439 bestWeight = weightSum;
2440 bestMAIndex = maIndex;
2441 }
2442 }
2443
2444 // Now select chosen alternative in each constraint.
2445 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2446 cIndex != eIndex; ++cIndex) {
2447 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2448 if (cInfo.Type == InlineAsm::isClobber)
2449 continue;
2450 cInfo.selectAlternative(bestMAIndex);
2451 }
2452 }
2453 }
2454
2455 // Check and hook up tied operands, choose constraint code to use.
2456 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2457 cIndex != eIndex; ++cIndex) {
2458 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
Wesley Peck527da1b2010-11-23 03:31:01 +00002459
John Thompson1094c802010-09-13 18:15:37 +00002460 // If this is an output operand with a matching input operand, look up the
2461 // matching input. If their types mismatch, e.g. one is an integer, the
2462 // other is floating point, or their sizes are different, flag it as an
2463 // error.
2464 if (OpInfo.hasMatchingInput()) {
2465 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompsone8360b72010-10-29 17:29:13 +00002466
John Thompson1094c802010-09-13 18:15:37 +00002467 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Eric Christopher11e4df72015-02-26 22:38:43 +00002468 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2469 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2470 OpInfo.ConstraintVT);
2471 std::pair<unsigned, const TargetRegisterClass *> InputRC =
2472 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2473 Input.ConstraintVT);
John Thompson1094c802010-09-13 18:15:37 +00002474 if ((OpInfo.ConstraintVT.isInteger() !=
2475 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00002476 (MatchRC.second != InputRC.second)) {
John Thompson1094c802010-09-13 18:15:37 +00002477 report_fatal_error("Unsupported asm: input constraint"
2478 " with a matching output constraint of"
2479 " incompatible type!");
2480 }
John Thompson1094c802010-09-13 18:15:37 +00002481 }
2482 }
2483 }
2484
2485 return ConstraintOperands;
2486}
2487
Sanjay Patelac6e9102015-12-29 22:11:50 +00002488/// Return an integer indicating how general CT is.
Chris Lattner47935152008-04-27 00:09:47 +00002489static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2490 switch (CT) {
Chris Lattner47935152008-04-27 00:09:47 +00002491 case TargetLowering::C_Other:
2492 case TargetLowering::C_Unknown:
2493 return 0;
2494 case TargetLowering::C_Register:
2495 return 1;
2496 case TargetLowering::C_RegisterClass:
2497 return 2;
2498 case TargetLowering::C_Memory:
2499 return 3;
2500 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002501 llvm_unreachable("Invalid constraint type");
Chris Lattner47935152008-04-27 00:09:47 +00002502}
2503
John Thompsone8360b72010-10-29 17:29:13 +00002504/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002505/// This object must already have been set up with the operand type
2506/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002507TargetLowering::ConstraintWeight
2508 TargetLowering::getMultipleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002509 AsmOperandInfo &info, int maIndex) const {
John Thompsone8360b72010-10-29 17:29:13 +00002510 InlineAsm::ConstraintCodeVector *rCodes;
John Thompsonc467aa22010-09-21 22:04:54 +00002511 if (maIndex >= (int)info.multipleAlternatives.size())
2512 rCodes = &info.Codes;
2513 else
2514 rCodes = &info.multipleAlternatives[maIndex].Codes;
John Thompsone8360b72010-10-29 17:29:13 +00002515 ConstraintWeight BestWeight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002516
2517 // Loop over the options, keeping track of the most general one.
John Thompsonc467aa22010-09-21 22:04:54 +00002518 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
John Thompsone8360b72010-10-29 17:29:13 +00002519 ConstraintWeight weight =
2520 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
John Thompson1094c802010-09-13 18:15:37 +00002521 if (weight > BestWeight)
2522 BestWeight = weight;
2523 }
2524
2525 return BestWeight;
2526}
2527
John Thompsone8360b72010-10-29 17:29:13 +00002528/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002529/// This object must already have been set up with the operand type
2530/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002531TargetLowering::ConstraintWeight
2532 TargetLowering::getSingleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002533 AsmOperandInfo &info, const char *constraint) const {
John Thompsone8360b72010-10-29 17:29:13 +00002534 ConstraintWeight weight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002535 Value *CallOperandVal = info.CallOperandVal;
2536 // If we don't have a value, we can't do a match,
2537 // but allow it at the lowest weight.
Craig Topperc0196b12014-04-14 00:51:57 +00002538 if (!CallOperandVal)
John Thompsone8360b72010-10-29 17:29:13 +00002539 return CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002540 // Look at the constraint type.
2541 switch (*constraint) {
2542 case 'i': // immediate integer.
2543 case 'n': // immediate integer with a known value.
John Thompsone8360b72010-10-29 17:29:13 +00002544 if (isa<ConstantInt>(CallOperandVal))
2545 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002546 break;
2547 case 's': // non-explicit intregal immediate.
John Thompsone8360b72010-10-29 17:29:13 +00002548 if (isa<GlobalValue>(CallOperandVal))
2549 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002550 break;
John Thompsone8360b72010-10-29 17:29:13 +00002551 case 'E': // immediate float if host format.
2552 case 'F': // immediate float.
2553 if (isa<ConstantFP>(CallOperandVal))
2554 weight = CW_Constant;
2555 break;
2556 case '<': // memory operand with autodecrement.
2557 case '>': // memory operand with autoincrement.
John Thompson1094c802010-09-13 18:15:37 +00002558 case 'm': // memory operand.
2559 case 'o': // offsettable memory operand
2560 case 'V': // non-offsettable memory operand
John Thompsone8360b72010-10-29 17:29:13 +00002561 weight = CW_Memory;
John Thompson1094c802010-09-13 18:15:37 +00002562 break;
John Thompsone8360b72010-10-29 17:29:13 +00002563 case 'r': // general register.
John Thompson1094c802010-09-13 18:15:37 +00002564 case 'g': // general register, memory operand or immediate integer.
John Thompsone8360b72010-10-29 17:29:13 +00002565 // note: Clang converts "g" to "imr".
2566 if (CallOperandVal->getType()->isIntegerTy())
2567 weight = CW_Register;
John Thompson1094c802010-09-13 18:15:37 +00002568 break;
John Thompsone8360b72010-10-29 17:29:13 +00002569 case 'X': // any operand.
John Thompson1094c802010-09-13 18:15:37 +00002570 default:
John Thompsone8360b72010-10-29 17:29:13 +00002571 weight = CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002572 break;
2573 }
2574 return weight;
2575}
2576
Sanjay Patelac6e9102015-12-29 22:11:50 +00002577/// If there are multiple different constraints that we could pick for this
2578/// operand (e.g. "imr") try to pick the 'best' one.
Chris Lattner58b9ece2008-04-27 01:49:46 +00002579/// This is somewhat tricky: constraints fall into four classes:
Chris Lattner47935152008-04-27 00:09:47 +00002580/// Other -> immediates and magic values
2581/// Register -> one specific register
2582/// RegisterClass -> a group of regs
2583/// Memory -> memory
2584/// Ideally, we would pick the most specific constraint possible: if we have
2585/// something that fits into a register, we would pick it. The problem here
2586/// is that if we have something that could either be in a register or in
2587/// memory that use of the register could cause selection of *other*
2588/// operands to fail: they might only succeed if we pick memory. Because of
2589/// this the heuristic we use is:
2590///
2591/// 1) If there is an 'other' constraint, and if the operand is valid for
2592/// that constraint, use it. This makes us take advantage of 'i'
2593/// constraints when available.
2594/// 2) Otherwise, pick the most general constraint present. This prefers
2595/// 'm' over 'r', for example.
2596///
2597static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
Dale Johannesence97d552010-06-25 21:55:36 +00002598 const TargetLowering &TLI,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002599 SDValue Op, SelectionDAG *DAG) {
Chris Lattner47935152008-04-27 00:09:47 +00002600 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2601 unsigned BestIdx = 0;
2602 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2603 int BestGenerality = -1;
Dale Johannesen17feb072010-06-28 22:09:45 +00002604
Chris Lattner47935152008-04-27 00:09:47 +00002605 // Loop over the options, keeping track of the most general one.
2606 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2607 TargetLowering::ConstraintType CType =
2608 TLI.getConstraintType(OpInfo.Codes[i]);
Dale Johannesen17feb072010-06-28 22:09:45 +00002609
Chris Lattner22379732008-04-27 00:37:18 +00002610 // If this is an 'other' constraint, see if the operand is valid for it.
2611 // For example, on X86 we might have an 'rI' constraint. If the operand
2612 // is an integer in the range [0..31] we want to use I (saving a load
2613 // of a register), otherwise we must use 'r'.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002614 if (CType == TargetLowering::C_Other && Op.getNode()) {
Chris Lattner22379732008-04-27 00:37:18 +00002615 assert(OpInfo.Codes[i].size() == 1 &&
2616 "Unhandled multi-letter 'other' constraint");
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002617 std::vector<SDValue> ResultOps;
Eric Christopherde9399b2011-06-02 23:16:42 +00002618 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
Chris Lattner22379732008-04-27 00:37:18 +00002619 ResultOps, *DAG);
2620 if (!ResultOps.empty()) {
2621 BestType = CType;
2622 BestIdx = i;
2623 break;
2624 }
2625 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002626
Dale Johannesen17feb072010-06-28 22:09:45 +00002627 // Things with matching constraints can only be registers, per gcc
2628 // documentation. This mainly affects "g" constraints.
2629 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2630 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002631
Chris Lattner47935152008-04-27 00:09:47 +00002632 // This constraint letter is more general than the previous one, use it.
2633 int Generality = getConstraintGenerality(CType);
2634 if (Generality > BestGenerality) {
2635 BestType = CType;
2636 BestIdx = i;
2637 BestGenerality = Generality;
2638 }
2639 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002640
Chris Lattner47935152008-04-27 00:09:47 +00002641 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2642 OpInfo.ConstraintType = BestType;
2643}
2644
Sanjay Patelac6e9102015-12-29 22:11:50 +00002645/// Determines the constraint code and constraint type to use for the specific
2646/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
Chris Lattner22379732008-04-27 00:37:18 +00002647void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
Wesley Peck527da1b2010-11-23 03:31:01 +00002648 SDValue Op,
Chris Lattner22379732008-04-27 00:37:18 +00002649 SelectionDAG *DAG) const {
Chris Lattner47935152008-04-27 00:09:47 +00002650 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
Wesley Peck527da1b2010-11-23 03:31:01 +00002651
Chris Lattner47935152008-04-27 00:09:47 +00002652 // Single-letter constraints ('r') are very common.
2653 if (OpInfo.Codes.size() == 1) {
2654 OpInfo.ConstraintCode = OpInfo.Codes[0];
2655 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2656 } else {
Dale Johannesence97d552010-06-25 21:55:36 +00002657 ChooseConstraint(OpInfo, *this, Op, DAG);
Chris Lattner47935152008-04-27 00:09:47 +00002658 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002659
Chris Lattner47935152008-04-27 00:09:47 +00002660 // 'X' matches anything.
2661 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2662 // Labels and constants are handled elsewhere ('X' is the only thing
Dale Johannesen4e331152009-07-07 23:26:33 +00002663 // that matches labels). For Functions, the type here is the type of
Dale Johannesenade297d2009-07-20 23:27:39 +00002664 // the result, which is not what we want to look at; leave them alone.
2665 Value *v = OpInfo.CallOperandVal;
Dale Johannesen4e331152009-07-07 23:26:33 +00002666 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2667 OpInfo.CallOperandVal = v;
Chris Lattner47935152008-04-27 00:09:47 +00002668 return;
Dale Johannesen4e331152009-07-07 23:26:33 +00002669 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002670
Chris Lattner47935152008-04-27 00:09:47 +00002671 // Otherwise, try to resolve it to something we know about by looking at
2672 // the actual operand type.
2673 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2674 OpInfo.ConstraintCode = Repl;
2675 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2676 }
2677 }
2678}
2679
David Majnemer0fc86702013-06-08 23:51:45 +00002680/// \brief Given an exact SDIV by a constant, create a multiplication
Benjamin Kramer9960a252011-07-08 10:31:30 +00002681/// with the multiplicative inverse of the constant.
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002682static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2683 SDLoc dl, SelectionDAG &DAG,
2684 std::vector<SDNode *> &Created) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002685 assert(d != 0 && "Division by zero!");
2686
2687 // Shift the value upfront if it is even, so the LSB is one.
2688 unsigned ShAmt = d.countTrailingZeros();
2689 if (ShAmt) {
2690 // TODO: For UDIV use SRL instead of SRA.
NAKAMURA Takumie4529982015-05-06 14:03:22 +00002691 SDValue Amt =
Mehdi Amini9639d652015-07-09 02:09:20 +00002692 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2693 DAG.getDataLayout()));
Sanjay Patelf1340482015-06-16 16:25:43 +00002694 SDNodeFlags Flags;
2695 Flags.setExact(true);
2696 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002697 Created.push_back(Op1.getNode());
Benjamin Kramer9960a252011-07-08 10:31:30 +00002698 d = d.ashr(ShAmt);
2699 }
2700
2701 // Calculate the multiplicative inverse, using Newton's method.
2702 APInt t, xn = d;
2703 while ((t = d*xn) != 1)
2704 xn *= APInt(d.getBitWidth(), 2) - t;
2705
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002706 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2707 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2708 Created.push_back(Mul.getNode());
2709 return Mul;
Benjamin Kramer9960a252011-07-08 10:31:30 +00002710}
2711
Steve King5cdbd202015-08-25 02:31:21 +00002712SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2713 SelectionDAG &DAG,
2714 std::vector<SDNode *> *Created) const {
2715 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2716 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2717 if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2718 return SDValue(N,0); // Lower SDIV as SDIV
2719 return SDValue();
2720}
2721
David Majnemer0fc86702013-06-08 23:51:45 +00002722/// \brief Given an ISD::SDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002723/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002724/// multiplying by a magic number.
2725/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002726SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2727 SelectionDAG &DAG, bool IsAfterLegalization,
2728 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002729 assert(Created && "No vector to hold sdiv ops.");
2730
Owen Anderson53aa7a92009-08-10 22:56:29 +00002731 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002732 SDLoc dl(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00002733
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002734 // Check to see if we can do this.
Eli Friedmanc8228d22008-11-30 06:35:39 +00002735 // FIXME: We should be more aggressive here.
2736 if (!isTypeLegal(VT))
2737 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002738
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002739 // If the sdiv has an 'exact' bit we can use a simpler lowering.
2740 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
2741 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
2742
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002743 APInt::ms magics = Divisor.magic();
Wesley Peck527da1b2010-11-23 03:31:01 +00002744
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002745 // Multiply the numerator (operand 0) by the magic value
Eli Friedmanc8228d22008-11-30 06:35:39 +00002746 // FIXME: We should support doing a MUL in a wider type
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002747 SDValue Q;
Richard Osborne561fac42011-11-07 17:09:05 +00002748 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2749 isOperationLegalOrCustom(ISD::MULHS, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002750 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002751 DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002752 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2753 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002754 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
Dan Gohmana1603612007-10-08 18:33:35 +00002755 N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002756 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002757 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002758 return SDValue(); // No mulhs or equvialent
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002759 // If d > 0 and m < 0, add the numerator
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002760 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002761 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002762 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002763 }
2764 // If d < 0 and m > 0, subtract the numerator.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002765 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002766 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002767 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002768 }
Mehdi Amini9639d652015-07-09 02:09:20 +00002769 auto &DL = DAG.getDataLayout();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002770 // Shift right algebraic if shift value is nonzero
2771 if (magics.s > 0) {
Mehdi Amini9639d652015-07-09 02:09:20 +00002772 Q = DAG.getNode(
2773 ISD::SRA, dl, VT, Q,
2774 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002775 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002776 }
2777 // Extract the sign bit and add it to the quotient
Mehdi Amini9639d652015-07-09 02:09:20 +00002778 SDValue T =
2779 DAG.getNode(ISD::SRL, dl, VT, Q,
2780 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
2781 getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002782 Created->push_back(T.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002783 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002784}
2785
David Majnemer0fc86702013-06-08 23:51:45 +00002786/// \brief Given an ISD::UDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002787/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002788/// multiplying by a magic number.
2789/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002790SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2791 SelectionDAG &DAG, bool IsAfterLegalization,
2792 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002793 assert(Created && "No vector to hold udiv ops.");
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002794
Owen Anderson53aa7a92009-08-10 22:56:29 +00002795 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002796 SDLoc dl(N);
Mehdi Amini9639d652015-07-09 02:09:20 +00002797 auto &DL = DAG.getDataLayout();
Eli Friedman1b7fc152008-11-30 06:02:26 +00002798
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002799 // Check to see if we can do this.
Eli Friedman1b7fc152008-11-30 06:02:26 +00002800 // FIXME: We should be more aggressive here.
2801 if (!isTypeLegal(VT))
2802 return SDValue();
2803
2804 // FIXME: We should use a narrower constant when the upper
2805 // bits are known to be zero.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002806 APInt::mu magics = Divisor.magicu();
Benjamin Kramercfcea122011-03-17 20:39:14 +00002807
2808 SDValue Q = N->getOperand(0);
2809
2810 // If the divisor is even, we can avoid using the expensive fixup by shifting
2811 // the divided value upfront.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002812 if (magics.a != 0 && !Divisor[0]) {
2813 unsigned Shift = Divisor.countTrailingZeros();
Mehdi Amini9639d652015-07-09 02:09:20 +00002814 Q = DAG.getNode(
2815 ISD::SRL, dl, VT, Q,
2816 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002817 Created->push_back(Q.getNode());
Benjamin Kramercfcea122011-03-17 20:39:14 +00002818
2819 // Get magic number for the shifted divisor.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002820 magics = Divisor.lshr(Shift).magicu(Shift);
Benjamin Kramercfcea122011-03-17 20:39:14 +00002821 assert(magics.a == 0 && "Should use cheap fixup now");
2822 }
Eli Friedman1b7fc152008-11-30 06:02:26 +00002823
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002824 // Multiply the numerator (operand 0) by the magic value
Eli Friedman1b7fc152008-11-30 06:02:26 +00002825 // FIXME: We should support doing a MUL in a wider type
Richard Osborne561fac42011-11-07 17:09:05 +00002826 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2827 isOperationLegalOrCustom(ISD::MULHU, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002828 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002829 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2830 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
Benjamin Kramercfcea122011-03-17 20:39:14 +00002831 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002832 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002833 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002834 return SDValue(); // No mulhu or equvialent
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002835
2836 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002837
2838 if (magics.a == 0) {
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002839 assert(magics.s < Divisor.getBitWidth() &&
Eli Friedman1b7fc152008-11-30 06:02:26 +00002840 "We shouldn't generate an undefined shift!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002841 return DAG.getNode(
2842 ISD::SRL, dl, VT, Q,
2843 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002844 } else {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002845 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002846 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002847 NPQ = DAG.getNode(
2848 ISD::SRL, dl, VT, NPQ,
2849 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002850 Created->push_back(NPQ.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002851 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002852 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002853 return DAG.getNode(
2854 ISD::SRL, dl, VT, NPQ,
2855 DAG.getConstant(magics.s - 1, dl,
2856 getShiftAmountTy(NPQ.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002857 }
2858}
Bill Wendling908bf812014-01-06 00:43:20 +00002859
2860bool TargetLowering::
2861verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
2862 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
2863 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
2864 "be a constant integer");
2865 return true;
2866 }
2867
2868 return false;
2869}
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002870
2871//===----------------------------------------------------------------------===//
2872// Legalization Utilities
2873//===----------------------------------------------------------------------===//
2874
2875bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
2876 SelectionDAG &DAG, SDValue LL, SDValue LH,
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002877 SDValue RL, SDValue RH) const {
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002878 EVT VT = N->getValueType(0);
2879 SDLoc dl(N);
2880
2881 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
2882 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
2883 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
2884 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
2885 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
2886 unsigned OuterBitSize = VT.getSizeInBits();
2887 unsigned InnerBitSize = HiLoVT.getSizeInBits();
2888 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
2889 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
2890
2891 // LL, LH, RL, and RH must be either all NULL or all set to a value.
2892 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
2893 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
2894
2895 if (!LL.getNode() && !RL.getNode() &&
2896 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
2897 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
2898 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
2899 }
2900
2901 if (!LL.getNode())
2902 return false;
2903
2904 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
2905 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
2906 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
2907 // The inputs are both zero-extended.
2908 if (HasUMUL_LOHI) {
2909 // We can emit a umul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002910 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
2911 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002912 Hi = SDValue(Lo.getNode(), 1);
2913 return true;
2914 }
2915 if (HasMULHU) {
2916 // We can emit a mulhu+mul.
2917 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2918 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
2919 return true;
2920 }
2921 }
2922 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
2923 // The input values are both sign-extended.
2924 if (HasSMUL_LOHI) {
2925 // We can emit a smul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002926 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
2927 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002928 Hi = SDValue(Lo.getNode(), 1);
2929 return true;
2930 }
2931 if (HasMULHS) {
2932 // We can emit a mulhs+mul.
2933 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2934 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
2935 return true;
2936 }
2937 }
2938
2939 if (!LH.getNode() && !RH.getNode() &&
2940 isOperationLegalOrCustom(ISD::SRL, VT) &&
2941 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +00002942 auto &DL = DAG.getDataLayout();
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002943 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
Mehdi Amini9639d652015-07-09 02:09:20 +00002944 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL));
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002945 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
2946 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
2947 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
2948 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
2949 }
2950
2951 if (!LH.getNode())
2952 return false;
2953
2954 if (HasUMUL_LOHI) {
2955 // Lo,Hi = umul LHS, RHS.
2956 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
2957 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
2958 Lo = UMulLOHI;
2959 Hi = UMulLOHI.getValue(1);
2960 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
2961 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
2962 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
2963 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
2964 return true;
2965 }
2966 if (HasMULHU) {
2967 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
2968 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
2969 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
2970 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
2971 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
2972 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
2973 return true;
2974 }
2975 }
2976 return false;
2977}
Jan Veselyeca89d22014-07-10 22:40:18 +00002978
2979bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
2980 SelectionDAG &DAG) const {
2981 EVT VT = Node->getOperand(0).getValueType();
2982 EVT NVT = Node->getValueType(0);
2983 SDLoc dl(SDValue(Node, 0));
2984
2985 // FIXME: Only f32 to i64 conversions are supported.
2986 if (VT != MVT::f32 || NVT != MVT::i64)
2987 return false;
2988
2989 // Expand f32 -> i64 conversion
2990 // This algorithm comes from compiler-rt's implementation of fixsfdi:
2991 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
2992 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
2993 VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002994 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
2995 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
2996 SDValue Bias = DAG.getConstant(127, dl, IntVT);
2997 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
Jan Veselyeca89d22014-07-10 22:40:18 +00002998 IntVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002999 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3000 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003001
3002 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3003
Mehdi Amini9639d652015-07-09 02:09:20 +00003004 auto &DL = DAG.getDataLayout();
3005 SDValue ExponentBits = DAG.getNode(
3006 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3007 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003008 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3009
Mehdi Amini9639d652015-07-09 02:09:20 +00003010 SDValue Sign = DAG.getNode(
3011 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3012 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003013 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3014
3015 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3016 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003017 DAG.getConstant(0x00800000, dl, IntVT));
Jan Veselyeca89d22014-07-10 22:40:18 +00003018
3019 R = DAG.getZExtOrTrunc(R, dl, NVT);
3020
Mehdi Amini9639d652015-07-09 02:09:20 +00003021 R = DAG.getSelectCC(
3022 dl, Exponent, ExponentLoBit,
3023 DAG.getNode(ISD::SHL, dl, NVT, R,
3024 DAG.getZExtOrTrunc(
3025 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3026 dl, getShiftAmountTy(IntVT, DL))),
3027 DAG.getNode(ISD::SRL, dl, NVT, R,
3028 DAG.getZExtOrTrunc(
3029 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3030 dl, getShiftAmountTy(IntVT, DL))),
3031 ISD::SETGT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003032
3033 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3034 DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3035 Sign);
3036
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003037 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3038 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003039 return true;
3040}
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003041
3042//===----------------------------------------------------------------------===//
3043// Implementation of Emulated TLS Model
3044//===----------------------------------------------------------------------===//
3045
3046SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3047 SelectionDAG &DAG) const {
3048 // Access to address of TLS varialbe xyz is lowered to a function call:
3049 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3050 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3051 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3052 SDLoc dl(GA);
3053
3054 ArgListTy Args;
3055 ArgListEntry Entry;
3056 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3057 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3058 StringRef EmuTlsVarName(NameString);
3059 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
3060 if (!EmuTlsVar)
3061 EmuTlsVar = dyn_cast_or_null<GlobalVariable>(
3062 VariableModule->getOrInsertGlobal(EmuTlsVarName, VoidPtrType));
3063 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3064 Entry.Ty = VoidPtrType;
3065 Args.push_back(Entry);
3066
3067 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3068
3069 TargetLowering::CallLoweringInfo CLI(DAG);
3070 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3071 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args), 0);
3072 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3073
3074 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3075 // At last for X86 targets, maybe good for other targets too?
3076 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3077 MFI->setAdjustsStack(true); // Is this only for X86 target?
3078 MFI->setHasCalls(true);
3079
3080 assert((GA->getOffset() == 0) &&
3081 "Emulated TLS must have zero offset in GlobalAddressSDNode");
3082 return CallResult.first;
3083}