blob: 184f080569295b90503ef43d397dd37cdec7ff50 [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"
Matthias Braun46b0f032016-04-14 01:10:42 +000018#include "llvm/CodeGen/CallingConvLower.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineJumpTableInfo.h"
Matthias Braun46b0f032016-04-14 01:10:42 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalVariable.h"
Bill Wendling908bf812014-01-06 00:43:20 +000027#include "llvm/IR/LLVMContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCExpr.h"
Torok Edwin56d06592009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf0b24d22006-01-30 04:09:27 +000031#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetLoweringObjectFile.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000035#include "llvm/Target/TargetSubtargetInfo.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000036#include <cctype>
Chris Lattner3a4d1b22005-01-07 07:44:53 +000037using namespace llvm;
38
Aditya Nandakumar30531552014-11-13 21:29:21 +000039/// NOTE: The TargetMachine owns TLOF.
40TargetLowering::TargetLowering(const TargetMachine &tm)
41 : TargetLoweringBase(tm) {}
Chris Lattner6f809792005-01-16 07:28:11 +000042
Evan Cheng6af02632005-12-20 06:22:03 +000043const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
Craig Topperc0196b12014-04-14 00:51:57 +000044 return nullptr;
Evan Cheng6af02632005-12-20 06:22:03 +000045}
Evan Cheng9cdc16c2005-12-21 23:05:39 +000046
Rafael Espindolaae0d8662016-06-26 22:13:55 +000047bool TargetLowering::isPositionIndependent() const {
Rafael Espindolab1556c42016-06-28 20:13:36 +000048 return getTargetMachine().isPositionIndependent();
Rafael Espindolaae0d8662016-06-26 22:13:55 +000049}
50
Tim Northoverf1450d82013-01-09 13:18:15 +000051/// Check whether a given call node is in tail position within its function. If
52/// so, it sets Chain to the input chain of the tail call.
53bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
54 SDValue &Chain) const {
55 const Function *F = DAG.getMachineFunction().getFunction();
56
57 // Conservatively require the attributes of the call to match those of
58 // the return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +000059 AttributeSet CallerAttrs = F->getAttributes();
60 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
Tim Northoverf1450d82013-01-09 13:18:15 +000061 .removeAttribute(Attribute::NoAlias).hasAttributes())
62 return false;
63
64 // It's not safe to eliminate the sign / zero extension of the return value.
Bill Wendling658d24d2013-01-18 21:53:16 +000065 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
66 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Tim Northoverf1450d82013-01-09 13:18:15 +000067 return false;
68
69 // Check if the only use is a function return node.
70 return isUsedByReturnOnly(Node, Chain);
71}
72
Matthias Braun46b0f032016-04-14 01:10:42 +000073bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
74 const uint32_t *CallerPreservedMask,
75 const SmallVectorImpl<CCValAssign> &ArgLocs,
76 const SmallVectorImpl<SDValue> &OutVals) const {
77 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
78 const CCValAssign &ArgLoc = ArgLocs[I];
79 if (!ArgLoc.isRegLoc())
80 continue;
81 unsigned Reg = ArgLoc.getLocReg();
82 // Only look at callee saved registers.
83 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
84 continue;
85 // Check that we pass the value used for the caller.
86 // (We look for a CopyFromReg reading a virtual register that is used
87 // for the function live-in value of register Reg)
88 SDValue Value = OutVals[I];
89 if (Value->getOpcode() != ISD::CopyFromReg)
90 return false;
91 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
92 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
93 return false;
94 }
95 return true;
96}
97
Andrew Trick74f4c742013-10-31 17:18:24 +000098/// \brief Set CallLoweringInfo attribute flags based on a call instruction
99/// and called function attributes.
100void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
101 unsigned AttrIdx) {
102 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
103 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
104 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
105 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
106 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
107 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
Reid Klecknerf5b76512014-01-31 23:50:57 +0000108 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
Andrew Trick74f4c742013-10-31 17:18:24 +0000109 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
Manman Renf46262e2016-03-29 17:37:21 +0000110 isSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf);
Manman Ren9bfd0d02016-04-01 21:41:15 +0000111 isSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError);
Andrew Trick74f4c742013-10-31 17:18:24 +0000112 Alignment = CS->getParamAlignment(AttrIdx);
113}
Tim Northoverf1450d82013-01-09 13:18:15 +0000114
115/// Generate a libcall taking the given operands as arguments and returning a
116/// result of type RetVT.
Michael Gottesman7a801722013-08-13 17:54:56 +0000117std::pair<SDValue, SDValue>
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000118TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
119 ArrayRef<SDValue> Ops, bool isSigned,
120 const SDLoc &dl, bool doesNotReturn,
Michael Gottesman7a801722013-08-13 17:54:56 +0000121 bool isReturnValueUsed) const {
Tim Northoverf1450d82013-01-09 13:18:15 +0000122 TargetLowering::ArgListTy Args;
Craig Topper8fe40e02015-10-22 17:05:00 +0000123 Args.reserve(Ops.size());
Tim Northoverf1450d82013-01-09 13:18:15 +0000124
125 TargetLowering::ArgListEntry Entry;
Craig Topper8fe40e02015-10-22 17:05:00 +0000126 for (SDValue Op : Ops) {
127 Entry.Node = Op;
Tim Northoverf1450d82013-01-09 13:18:15 +0000128 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
Craig Topper8fe40e02015-10-22 17:05:00 +0000129 Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
130 Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
Tim Northoverf1450d82013-01-09 13:18:15 +0000131 Args.push_back(Entry);
132 }
Michael Kupersteineaa16002015-10-25 08:14:05 +0000133
Ahmed Bougachae85a2d32015-03-26 22:46:58 +0000134 if (LC == RTLIB::UNKNOWN_LIBCALL)
135 report_fatal_error("Unsupported library call operation!");
Mehdi Amini44ede332015-07-09 02:09:04 +0000136 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
137 getPointerTy(DAG.getDataLayout()));
Tim Northoverf1450d82013-01-09 13:18:15 +0000138
139 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000140 TargetLowering::CallLoweringInfo CLI(DAG);
Petar Jovanovic5b436222015-03-23 12:28:13 +0000141 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000142 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000143 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000144 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
Petar Jovanovic5b436222015-03-23 12:28:13 +0000145 .setSExtResult(signExtend).setZExtResult(!signExtend);
Michael Gottesman7a801722013-08-13 17:54:56 +0000146 return LowerCallTo(CLI);
Tim Northoverf1450d82013-01-09 13:18:15 +0000147}
148
Sanjay Patelac6e9102015-12-29 22:11:50 +0000149/// Soften the operands of a comparison. This code is shared among BR_CC,
150/// SELECT_CC, and SETCC handlers.
Tim Northoverf1450d82013-01-09 13:18:15 +0000151void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
152 SDValue &NewLHS, SDValue &NewRHS,
153 ISD::CondCode &CCCode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000154 const SDLoc &dl) const {
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000155 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
Tim Northoverf1450d82013-01-09 13:18:15 +0000156 && "Unsupported setcc type!");
157
158 // Expand into one or more soft-fp libcall(s).
159 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
Alexey Bataevb9288602015-07-15 08:39:35 +0000160 bool ShouldInvertCC = false;
Tim Northoverf1450d82013-01-09 13:18:15 +0000161 switch (CCCode) {
162 case ISD::SETEQ:
163 case ISD::SETOEQ:
164 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000165 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
166 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000167 break;
168 case ISD::SETNE:
169 case ISD::SETUNE:
170 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000171 (VT == MVT::f64) ? RTLIB::UNE_F64 :
172 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000173 break;
174 case ISD::SETGE:
175 case ISD::SETOGE:
176 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000177 (VT == MVT::f64) ? RTLIB::OGE_F64 :
178 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000179 break;
180 case ISD::SETLT:
181 case ISD::SETOLT:
182 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000183 (VT == MVT::f64) ? RTLIB::OLT_F64 :
184 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000185 break;
186 case ISD::SETLE:
187 case ISD::SETOLE:
188 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000189 (VT == MVT::f64) ? RTLIB::OLE_F64 :
190 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000191 break;
192 case ISD::SETGT:
193 case ISD::SETOGT:
194 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000195 (VT == MVT::f64) ? RTLIB::OGT_F64 :
196 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000197 break;
198 case ISD::SETUO:
199 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000200 (VT == MVT::f64) ? RTLIB::UO_F64 :
201 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000202 break;
203 case ISD::SETO:
204 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000205 (VT == MVT::f64) ? RTLIB::O_F64 :
206 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000207 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000208 case ISD::SETONE:
209 // SETONE = SETOLT | SETOGT
210 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000211 (VT == MVT::f64) ? RTLIB::OLT_F64 :
212 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000213 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000214 (VT == MVT::f64) ? RTLIB::OGT_F64 :
215 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000216 break;
217 case ISD::SETUEQ:
Tim Northoverf1450d82013-01-09 13:18:15 +0000218 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000219 (VT == MVT::f64) ? RTLIB::UO_F64 :
220 (VT == MVT::f128) ? RTLIB::UO_F64 : RTLIB::UO_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000221 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000222 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
223 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000224 break;
225 default:
226 // Invert CC for unordered comparisons
227 ShouldInvertCC = true;
Tim Northoverf1450d82013-01-09 13:18:15 +0000228 switch (CCCode) {
Alexey Bataevb9288602015-07-15 08:39:35 +0000229 case ISD::SETULT:
230 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000231 (VT == MVT::f64) ? RTLIB::OGE_F64 :
232 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000233 break;
Tim Northoverf1450d82013-01-09 13:18:15 +0000234 case ISD::SETULE:
Alexey Bataevb9288602015-07-15 08:39:35 +0000235 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000236 (VT == MVT::f64) ? RTLIB::OGT_F64 :
237 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000238 break;
239 case ISD::SETUGT:
240 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000241 (VT == MVT::f64) ? RTLIB::OLE_F64 :
242 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000243 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000244 case ISD::SETUGE:
245 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000246 (VT == MVT::f64) ? RTLIB::OLT_F64 :
247 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000248 break;
249 default: llvm_unreachable("Do not know how to soften this setcc!");
250 }
251 }
252
253 // Use the target specific return value for comparions lib calls.
254 EVT RetVT = getCmpLibcallReturnType();
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000255 SDValue Ops[2] = {NewLHS, NewRHS};
Craig Topper8fe40e02015-10-22 17:05:00 +0000256 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
257 dl).first;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000258 NewRHS = DAG.getConstant(0, dl, RetVT);
Alexey Bataevb9288602015-07-15 08:39:35 +0000259
Tim Northoverf1450d82013-01-09 13:18:15 +0000260 CCCode = getCmpLibcallCC(LC1);
Alexey Bataevb9288602015-07-15 08:39:35 +0000261 if (ShouldInvertCC)
262 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
263
Tim Northoverf1450d82013-01-09 13:18:15 +0000264 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000265 SDValue Tmp = DAG.getNode(
266 ISD::SETCC, dl,
267 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
268 NewLHS, NewRHS, DAG.getCondCode(CCCode));
Craig Topper8fe40e02015-10-22 17:05:00 +0000269 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
270 dl).first;
Mehdi Amini44ede332015-07-09 02:09:04 +0000271 NewLHS = DAG.getNode(
272 ISD::SETCC, dl,
273 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
274 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
Tim Northoverf1450d82013-01-09 13:18:15 +0000275 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
276 NewRHS = SDValue();
277 }
278}
279
Sanjay Patelac6e9102015-12-29 22:11:50 +0000280/// Return the entry encoding for a jump table in the current function. The
281/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000282unsigned TargetLowering::getJumpTableEncoding() const {
283 // In non-pic modes, just use the address of a block.
Rafael Espindola12bb38d2016-06-26 22:30:06 +0000284 if (!isPositionIndependent())
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000285 return MachineJumpTableInfo::EK_BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000286
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000287 // In PIC mode, if the target supports a GPRel32 directive, use it.
Craig Topperc0196b12014-04-14 00:51:57 +0000288 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000289 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000290
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000291 // Otherwise, use a label difference.
292 return MachineJumpTableInfo::EK_LabelDifference32;
293}
294
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000295SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
296 SelectionDAG &DAG) const {
Chris Lattner547c7612010-01-26 06:53:37 +0000297 // If our PIC model is GP relative, use the global offset table as the base.
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000298 unsigned JTEncoding = getJumpTableEncoding();
299
300 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
301 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
Mehdi Amini44ede332015-07-09 02:09:04 +0000302 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000303
Evan Cheng797d56f2007-11-09 01:32:10 +0000304 return Table;
305}
306
Sanjay Patelac6e9102015-12-29 22:11:50 +0000307/// This returns the relocation base for the given PIC jumptable, the same as
308/// getPICJumpTableRelocBase, but as an MCExpr.
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000309const MCExpr *
Chris Lattner8a785d72010-01-26 06:28:43 +0000310TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
311 unsigned JTI,MCContext &Ctx) const{
Chris Lattner273735b2010-01-26 05:58:28 +0000312 // The normal PIC reloc base is the label at the start of the jump table.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000313 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000314}
315
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000316bool
317TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000318 const TargetMachine &TM = getTargetMachine();
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000319 const GlobalValue *GV = GA->getGlobal();
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000320
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000321 // If the address is not even local to this DSO we will have to load it from
322 // a got and then add the offset.
Rafael Espindola3beef8d2016-06-27 23:15:57 +0000323 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000324 return false;
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000325
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000326 // If the code is position independent we will have to add a base register.
Rafael Espindola0a68bf92016-06-26 22:38:44 +0000327 if (isPositionIndependent())
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000328 return false;
329
330 // Otherwise we can do it.
331 return true;
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000332}
333
Chris Lattneree1dadb2006-02-04 02:13:02 +0000334//===----------------------------------------------------------------------===//
335// Optimization Methods
336//===----------------------------------------------------------------------===//
337
Sanjay Patelac6e9102015-12-29 22:11:50 +0000338/// Check to see if the specified operand of the specified instruction is a
339/// constant integer. If so, check to see if there are any bits set in the
340/// constant that are not demanded. If so, shrink the constant and return true.
Wesley Peck527da1b2010-11-23 03:31:01 +0000341bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000342 const APInt &Demanded) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000343 SDLoc dl(Op);
Bill Wendling6d271472009-03-04 00:18:06 +0000344
Chris Lattner118ddba2006-02-26 23:36:02 +0000345 // FIXME: ISD::SELECT, ISD::SELECT_CC
Dan Gohmane58ab792009-01-29 01:59:02 +0000346 switch (Op.getOpcode()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000347 default: break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000348 case ISD::XOR:
Bill Wendling6d271472009-03-04 00:18:06 +0000349 case ISD::AND:
350 case ISD::OR: {
351 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
352 if (!C) return false;
353
354 if (Op.getOpcode() == ISD::XOR &&
355 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
356 return false;
357
358 // if we can expand it to have all bits set, do it
359 if (C->getAPIntValue().intersects(~Demanded)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000360 EVT VT = Op.getValueType();
Bill Wendling6d271472009-03-04 00:18:06 +0000361 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
362 DAG.getConstant(Demanded &
Wesley Peck527da1b2010-11-23 03:31:01 +0000363 C->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000364 dl, VT));
Bill Wendling6d271472009-03-04 00:18:06 +0000365 return CombineTo(Op, New);
366 }
367
Nate Begemandc7bba92006-02-03 22:24:05 +0000368 break;
369 }
Bill Wendling6d271472009-03-04 00:18:06 +0000370 }
371
Nate Begemandc7bba92006-02-03 22:24:05 +0000372 return false;
373}
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000374
Sanjay Patelac6e9102015-12-29 22:11:50 +0000375/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
376/// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
377/// generalized for targets with other types of implicit widening casts.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000378bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
379 unsigned BitWidth,
380 const APInt &Demanded,
381 const SDLoc &dl) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000382 assert(Op.getNumOperands() == 2 &&
383 "ShrinkDemandedOp only supports binary operators!");
384 assert(Op.getNode()->getNumValues() == 1 &&
385 "ShrinkDemandedOp only supports nodes with one result!");
386
Hao Liu40914502014-05-29 09:19:07 +0000387 // Early return, as this function cannot handle vector types.
388 if (Op.getValueType().isVector())
389 return false;
390
Dan Gohmanad3e5492009-04-08 00:15:30 +0000391 // Don't do this if the node has another user, which may require the
392 // full value.
393 if (!Op.getNode()->hasOneUse())
394 return false;
395
396 // Search for the smallest integer type with free casts to and from
397 // Op's type. For expedience, just check power-of-2 integer types.
398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Nadav Rotem33360d82012-12-19 07:39:08 +0000399 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
400 unsigned SmallVTBits = DemandedSize;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000401 if (!isPowerOf2_32(SmallVTBits))
402 SmallVTBits = NextPowerOf2(SmallVTBits);
403 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
Owen Anderson117c9e82009-08-12 00:36:31 +0000404 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000405 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
406 TLI.isZExtFree(SmallVT, Op.getValueType())) {
407 // We found a type with free casts.
408 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
409 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
410 Op.getNode()->getOperand(0)),
411 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
412 Op.getNode()->getOperand(1)));
Nadav Rotem33360d82012-12-19 07:39:08 +0000413 bool NeedZext = DemandedSize > SmallVTBits;
414 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
415 dl, Op.getValueType(), X);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000416 return CombineTo(Op, Z);
417 }
418 }
419 return false;
420}
421
Sanjay Patelac6e9102015-12-29 22:11:50 +0000422/// Look at Op. At this point, we know that only the DemandedMask bits of the
423/// result of Op are ever used downstream. If we can use this information to
424/// simplify Op, create a new simplified DAG node and return true, returning the
425/// original and new nodes in Old and New. Otherwise, analyze the expression and
426/// return a mask of KnownOne and KnownZero bits for the expression (used to
427/// simplify the caller). The KnownZero/One bits may only be accurate for those
428/// bits in the DemandedMask.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000429bool TargetLowering::SimplifyDemandedBits(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000430 const APInt &DemandedMask,
431 APInt &KnownZero,
432 APInt &KnownOne,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000433 TargetLoweringOpt &TLO,
434 unsigned Depth) const {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000435 unsigned BitWidth = DemandedMask.getBitWidth();
Dan Gohman1d459e42009-12-11 21:31:27 +0000436 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000437 "Mask size mismatches value type size!");
438 APInt NewMask = DemandedMask;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000439 SDLoc dl(Op);
Mehdi Amini9639d652015-07-09 02:09:20 +0000440 auto &DL = TLO.DAG.getDataLayout();
Chris Lattner0184f882007-05-17 18:19:23 +0000441
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000442 // Don't know anything.
443 KnownZero = KnownOne = APInt(BitWidth, 0);
444
Nate Begeman8a77efe2006-02-16 21:11:51 +0000445 // Other users may use these bits.
Wesley Peck527da1b2010-11-23 03:31:01 +0000446 if (!Op.getNode()->hasOneUse()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000447 if (Depth != 0) {
Wesley Peck527da1b2010-11-23 03:31:01 +0000448 // If not at the root, Just compute the KnownZero/KnownOne bits to
Nate Begeman8a77efe2006-02-16 21:11:51 +0000449 // simplify things downstream.
Jay Foada0653a32014-05-14 21:14:37 +0000450 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Nate Begeman8a77efe2006-02-16 21:11:51 +0000451 return false;
452 }
453 // If this is the root being simplified, allow it to have multiple uses,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000454 // just set the NewMask to all bits.
455 NewMask = APInt::getAllOnesValue(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000456 } else if (DemandedMask == 0) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000457 // Not demanding any bits from Op.
Sanjay Patel75068522016-03-14 18:09:43 +0000458 if (!Op.isUndef())
Dale Johannesen84935752009-02-06 23:05:02 +0000459 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000460 return false;
461 } else if (Depth == 6) { // Limit search depth.
462 return false;
463 }
464
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000465 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000466 switch (Op.getOpcode()) {
467 case ISD::Constant:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000468 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000469 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
470 KnownZero = ~KnownOne;
Chris Lattner118ddba2006-02-26 23:36:02 +0000471 return false; // Don't fall through, will infinitely loop.
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000472 case ISD::AND:
Chris Lattnera60751d2006-02-27 00:36:27 +0000473 // If the RHS is a constant, check to see if the LHS would be zero without
474 // using the bits from the RHS. Below, we use knowledge about the RHS to
475 // simplify the LHS, here we're using information from the LHS to simplify
476 // the RHS.
477 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000478 APInt LHSZero, LHSOne;
Dale Johannesend2b48112011-01-10 21:53:07 +0000479 // Do not increment Depth here; that can cause an infinite loop.
Jay Foada0653a32014-05-14 21:14:37 +0000480 TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
Chris Lattnera60751d2006-02-27 00:36:27 +0000481 // If the LHS already has zeros where RHSC does, this and is dead.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000482 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000483 return TLO.CombineTo(Op, Op.getOperand(0));
484 // If any of the set bits in the RHS are known zero on the LHS, shrink
485 // the constant.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000486 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000487 return true;
488 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000489
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000490 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000491 KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000492 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000493 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000494 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000495 KnownZero2, KnownOne2, TLO, Depth+1))
496 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000497 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
498
Nate Begeman8a77efe2006-02-16 21:11:51 +0000499 // If all of the demanded bits are known one on one side, return the other.
500 // These bits cannot contribute to the result of the 'and'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000501 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000502 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000503 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000504 return TLO.CombineTo(Op, Op.getOperand(1));
505 // If all of the demanded bits in the inputs are known zeros, return zero.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000506 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000507 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000508 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000509 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000510 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000511 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000512 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000513 return true;
514
Nate Begeman8a77efe2006-02-16 21:11:51 +0000515 // Output known-1 bits are only known if set in both the LHS & RHS.
516 KnownOne &= KnownOne2;
517 // Output known-0 are known to be clear if zero in either the LHS | RHS.
518 KnownZero |= KnownZero2;
519 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000520 case ISD::OR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000521 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000522 KnownOne, TLO, Depth+1))
523 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000524 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000525 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000526 KnownZero2, KnownOne2, TLO, Depth+1))
527 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000528 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
529
Nate Begeman8a77efe2006-02-16 21:11:51 +0000530 // If all of the demanded bits are known zero on one side, return the other.
531 // These bits cannot contribute to the result of the 'or'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000532 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000533 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000534 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000535 return TLO.CombineTo(Op, Op.getOperand(1));
536 // If all of the potentially set bits on one side are known to be set on
537 // the other side, just use the 'other' side.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000538 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000539 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000540 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000541 return TLO.CombineTo(Op, Op.getOperand(1));
542 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000543 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000544 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000545 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000546 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000547 return true;
548
Nate Begeman8a77efe2006-02-16 21:11:51 +0000549 // Output known-0 bits are only known if clear in both the LHS & RHS.
550 KnownZero &= KnownZero2;
551 // Output known-1 are known to be set if set in either the LHS | RHS.
552 KnownOne |= KnownOne2;
553 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000554 case ISD::XOR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000555 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000556 KnownOne, TLO, Depth+1))
557 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000558 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000559 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000560 KnownOne2, TLO, Depth+1))
561 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000562 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
563
Nate Begeman8a77efe2006-02-16 21:11:51 +0000564 // If all of the demanded bits are known zero on one side, return the other.
565 // These bits cannot contribute to the result of the 'xor'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000566 if ((KnownZero & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000567 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000568 if ((KnownZero2 & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000569 return TLO.CombineTo(Op, Op.getOperand(1));
Dan Gohmanad3e5492009-04-08 00:15:30 +0000570 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000571 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000572 return true;
573
Chris Lattner5d5916b2006-11-27 21:50:02 +0000574 // If all of the unknown bits are known to be zero on one side or the other
575 // (but not both) turn this into an *inclusive* or.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000576 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000577 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
Dale Johannesen400dc2e2009-02-06 21:50:26 +0000578 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
Chris Lattner5d5916b2006-11-27 21:50:02 +0000579 Op.getOperand(0),
580 Op.getOperand(1)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000581
Nate Begeman8a77efe2006-02-16 21:11:51 +0000582 // Output known-0 bits are known if clear or set in both the LHS & RHS.
583 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
584 // Output known-1 are known to be set if set in only one of the LHS, RHS.
585 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
Wesley Peck527da1b2010-11-23 03:31:01 +0000586
Nate Begeman8a77efe2006-02-16 21:11:51 +0000587 // If all of the demanded bits on one side are known, and all of the set
588 // bits on that side are also known to be set on the other side, turn this
589 // into an AND, as we know the bits will be cleared.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000590 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Joel Jones828531f2012-04-17 22:23:10 +0000591 // NB: it is okay if more bits are known than are requested
Stephen Lincfe7f352013-07-08 00:37:03 +0000592 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
Joel Jones828531f2012-04-17 22:23:10 +0000593 if (KnownOne == KnownOne2) { // set bits are the same on both sides
Owen Anderson53aa7a92009-08-10 22:56:29 +0000594 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000595 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000596 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
Dale Johannesenf1163e92009-02-03 00:47:48 +0000597 Op.getOperand(0), ANDC));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000598 }
599 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000600
Nate Begeman8a77efe2006-02-16 21:11:51 +0000601 // If the RHS is a constant, see if we can simplify it.
Torok Edwin613d7af2008-04-06 21:23:02 +0000602 // for XOR, we prefer to force bits to 1 if they will make a -1.
603 // if we can't force bits, try to shrink constant
604 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
605 APInt Expanded = C->getAPIntValue() | (~NewMask);
606 // if we can expand it to have all bits set, do it
607 if (Expanded.isAllOnesValue()) {
608 if (Expanded != C->getAPIntValue()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000609 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000610 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000611 TLO.DAG.getConstant(Expanded, dl, VT));
Torok Edwin613d7af2008-04-06 21:23:02 +0000612 return TLO.CombineTo(Op, New);
613 }
614 // if it already has all the bits set, nothing to change
615 // but don't shrink either!
616 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
617 return true;
618 }
619 }
620
Nate Begeman8a77efe2006-02-16 21:11:51 +0000621 KnownZero = KnownZeroOut;
622 KnownOne = KnownOneOut;
623 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000624 case ISD::SELECT:
Wesley Peck527da1b2010-11-23 03:31:01 +0000625 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000626 KnownOne, TLO, Depth+1))
627 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000628 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000629 KnownOne2, TLO, Depth+1))
630 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000631 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
632 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
633
Nate Begeman8a77efe2006-02-16 21:11:51 +0000634 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000635 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000636 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000637
Nate Begeman8a77efe2006-02-16 21:11:51 +0000638 // Only known if known in both the LHS and RHS.
639 KnownOne &= KnownOne2;
640 KnownZero &= KnownZero2;
641 break;
Chris Lattner118ddba2006-02-26 23:36:02 +0000642 case ISD::SELECT_CC:
Wesley Peck527da1b2010-11-23 03:31:01 +0000643 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +0000644 KnownOne, TLO, Depth+1))
645 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000646 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
Chris Lattner118ddba2006-02-26 23:36:02 +0000647 KnownOne2, TLO, Depth+1))
648 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000649 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
650 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651
Chris Lattner118ddba2006-02-26 23:36:02 +0000652 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000653 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Chris Lattner118ddba2006-02-26 23:36:02 +0000654 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000655
Chris Lattner118ddba2006-02-26 23:36:02 +0000656 // Only known if known in both the LHS and RHS.
657 KnownOne &= KnownOne2;
658 KnownZero &= KnownZero2;
659 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000660 case ISD::SHL:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000661 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000662 unsigned ShAmt = SA->getZExtValue();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000663 SDValue InOp = Op.getOperand(0);
Chris Lattner9a861a82007-04-17 21:14:16 +0000664
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000665 // If the shift count is an invalid immediate, don't do anything.
666 if (ShAmt >= BitWidth)
667 break;
668
Chris Lattner9a861a82007-04-17 21:14:16 +0000669 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
670 // single shift. We can do this if the bottom bits (which are shifted
671 // out) are never demanded.
672 if (InOp.getOpcode() == ISD::SRL &&
673 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000674 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000675 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000676 unsigned Opc = ISD::SHL;
677 int Diff = ShAmt-C1;
678 if (Diff < 0) {
679 Diff = -Diff;
680 Opc = ISD::SRL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000681 }
682
683 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000684 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Owen Anderson53aa7a92009-08-10 22:56:29 +0000685 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000686 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000687 InOp.getOperand(0), NewSA));
688 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000689 }
690
Dan Gohman08186842010-07-23 18:03:30 +0000691 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
Nate Begeman8a77efe2006-02-16 21:11:51 +0000692 KnownZero, KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000693 return true;
Dan Gohman08186842010-07-23 18:03:30 +0000694
695 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
696 // are not demanded. This will likely allow the anyext to be folded away.
697 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
698 SDValue InnerOp = InOp.getNode()->getOperand(0);
699 EVT InnerVT = InnerOp.getValueType();
Eli Friedman053a7242011-12-09 01:16:26 +0000700 unsigned InnerBits = InnerVT.getSizeInBits();
701 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
Dan Gohman08186842010-07-23 18:03:30 +0000702 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +0000703 EVT ShTy = getShiftAmountTy(InnerVT, DL);
Dan Gohman55e24462010-07-23 21:08:12 +0000704 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
705 ShTy = InnerVT;
Dan Gohman08186842010-07-23 18:03:30 +0000706 SDValue NarrowShl =
707 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000708 TLO.DAG.getConstant(ShAmt, dl, ShTy));
Dan Gohman08186842010-07-23 18:03:30 +0000709 return
710 TLO.CombineTo(Op,
711 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
712 NarrowShl));
713 }
Richard Sandiford374a0e52013-10-16 10:26:19 +0000714 // Repeat the SHL optimization above in cases where an extension
715 // intervenes: (shl (anyext (shr x, c1)), c2) to
716 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
717 // aren't demanded (as above) and that the shifted upper c1 bits of
718 // x aren't demanded.
719 if (InOp.hasOneUse() &&
720 InnerOp.getOpcode() == ISD::SRL &&
721 InnerOp.hasOneUse() &&
722 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
723 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
724 ->getZExtValue();
725 if (InnerShAmt < ShAmt &&
726 InnerShAmt < InnerBits &&
727 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
728 NewMask.trunc(ShAmt) == 0) {
729 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000730 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
Richard Sandiford374a0e52013-10-16 10:26:19 +0000731 Op.getOperand(1).getValueType());
732 EVT VT = Op.getValueType();
733 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
734 InnerOp.getOperand(0));
735 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
736 NewExt, NewSA));
737 }
738 }
Dan Gohman08186842010-07-23 18:03:30 +0000739 }
740
Dan Gohmaneffb8942008-09-12 16:56:44 +0000741 KnownZero <<= SA->getZExtValue();
742 KnownOne <<= SA->getZExtValue();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000743 // low bits known zero.
Dan Gohmaneffb8942008-09-12 16:56:44 +0000744 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000745 }
746 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000747 case ISD::SRL:
748 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000749 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000750 unsigned ShAmt = SA->getZExtValue();
Duncan Sands13237ac2008-06-06 12:08:01 +0000751 unsigned VTSize = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000752 SDValue InOp = Op.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +0000753
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000754 // If the shift count is an invalid immediate, don't do anything.
755 if (ShAmt >= BitWidth)
756 break;
757
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000758 APInt InDemandedMask = (NewMask << ShAmt);
759
760 // If the shift is exact, then it does demand the low bits (and knows that
761 // they are zero).
762 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
763 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
764
Chris Lattner9a861a82007-04-17 21:14:16 +0000765 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
766 // single shift. We can do this if the top bits (which are shifted out)
767 // are never demanded.
768 if (InOp.getOpcode() == ISD::SHL &&
769 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000770 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000771 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000772 unsigned Opc = ISD::SRL;
773 int Diff = ShAmt-C1;
774 if (Diff < 0) {
775 Diff = -Diff;
776 Opc = ISD::SHL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000777 }
778
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000779 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000780 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Dale Johannesenf1163e92009-02-03 00:47:48 +0000781 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000782 InOp.getOperand(0), NewSA));
783 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000784 }
785
Nate Begeman8a77efe2006-02-16 21:11:51 +0000786 // Compute the new bits that are at the top now.
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000787 if (SimplifyDemandedBits(InOp, InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000788 KnownZero, KnownOne, TLO, Depth+1))
789 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000790 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000791 KnownZero = KnownZero.lshr(ShAmt);
792 KnownOne = KnownOne.lshr(ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000793
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000794 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000795 KnownZero |= HighBits; // High bits known zero.
Nate Begeman8a77efe2006-02-16 21:11:51 +0000796 }
797 break;
798 case ISD::SRA:
Dan Gohmane58ab792009-01-29 01:59:02 +0000799 // If this is an arithmetic shift right and only the low-bit is set, we can
800 // always convert this into a logical shr, even if the shift amount is
801 // variable. The low bit of the shift cannot be an input sign bit unless
802 // the shift amount is >= the size of the datatype, which is undefined.
Eli Friedman053a7242011-12-09 01:16:26 +0000803 if (NewMask == 1)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000804 return TLO.CombineTo(Op,
805 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
806 Op.getOperand(0), Op.getOperand(1)));
Dan Gohmane58ab792009-01-29 01:59:02 +0000807
Nate Begeman8a77efe2006-02-16 21:11:51 +0000808 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000809 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000810 unsigned ShAmt = SA->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +0000811
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000812 // If the shift count is an invalid immediate, don't do anything.
813 if (ShAmt >= BitWidth)
814 break;
815
816 APInt InDemandedMask = (NewMask << ShAmt);
Chris Lattner10c65372006-05-08 17:22:53 +0000817
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000818 // If the shift is exact, then it does demand the low bits (and knows that
819 // they are zero).
820 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
821 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
822
Chris Lattner10c65372006-05-08 17:22:53 +0000823 // If any of the demanded bits are produced by the sign extension, we also
824 // demand the input sign bit.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000825 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
826 if (HighBits.intersects(NewMask))
Dan Gohman1d459e42009-12-11 21:31:27 +0000827 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000828
Chris Lattner10c65372006-05-08 17:22:53 +0000829 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000830 KnownZero, KnownOne, TLO, Depth+1))
831 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000832 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000833 KnownZero = KnownZero.lshr(ShAmt);
834 KnownOne = KnownOne.lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000835
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000836 // Handle the sign bit, adjusted to where it is now in the mask.
837 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000838
Nate Begeman8a77efe2006-02-16 21:11:51 +0000839 // If the input sign bit is known to be zero, or if none of the top bits
840 // are demanded, turn this into an unsigned shift right.
Benjamin Kramerc2ae7672015-06-26 14:51:49 +0000841 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
842 SDNodeFlags Flags;
843 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
844 return TLO.CombineTo(Op,
845 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
846 Op.getOperand(1), &Flags));
847 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000848
849 int Log2 = NewMask.exactLogBase2();
850 if (Log2 >= 0) {
851 // The bit must come from the sign.
852 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000853 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000854 Op.getOperand(1).getValueType());
855 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
856 Op.getOperand(0), NewSA));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000857 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000858
859 if (KnownOne.intersects(SignBit))
860 // New bits are known one.
861 KnownOne |= HighBits;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000862 }
863 break;
864 case ISD::SIGN_EXTEND_INREG: {
Nadav Rotem57935242012-01-15 19:27:55 +0000865 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
866
867 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
868 // If we only care about the highest bit, don't bother shifting right.
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000869 if (MsbMask == NewMask) {
Nadav Rotem57935242012-01-15 19:27:55 +0000870 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
871 SDValue InOp = Op.getOperand(0);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000872 unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
873 bool AlreadySignExtended =
874 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
875 // However if the input is already sign extended we expect the sign
876 // extension to be dropped altogether later and do not simplify.
877 if (!AlreadySignExtended) {
878 // Compute the correct shift amount type, which must be getShiftAmountTy
879 // for scalar types after legalization.
880 EVT ShiftAmtTy = Op.getValueType();
881 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
Mehdi Amini9639d652015-07-09 02:09:20 +0000882 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
Eli Friedman18a4c312012-01-31 01:08:03 +0000883
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000884 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
885 ShiftAmtTy);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000886 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
887 Op.getValueType(), InOp,
888 ShiftAmt));
889 }
Nadav Rotem57935242012-01-15 19:27:55 +0000890 }
Nate Begeman8a77efe2006-02-16 21:11:51 +0000891
Wesley Peck527da1b2010-11-23 03:31:01 +0000892 // Sign extension. Compute the demanded bits in the result that are not
Nate Begeman8a77efe2006-02-16 21:11:51 +0000893 // present in the input.
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000894 APInt NewBits =
895 APInt::getHighBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000896 BitWidth - ExVT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000897
Chris Lattner118ddba2006-02-26 23:36:02 +0000898 // If none of the extended bits are demanded, eliminate the sextinreg.
Eli Friedman460ad412010-08-02 04:42:25 +0000899 if ((NewBits & NewMask) == 0)
Chris Lattner118ddba2006-02-26 23:36:02 +0000900 return TLO.CombineTo(Op, Op.getOperand(0));
901
Jay Foad583abbc2010-12-07 08:25:19 +0000902 APInt InSignBit =
Nadav Rotem57935242012-01-15 19:27:55 +0000903 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000904 APInt InputDemandedBits =
905 APInt::getLowBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000906 ExVT.getScalarType().getSizeInBits()) &
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000907 NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +0000908
Chris Lattner118ddba2006-02-26 23:36:02 +0000909 // Since the sign extended bits are demanded, we know that the sign
Nate Begeman8a77efe2006-02-16 21:11:51 +0000910 // bit is demanded.
Chris Lattner118ddba2006-02-26 23:36:02 +0000911 InputDemandedBits |= InSignBit;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000912
913 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
914 KnownZero, KnownOne, TLO, Depth+1))
915 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000916 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Nate Begeman8a77efe2006-02-16 21:11:51 +0000917
918 // If the sign bit of the input is known set or clear, then we know the
919 // top bits of the result.
Wesley Peck527da1b2010-11-23 03:31:01 +0000920
Chris Lattner118ddba2006-02-26 23:36:02 +0000921 // If the input sign bit is known zero, convert this into a zero extension.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000922 if (KnownZero.intersects(InSignBit))
Wesley Peck527da1b2010-11-23 03:31:01 +0000923 return TLO.CombineTo(Op,
Nadav Rotem57935242012-01-15 19:27:55 +0000924 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
Wesley Peck527da1b2010-11-23 03:31:01 +0000925
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000926 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
Nate Begeman8a77efe2006-02-16 21:11:51 +0000927 KnownOne |= NewBits;
928 KnownZero &= ~NewBits;
Chris Lattner118ddba2006-02-26 23:36:02 +0000929 } else { // Input sign bit unknown
Nate Begeman8a77efe2006-02-16 21:11:51 +0000930 KnownZero &= ~NewBits;
931 KnownOne &= ~NewBits;
932 }
933 break;
934 }
Matt Arsenault2adca602014-05-12 17:14:48 +0000935 case ISD::BUILD_PAIR: {
936 EVT HalfVT = Op.getOperand(0).getValueType();
937 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
938
939 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
940 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
941
942 APInt KnownZeroLo, KnownOneLo;
943 APInt KnownZeroHi, KnownOneHi;
944
945 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
946 KnownOneLo, TLO, Depth + 1))
947 return true;
948
949 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
950 KnownOneHi, TLO, Depth + 1))
951 return true;
952
953 KnownZero = KnownZeroLo.zext(BitWidth) |
954 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
955
956 KnownOne = KnownOneLo.zext(BitWidth) |
957 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
958 break;
959 }
Chris Lattner118ddba2006-02-26 23:36:02 +0000960 case ISD::ZERO_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000961 unsigned OperandBitWidth =
962 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000963 APInt InMask = NewMask.trunc(OperandBitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000964
Chris Lattner118ddba2006-02-26 23:36:02 +0000965 // If none of the top bits are demanded, convert this into an any_extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000966 APInt NewBits =
967 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
968 if (!NewBits.intersects(NewMask))
Dale Johannesenf1163e92009-02-03 00:47:48 +0000969 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +0000970 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +0000971 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000972
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000973 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +0000974 KnownZero, KnownOne, TLO, Depth+1))
975 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000976 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +0000977 KnownZero = KnownZero.zext(BitWidth);
978 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +0000979 KnownZero |= NewBits;
980 break;
981 }
982 case ISD::SIGN_EXTEND: {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000983 EVT InVT = Op.getOperand(0).getValueType();
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000984 unsigned InBits = InVT.getScalarType().getSizeInBits();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000985 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
Dan Gohman44b4c072008-03-11 21:29:43 +0000986 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000987 APInt NewBits = ~InMask & NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +0000988
Chris Lattner118ddba2006-02-26 23:36:02 +0000989 // If none of the top bits are demanded, convert this into an any_extend.
990 if (NewBits == 0)
Dale Johannesenf1163e92009-02-03 00:47:48 +0000991 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
992 Op.getValueType(),
993 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000994
Chris Lattner118ddba2006-02-26 23:36:02 +0000995 // Since some of the sign extended bits are demanded, we know that the sign
996 // bit is demanded.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000997 APInt InDemandedBits = InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +0000998 InDemandedBits |= InSignBit;
Jay Foad583abbc2010-12-07 08:25:19 +0000999 InDemandedBits = InDemandedBits.trunc(InBits);
Wesley Peck527da1b2010-11-23 03:31:01 +00001000
1001 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +00001002 KnownOne, TLO, Depth+1))
1003 return true;
Jay Foad583abbc2010-12-07 08:25:19 +00001004 KnownZero = KnownZero.zext(BitWidth);
1005 KnownOne = KnownOne.zext(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +00001006
Chris Lattner118ddba2006-02-26 23:36:02 +00001007 // If the sign bit is known zero, convert this to a zero extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001008 if (KnownZero.intersects(InSignBit))
Dale Johannesenf1163e92009-02-03 00:47:48 +00001009 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +00001010 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +00001011 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00001012
Chris Lattner118ddba2006-02-26 23:36:02 +00001013 // If the sign bit is known one, the top bits match.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001014 if (KnownOne.intersects(InSignBit)) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001015 KnownOne |= NewBits;
1016 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +00001017 } else { // Otherwise, top bits aren't known.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001018 assert((KnownOne & NewBits) == 0);
1019 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +00001020 }
1021 break;
1022 }
1023 case ISD::ANY_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00001024 unsigned OperandBitWidth =
1025 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +00001026 APInt InMask = NewMask.trunc(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001027 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001028 KnownZero, KnownOne, TLO, Depth+1))
1029 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001030 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +00001031 KnownZero = KnownZero.zext(BitWidth);
1032 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +00001033 break;
1034 }
Chris Lattner0f649322006-05-05 22:32:12 +00001035 case ISD::TRUNCATE: {
Chris Lattner86a14672006-05-06 00:11:52 +00001036 // Simplify the input, using demanded bit information, and compute the known
1037 // zero/one bits live out.
Dan Gohmanc3c3c682010-03-01 17:59:21 +00001038 unsigned OperandBitWidth =
1039 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +00001040 APInt TruncMask = NewMask.zext(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001041 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
Chris Lattner0f649322006-05-05 22:32:12 +00001042 KnownZero, KnownOne, TLO, Depth+1))
1043 return true;
Jay Foad583abbc2010-12-07 08:25:19 +00001044 KnownZero = KnownZero.trunc(BitWidth);
1045 KnownOne = KnownOne.trunc(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +00001046
Chris Lattner86a14672006-05-06 00:11:52 +00001047 // If the input is only used by this truncate, see if we can shrink it based
1048 // on the known demanded bits.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001049 if (Op.getOperand(0).getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001050 SDValue In = Op.getOperand(0);
Chris Lattner86a14672006-05-06 00:11:52 +00001051 switch (In.getOpcode()) {
1052 default: break;
1053 case ISD::SRL:
1054 // Shrink SRL by a constant if none of the high bits shifted in are
1055 // demanded.
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001056 if (TLO.LegalTypes() &&
1057 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1058 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1059 // undesirable.
1060 break;
1061 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1062 if (!ShAmt)
1063 break;
Owen Anderson9c128342011-04-13 23:22:23 +00001064 SDValue Shift = In.getOperand(1);
1065 if (TLO.LegalTypes()) {
1066 uint64_t ShVal = ShAmt->getZExtValue();
Mehdi Amini9639d652015-07-09 02:09:20 +00001067 Shift = TLO.DAG.getConstant(ShVal, dl,
1068 getShiftAmountTy(Op.getValueType(), DL));
Owen Anderson9c128342011-04-13 23:22:23 +00001069 }
1070
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001071 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1072 OperandBitWidth - BitWidth);
Jay Foad583abbc2010-12-07 08:25:19 +00001073 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001074
1075 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1076 // None of the shifted in bits are needed. Add a truncate of the
1077 // shift input, then shift it.
1078 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +00001079 Op.getValueType(),
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001080 In.getOperand(0));
1081 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1082 Op.getValueType(),
Wesley Peck527da1b2010-11-23 03:31:01 +00001083 NewTrunc,
Owen Anderson9c128342011-04-13 23:22:23 +00001084 Shift));
Chris Lattner86a14672006-05-06 00:11:52 +00001085 }
1086 break;
1087 }
1088 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001089
1090 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0f649322006-05-05 22:32:12 +00001091 break;
1092 }
Chris Lattner118ddba2006-02-26 23:36:02 +00001093 case ISD::AssertZext: {
Owen Anderson40d756e2011-09-03 00:26:49 +00001094 // AssertZext demands all of the high bits, plus any of the low bits
1095 // demanded by its users.
1096 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1097 APInt InMask = APInt::getLowBitsSet(BitWidth,
1098 VT.getSizeInBits());
1099 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001100 KnownZero, KnownOne, TLO, Depth+1))
1101 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001102 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmand83e3e72010-06-03 20:21:33 +00001103
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001104 KnownZero |= ~InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +00001105 break;
1106 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001107 case ISD::BITCAST:
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001108 // If this is an FP->Int bitcast and if the sign bit is the only
1109 // thing demanded, turn this into a FGETSIGN.
Eli Friedman2ec82492011-12-15 02:07:20 +00001110 if (!TLO.LegalOperations() &&
1111 !Op.getValueType().isVector() &&
Eli Friedman53218b62011-11-09 22:25:12 +00001112 !Op.getOperand(0).getValueType().isVector() &&
Nadav Rotem504cf0c2011-06-12 14:56:55 +00001113 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1114 Op.getOperand(0).getValueType().isFloatingPoint()) {
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001115 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1116 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
Chih-Hung Hsiehed7d81e2015-12-03 22:02:40 +00001117 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1118 Op.getOperand(0).getValueType() != MVT::f128) {
1119 // Cannot eliminate/lower SHL for f128 yet.
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001120 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
Chris Lattnerde272b12007-12-22 21:35:38 +00001121 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1122 // place. We expect the SHL to be eliminated by other optimizations.
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001123 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001124 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1125 if (!OpVTLegal && OpVTSizeInBits > 32)
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001126 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
Duncan Sands13237ac2008-06-06 12:08:01 +00001127 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001128 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
Stuart Hastings4a4e5a22011-05-19 18:48:20 +00001129 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1130 Op.getValueType(),
Chris Lattnerde272b12007-12-22 21:35:38 +00001131 Sign, ShAmt));
1132 }
1133 }
Chris Lattnerde272b12007-12-22 21:35:38 +00001134 break;
Dan Gohmanad3e5492009-04-08 00:15:30 +00001135 case ISD::ADD:
1136 case ISD::MUL:
1137 case ISD::SUB: {
1138 // Add, Sub, and Mul don't demand any bits in positions beyond that
1139 // of the highest bit demanded of them.
1140 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1141 BitWidth - NewMask.countLeadingZeros());
1142 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1143 KnownOne2, TLO, Depth+1))
1144 return true;
1145 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1146 KnownOne2, TLO, Depth+1))
1147 return true;
1148 // See if the operation should be performed at a smaller bit width.
Dan Gohman600f62b2010-06-24 14:30:44 +00001149 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +00001150 return true;
1151 }
1152 // FALL THROUGH
Dan Gohman38dc08f2008-05-06 00:53:29 +00001153 default:
Jay Foada0653a32014-05-14 21:14:37 +00001154 // Just use computeKnownBits to compute output bits.
1155 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Chris Lattnerab816402006-02-27 01:00:42 +00001156 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +00001157 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001158
Chris Lattner118ddba2006-02-26 23:36:02 +00001159 // If we know the value of all of the demanded bits, return this as a
1160 // constant.
Matthias Braun56a78142015-05-20 18:54:02 +00001161 if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1162 // Avoid folding to a constant if any OpaqueConstant is involved.
1163 const SDNode *N = Op.getNode();
1164 for (SDNodeIterator I = SDNodeIterator::begin(N),
1165 E = SDNodeIterator::end(N); I != E; ++I) {
1166 SDNode *Op = *I;
1167 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1168 if (C->isOpaque())
1169 return false;
1170 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001171 return TLO.CombineTo(Op,
1172 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
Matthias Braun56a78142015-05-20 18:54:02 +00001173 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001174
Nate Begeman8a77efe2006-02-16 21:11:51 +00001175 return false;
1176}
1177
Sanjay Patelac6e9102015-12-29 22:11:50 +00001178/// Determine which of the bits specified in Mask are known to be either zero or
1179/// one and return them in the KnownZero/KnownOne bitsets.
Jay Foada0653a32014-05-14 21:14:37 +00001180void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1181 APInt &KnownZero,
1182 APInt &KnownOne,
1183 const SelectionDAG &DAG,
1184 unsigned Depth) const {
Chris Lattner6c1321c2006-04-02 06:19:46 +00001185 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1186 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1187 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1188 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
Chris Lattnerf0b24d22006-01-30 04:09:27 +00001189 "Should use MaskedValueIsZero if you don't know whether Op"
1190 " is a target node!");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001191 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
Evan Cheng9cdc16c2005-12-21 23:05:39 +00001192}
Chris Lattner32fef532006-01-26 20:37:03 +00001193
Sanjay Patelac6e9102015-12-29 22:11:50 +00001194/// This method can be implemented by targets that want to expose additional
1195/// information about sign bits to the DAG Combiner.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001196unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
Matt Arsenaultcf6f6882014-04-04 20:13:13 +00001197 const SelectionDAG &,
Chris Lattner7206d742006-05-06 09:27:13 +00001198 unsigned Depth) const {
1199 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1200 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1201 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1202 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1203 "Should use ComputeNumSignBits if you don't know whether Op"
1204 " is a target node!");
1205 return 1;
1206}
1207
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001208bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1209 if (!N)
1210 return false;
1211
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001212 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001213 if (!CN) {
1214 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1215 if (!BV)
1216 return false;
1217
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001218 BitVector UndefElements;
1219 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001220 // Only interested in constant splats, and we don't try to handle undef
1221 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001222 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001223 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001224 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001225
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001226 switch (getBooleanContents(N->getValueType(0))) {
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001227 case UndefinedBooleanContent:
1228 return CN->getAPIntValue()[0];
1229 case ZeroOrOneBooleanContent:
1230 return CN->isOne();
1231 case ZeroOrNegativeOneBooleanContent:
1232 return CN->isAllOnesValue();
1233 }
1234
1235 llvm_unreachable("Invalid boolean contents");
1236}
1237
1238bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1239 if (!N)
1240 return false;
1241
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001242 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001243 if (!CN) {
1244 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1245 if (!BV)
1246 return false;
1247
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001248 BitVector UndefElements;
1249 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001250 // Only interested in constant splats, and we don't try to handle undef
1251 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001252 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001253 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001254 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001255
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001256 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001257 return !CN->getAPIntValue()[0];
1258
1259 return CN->isNullValue();
1260}
1261
Tom Stellardccdc5392016-01-18 19:55:21 +00001262bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1263 bool SExt) const {
1264 if (VT == MVT::i1)
1265 return N->isOne();
1266
1267 TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1268 switch (Cnt) {
1269 case TargetLowering::ZeroOrOneBooleanContent:
1270 // An extended value of 1 is always true, unless its original type is i1,
1271 // in which case it will be sign extended to -1.
1272 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1273 case TargetLowering::UndefinedBooleanContent:
1274 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1275 return N->isAllOnesValue() && SExt;
1276 }
Simon Pilgrimc4d519d2016-01-18 22:54:46 +00001277 llvm_unreachable("Unexpected enumeration.");
Tom Stellardccdc5392016-01-18 19:55:21 +00001278}
1279
Sanjay Patel91592562016-05-09 16:42:50 +00001280/// This helper function of SimplifySetCC tries to optimize the comparison when
1281/// either operand of the SetCC node is a bitwise-and instruction.
1282SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1283 ISD::CondCode Cond,
1284 DAGCombinerInfo &DCI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001285 const SDLoc &DL) const {
Sanjay Patelc2751e72016-05-07 15:03:40 +00001286 // Match these patterns in any of their permutations:
1287 // (X & Y) == Y
1288 // (X & Y) != Y
1289 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1290 std::swap(N0, N1);
1291
Sanjay Patel91592562016-05-09 16:42:50 +00001292 EVT OpVT = N0.getValueType();
1293 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
Sanjay Patelc2751e72016-05-07 15:03:40 +00001294 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1295 return SDValue();
1296
1297 SDValue X, Y;
1298 if (N0.getOperand(0) == N1) {
1299 X = N0.getOperand(1);
1300 Y = N0.getOperand(0);
1301 } else if (N0.getOperand(1) == N1) {
1302 X = N0.getOperand(0);
1303 Y = N0.getOperand(1);
1304 } else {
1305 return SDValue();
1306 }
1307
Sanjay Patel91592562016-05-09 16:42:50 +00001308 SelectionDAG &DAG = DCI.DAG;
1309 SDValue Zero = DAG.getConstant(0, DL, OpVT);
Sanjay Patelf39f42d2016-05-19 15:53:52 +00001310 if (DAG.isKnownToBeAPowerOfTwo(Y)) {
Sanjay Patel91592562016-05-09 16:42:50 +00001311 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1312 // Note that where Y is variable and is known to have at most one bit set
1313 // (for example, if it is Z & 1) we cannot do this; the expressions are not
1314 // equivalent when Y == 0.
1315 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1316 if (DCI.isBeforeLegalizeOps() ||
1317 isCondCodeLegal(Cond, N0.getSimpleValueType()))
1318 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1319 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1320 // If the target supports an 'and-not' or 'and-complement' logic operation,
1321 // try to use that to make a comparison operation more efficient.
1322 // But don't do this transform if the mask is a single bit because there are
1323 // more efficient ways to deal with that case (for example, 'bt' on x86 or
1324 // 'rlwinm' on PPC).
Sanjay Patelc2751e72016-05-07 15:03:40 +00001325
Sanjay Patel91592562016-05-09 16:42:50 +00001326 // Bail out if the compare operand that we want to turn into a zero is
1327 // already a zero (otherwise, infinite loop).
1328 auto *YConst = dyn_cast<ConstantSDNode>(Y);
1329 if (YConst && YConst->isNullValue())
1330 return SDValue();
Sanjay Patelc2751e72016-05-07 15:03:40 +00001331
Sanjay Patel91592562016-05-09 16:42:50 +00001332 // Transform this into: ~X & Y == 0.
1333 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1334 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1335 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1336 }
1337
1338 return SDValue();
Sanjay Patelc2751e72016-05-07 15:03:40 +00001339}
1340
Sanjay Patelac6e9102015-12-29 22:11:50 +00001341/// Try to simplify a setcc built with the specified operands and cc. If it is
1342/// unable to simplify it, return a null SDValue.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001343SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1344 ISD::CondCode Cond, bool foldBooleans,
1345 DAGCombinerInfo &DCI,
1346 const SDLoc &dl) const {
Evan Cheng92658d52007-02-08 22:13:59 +00001347 SelectionDAG &DAG = DCI.DAG;
1348
1349 // These setcc operations always fold.
1350 switch (Cond) {
1351 default: break;
1352 case ISD::SETFALSE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001353 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001354 case ISD::SETTRUE:
Tim Northover950fcc02013-09-06 12:38:12 +00001355 case ISD::SETTRUE2: {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001356 TargetLowering::BooleanContent Cnt =
1357 getBooleanContents(N0->getValueType(0));
Tim Northover950fcc02013-09-06 12:38:12 +00001358 return DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001359 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1360 VT);
Tim Northover950fcc02013-09-06 12:38:12 +00001361 }
Evan Cheng92658d52007-02-08 22:13:59 +00001362 }
1363
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001364 // Ensure that the constant occurs on the RHS, and fold constant
1365 // comparisons.
Tom Stellardcd428182013-09-28 02:50:38 +00001366 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1367 if (isa<ConstantSDNode>(N0.getNode()) &&
1368 (DCI.isBeforeLegalizeOps() ||
1369 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1370 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00001371
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001372 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
Dan Gohman2fa65b72008-03-03 22:22:56 +00001373 const APInt &C1 = N1C->getAPIntValue();
Dale Johannesen7aad5422008-11-07 01:28:02 +00001374
Eli Friedman65919b52009-07-26 23:47:17 +00001375 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1376 // equality comparison, then we're just comparing whether X itself is
1377 // zero.
1378 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1379 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1380 N0.getOperand(1).getOpcode() == ISD::Constant) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001381 const APInt &ShAmt
1382 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001383 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1384 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1385 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1386 // (srl (ctlz x), 5) == 0 -> X != 0
1387 // (srl (ctlz x), 5) != 1 -> X != 0
1388 Cond = ISD::SETNE;
1389 } else {
1390 // (srl (ctlz x), 5) != 0 -> X == 0
1391 // (srl (ctlz x), 5) == 1 -> X == 0
1392 Cond = ISD::SETEQ;
1393 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001394 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
Eli Friedman65919b52009-07-26 23:47:17 +00001395 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1396 Zero, Cond);
1397 }
1398 }
1399
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001400 SDValue CTPOP = N0;
1401 // Look through truncs that don't change the value of a ctpop.
1402 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1403 CTPOP = N0.getOperand(0);
1404
1405 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
Benjamin Kramer45d183c2011-01-17 18:00:28 +00001406 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001407 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1408 EVT CTVT = CTPOP.getValueType();
1409 SDValue CTOp = CTPOP.getOperand(0);
1410
1411 // (ctpop x) u< 2 -> (x & x-1) == 0
1412 // (ctpop x) u> 1 -> (x & x-1) != 0
1413 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1414 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001415 DAG.getConstant(1, dl, CTVT));
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001416 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1417 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001418 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001419 }
1420
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001421 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001422 }
1423
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001424 // (zext x) == C --> x == (trunc C)
Matt Arsenault22b4c252014-12-21 16:48:42 +00001425 // (sext x) == C --> x == (trunc C)
1426 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1427 DCI.isBeforeLegalize() && N0->hasOneUse()) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001428 unsigned MinBits = N0.getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001429 SDValue PreExt;
1430 bool Signed = false;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001431 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1432 // ZExt
1433 MinBits = N0->getOperand(0).getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001434 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001435 } else if (N0->getOpcode() == ISD::AND) {
1436 // DAGCombine turns costly ZExts into ANDs
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001437 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001438 if ((C->getAPIntValue()+1).isPowerOf2()) {
1439 MinBits = C->getAPIntValue().countTrailingOnes();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001440 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001441 }
Matt Arsenault22b4c252014-12-21 16:48:42 +00001442 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1443 // SExt
1444 MinBits = N0->getOperand(0).getValueSizeInBits();
1445 PreExt = N0->getOperand(0);
1446 Signed = true;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001447 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
Matt Arsenault22b4c252014-12-21 16:48:42 +00001448 // ZEXTLOAD / SEXTLOAD
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001449 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1450 MinBits = LN0->getMemoryVT().getSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001451 PreExt = N0;
1452 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1453 Signed = true;
1454 MinBits = LN0->getMemoryVT().getSizeInBits();
1455 PreExt = N0;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001456 }
1457 }
1458
Matt Arsenault22b4c252014-12-21 16:48:42 +00001459 // Figure out how many bits we need to preserve this constant.
1460 unsigned ReqdBits = Signed ?
1461 C1.getBitWidth() - C1.getNumSignBits() + 1 :
1462 C1.getActiveBits();
1463
Benjamin Kramerbde91762012-06-02 10:20:22 +00001464 // Make sure we're not losing bits from the constant.
Benjamin Kramer8aaf1972013-05-21 08:51:09 +00001465 if (MinBits > 0 &&
Matt Arsenault22b4c252014-12-21 16:48:42 +00001466 MinBits < C1.getBitWidth() &&
1467 MinBits >= ReqdBits) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001468 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1469 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1470 // Will get folded away.
Matt Arsenault22b4c252014-12-21 16:48:42 +00001471 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001472 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001473 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1474 }
Tom Stellardccdc5392016-01-18 19:55:21 +00001475
1476 // If truncating the setcc operands is not desirable, we can still
1477 // simplify the expression in some cases:
1478 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1479 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1480 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1481 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1482 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1483 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1484 SDValue TopSetCC = N0->getOperand(0);
1485 unsigned N0Opc = N0->getOpcode();
1486 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1487 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1488 TopSetCC.getOpcode() == ISD::SETCC &&
1489 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1490 (isConstFalseVal(N1C) ||
1491 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1492
1493 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1494 (!N1C->isNullValue() && Cond == ISD::SETNE);
1495
1496 if (!Inverse)
1497 return TopSetCC;
1498
1499 ISD::CondCode InvCond = ISD::getSetCCInverse(
1500 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1501 TopSetCC.getOperand(0).getValueType().isInteger());
1502 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1503 TopSetCC.getOperand(1),
1504 InvCond);
1505
1506 }
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001507 }
1508 }
1509
Eli Friedman65919b52009-07-26 23:47:17 +00001510 // If the LHS is '(and load, const)', the RHS is 0,
1511 // the test is for equality or unsigned, and all 1 bits of the const are
1512 // in the same partial word, see if we can shorten the load.
1513 if (DCI.isBeforeLegalize() &&
Eli Friedmana961d692013-09-24 22:50:14 +00001514 !ISD::isSignedIntSetCC(Cond) &&
Eli Friedman65919b52009-07-26 23:47:17 +00001515 N0.getOpcode() == ISD::AND && C1 == 0 &&
1516 N0.getNode()->hasOneUse() &&
1517 isa<LoadSDNode>(N0.getOperand(0)) &&
1518 N0.getOperand(0).getNode()->hasOneUse() &&
1519 isa<ConstantSDNode>(N0.getOperand(1))) {
1520 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
Evan Cheng16b75ce2010-01-07 20:58:44 +00001521 APInt bestMask;
Eli Friedman65919b52009-07-26 23:47:17 +00001522 unsigned bestWidth = 0, bestOffset = 0;
Evan Cheng16b75ce2010-01-07 20:58:44 +00001523 if (!Lod->isVolatile() && Lod->isUnindexed()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001524 unsigned origWidth = N0.getValueType().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001525 unsigned maskWidth = origWidth;
Wesley Peck527da1b2010-11-23 03:31:01 +00001526 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
Eli Friedman65919b52009-07-26 23:47:17 +00001527 // 8 bits, but have to be careful...
1528 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1529 origWidth = Lod->getMemoryVT().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001530 const APInt &Mask =
1531 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001532 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001533 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
Eli Friedman65919b52009-07-26 23:47:17 +00001534 for (unsigned offset=0; offset<origWidth/width; offset++) {
1535 if ((newMask & Mask) == Mask) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00001536 if (!DAG.getDataLayout().isLittleEndian())
Eli Friedman65919b52009-07-26 23:47:17 +00001537 bestOffset = (origWidth/width - offset - 1) * (width/8);
1538 else
1539 bestOffset = (uint64_t)offset * (width/8);
Evan Cheng16b75ce2010-01-07 20:58:44 +00001540 bestMask = Mask.lshr(offset * (width/8) * 8);
Eli Friedman65919b52009-07-26 23:47:17 +00001541 bestWidth = width;
1542 break;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001543 }
Eli Friedman65919b52009-07-26 23:47:17 +00001544 newMask = newMask << width;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001545 }
1546 }
1547 }
Eli Friedman65919b52009-07-26 23:47:17 +00001548 if (bestWidth) {
Chris Lattner493b3e72011-04-14 04:12:47 +00001549 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
Eli Friedman65919b52009-07-26 23:47:17 +00001550 if (newVT.isRound()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001551 EVT PtrType = Lod->getOperand(1).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001552 SDValue Ptr = Lod->getBasePtr();
1553 if (bestOffset != 0)
1554 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001555 DAG.getConstant(bestOffset, dl, PtrType));
Eli Friedman65919b52009-07-26 23:47:17 +00001556 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1557 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
Chris Lattner1ffcf522010-09-21 16:36:31 +00001558 Lod->getPointerInfo().getWithOffset(bestOffset),
Pete Cooper82cd9e82011-11-08 18:42:53 +00001559 false, false, false, NewAlign);
Wesley Peck527da1b2010-11-23 03:31:01 +00001560 return DAG.getSetCC(dl, VT,
Eli Friedman65919b52009-07-26 23:47:17 +00001561 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
Evan Cheng16b75ce2010-01-07 20:58:44 +00001562 DAG.getConstant(bestMask.trunc(bestWidth),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001563 dl, newVT)),
1564 DAG.getConstant(0LL, dl, newVT), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001565 }
Eli Friedman65919b52009-07-26 23:47:17 +00001566 }
1567 }
Evan Cheng92658d52007-02-08 22:13:59 +00001568
Eli Friedman65919b52009-07-26 23:47:17 +00001569 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1570 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1571 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1572
1573 // If the comparison constant has bits in the upper part, the
1574 // zero-extended value could never match.
1575 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1576 C1.getBitWidth() - InSize))) {
Evan Cheng92658d52007-02-08 22:13:59 +00001577 switch (Cond) {
Evan Cheng92658d52007-02-08 22:13:59 +00001578 case ISD::SETUGT:
1579 case ISD::SETUGE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001580 case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001581 case ISD::SETULT:
Eli Friedman65919b52009-07-26 23:47:17 +00001582 case ISD::SETULE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001583 case ISD::SETNE: return DAG.getConstant(1, dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001584 case ISD::SETGT:
1585 case ISD::SETGE:
1586 // True if the sign bit of C1 is set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001587 return DAG.getConstant(C1.isNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001588 case ISD::SETLT:
1589 case ISD::SETLE:
1590 // True if the sign bit of C1 isn't set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001591 return DAG.getConstant(C1.isNonNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001592 default:
Jakob Stoklund Olesen1ae07362009-07-24 18:22:59 +00001593 break;
1594 }
Eli Friedman65919b52009-07-26 23:47:17 +00001595 }
Evan Cheng92658d52007-02-08 22:13:59 +00001596
Eli Friedman65919b52009-07-26 23:47:17 +00001597 // Otherwise, we can perform the comparison with the low bits.
1598 switch (Cond) {
1599 case ISD::SETEQ:
1600 case ISD::SETNE:
1601 case ISD::SETUGT:
1602 case ISD::SETUGE:
1603 case ISD::SETULT:
1604 case ISD::SETULE: {
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001605 EVT newVT = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001606 if (DCI.isBeforeLegalizeOps() ||
1607 (isOperationLegal(ISD::SETCC, newVT) &&
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001608 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001609 EVT NewSetCCVT =
1610 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001611 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001612
1613 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1614 NewConst, Cond);
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001615 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001616 }
Eli Friedman65919b52009-07-26 23:47:17 +00001617 break;
1618 }
1619 default:
1620 break; // todo, be more careful with signed comparisons
1621 }
1622 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Evan Cheng228c31f2010-02-27 07:36:59 +00001623 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001624 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
Eli Friedman65919b52009-07-26 23:47:17 +00001625 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
Owen Anderson53aa7a92009-08-10 22:56:29 +00001626 EVT ExtDstTy = N0.getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001627 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1628
Eli Friedmanffe64c02010-07-30 06:44:31 +00001629 // If the constant doesn't fit into the number of bits for the source of
1630 // the sign extension, it is impossible for both sides to be equal.
1631 if (C1.getMinSignedBits() > ExtSrcTyBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001632 return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +00001633
Eli Friedman65919b52009-07-26 23:47:17 +00001634 SDValue ZextOp;
Owen Anderson53aa7a92009-08-10 22:56:29 +00001635 EVT Op0Ty = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001636 if (Op0Ty == ExtSrcTy) {
1637 ZextOp = N0.getOperand(0);
1638 } else {
1639 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1640 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001641 DAG.getConstant(Imm, dl, Op0Ty));
Eli Friedman65919b52009-07-26 23:47:17 +00001642 }
1643 if (!DCI.isCalledByLegalizer())
1644 DCI.AddToWorklist(ZextOp.getNode());
1645 // Otherwise, make this a use of a zext.
Wesley Peck527da1b2010-11-23 03:31:01 +00001646 return DAG.getSetCC(dl, VT, ZextOp,
Eli Friedman65919b52009-07-26 23:47:17 +00001647 DAG.getConstant(C1 & APInt::getLowBitsSet(
1648 ExtDstTyBits,
Wesley Peck527da1b2010-11-23 03:31:01 +00001649 ExtSrcTyBits),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001650 dl, ExtDstTy),
Eli Friedman65919b52009-07-26 23:47:17 +00001651 Cond);
1652 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1653 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Eli Friedman65919b52009-07-26 23:47:17 +00001654 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00001655 if (N0.getOpcode() == ISD::SETCC &&
1656 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001657 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
Eli Friedman65919b52009-07-26 23:47:17 +00001658 if (TrueWhenTrue)
Wesley Peck527da1b2010-11-23 03:31:01 +00001659 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
Eli Friedman65919b52009-07-26 23:47:17 +00001660 // Invert the condition.
1661 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Wesley Peck527da1b2010-11-23 03:31:01 +00001662 CC = ISD::getSetCCInverse(CC,
Eli Friedman65919b52009-07-26 23:47:17 +00001663 N0.getOperand(0).getValueType().isInteger());
Tom Stellardcd428182013-09-28 02:50:38 +00001664 if (DCI.isBeforeLegalizeOps() ||
1665 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1666 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
Evan Cheng92658d52007-02-08 22:13:59 +00001667 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001668
Eli Friedman65919b52009-07-26 23:47:17 +00001669 if ((N0.getOpcode() == ISD::XOR ||
Wesley Peck527da1b2010-11-23 03:31:01 +00001670 (N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001671 N0.getOperand(0).getOpcode() == ISD::XOR &&
1672 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1673 isa<ConstantSDNode>(N0.getOperand(1)) &&
1674 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1675 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1676 // can only do this if the top bits are known zero.
1677 unsigned BitWidth = N0.getValueSizeInBits();
1678 if (DAG.MaskedValueIsZero(N0,
1679 APInt::getHighBitsSet(BitWidth,
1680 BitWidth-1))) {
1681 // Okay, get the un-inverted input value.
1682 SDValue Val;
1683 if (N0.getOpcode() == ISD::XOR)
1684 Val = N0.getOperand(0);
1685 else {
Wesley Peck527da1b2010-11-23 03:31:01 +00001686 assert(N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001687 N0.getOperand(0).getOpcode() == ISD::XOR);
1688 // ((X^1)&1)^1 -> X & 1
1689 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1690 N0.getOperand(0).getOperand(0),
1691 N0.getOperand(1));
1692 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001693
Eli Friedman65919b52009-07-26 23:47:17 +00001694 return DAG.getSetCC(dl, VT, Val, N1,
1695 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1696 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001697 } else if (N1C->getAPIntValue() == 1 &&
1698 (VT == MVT::i1 ||
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001699 getBooleanContents(N0->getValueType(0)) ==
1700 ZeroOrOneBooleanContent)) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001701 SDValue Op0 = N0;
1702 if (Op0.getOpcode() == ISD::TRUNCATE)
1703 Op0 = Op0.getOperand(0);
1704
1705 if ((Op0.getOpcode() == ISD::XOR) &&
1706 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1707 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1708 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1709 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1710 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1711 Cond);
Craig Topper63f59212012-12-19 06:12:28 +00001712 }
1713 if (Op0.getOpcode() == ISD::AND &&
1714 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1715 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001716 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001717 if (Op0.getValueType().bitsGT(VT))
Evan Cheng228c31f2010-02-27 07:36:59 +00001718 Op0 = DAG.getNode(ISD::AND, dl, VT,
1719 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001720 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001721 else if (Op0.getValueType().bitsLT(VT))
1722 Op0 = DAG.getNode(ISD::AND, dl, VT,
1723 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001724 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001725
Evan Cheng228c31f2010-02-27 07:36:59 +00001726 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001727 DAG.getConstant(0, dl, Op0.getValueType()),
Evan Cheng228c31f2010-02-27 07:36:59 +00001728 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1729 }
Craig Topper63f59212012-12-19 06:12:28 +00001730 if (Op0.getOpcode() == ISD::AssertZext &&
1731 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1732 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001733 DAG.getConstant(0, dl, Op0.getValueType()),
Craig Topper63f59212012-12-19 06:12:28 +00001734 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001735 }
Eli Friedman65919b52009-07-26 23:47:17 +00001736 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001737
Eli Friedman65919b52009-07-26 23:47:17 +00001738 APInt MinVal, MaxVal;
1739 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1740 if (ISD::isSignedIntSetCC(Cond)) {
1741 MinVal = APInt::getSignedMinValue(OperandBitSize);
1742 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1743 } else {
1744 MinVal = APInt::getMinValue(OperandBitSize);
1745 MaxVal = APInt::getMaxValue(OperandBitSize);
1746 }
Evan Cheng92658d52007-02-08 22:13:59 +00001747
Eli Friedman65919b52009-07-26 23:47:17 +00001748 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1749 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001750 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001751 // X >= C0 --> X > (C0 - 1)
1752 APInt C = C1 - 1;
1753 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1754 if ((DCI.isBeforeLegalizeOps() ||
1755 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1756 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1757 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001758 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001759 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001760 NewCC);
1761 }
Eli Friedman65919b52009-07-26 23:47:17 +00001762 }
Evan Cheng92658d52007-02-08 22:13:59 +00001763
Eli Friedman65919b52009-07-26 23:47:17 +00001764 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001765 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001766 // X <= C0 --> X < (C0 + 1)
1767 APInt C = C1 + 1;
1768 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1769 if ((DCI.isBeforeLegalizeOps() ||
1770 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1771 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1772 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001773 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001774 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001775 NewCC);
1776 }
Eli Friedman65919b52009-07-26 23:47:17 +00001777 }
Evan Cheng92658d52007-02-08 22:13:59 +00001778
Eli Friedman65919b52009-07-26 23:47:17 +00001779 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001780 return DAG.getConstant(0, dl, VT); // X < MIN --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001781 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001782 return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Eli Friedman65919b52009-07-26 23:47:17 +00001783 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001784 return DAG.getConstant(0, dl, VT); // X > MAX --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001785 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001786 return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Evan Cheng92658d52007-02-08 22:13:59 +00001787
Eli Friedman65919b52009-07-26 23:47:17 +00001788 // Canonicalize setgt X, Min --> setne X, Min
1789 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1790 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1791 // Canonicalize setlt X, Max --> setne X, Max
1792 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1793 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
Evan Cheng92658d52007-02-08 22:13:59 +00001794
Eli Friedman65919b52009-07-26 23:47:17 +00001795 // If we have setult X, 1, turn it into seteq X, 0
1796 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001797 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001798 DAG.getConstant(MinVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001799 ISD::SETEQ);
1800 // If we have setugt X, Max-1, turn it into seteq X, Max
Craig Topper3f194c82012-12-19 06:43:58 +00001801 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001802 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001803 DAG.getConstant(MaxVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001804 ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001805
Eli Friedman65919b52009-07-26 23:47:17 +00001806 // If we have "setcc X, C0", check to see if we can shrink the immediate
1807 // by changing cc.
Evan Cheng92658d52007-02-08 22:13:59 +00001808
Eli Friedman65919b52009-07-26 23:47:17 +00001809 // SETUGT X, SINTMAX -> SETLT X, 0
Wesley Peck527da1b2010-11-23 03:31:01 +00001810 if (Cond == ISD::SETUGT &&
Eli Friedman65919b52009-07-26 23:47:17 +00001811 C1 == APInt::getSignedMaxValue(OperandBitSize))
Wesley Peck527da1b2010-11-23 03:31:01 +00001812 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001813 DAG.getConstant(0, dl, N1.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001814 ISD::SETLT);
Evan Cheng92658d52007-02-08 22:13:59 +00001815
Eli Friedman65919b52009-07-26 23:47:17 +00001816 // SETULT X, SINTMIN -> SETGT X, -1
1817 if (Cond == ISD::SETULT &&
1818 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1819 SDValue ConstMinusOne =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001820 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
Eli Friedman65919b52009-07-26 23:47:17 +00001821 N1.getValueType());
1822 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1823 }
Evan Cheng92658d52007-02-08 22:13:59 +00001824
Eli Friedman65919b52009-07-26 23:47:17 +00001825 // Fold bit comparisons when we can.
1826 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Evan Cheng166a4e62010-01-06 19:38:29 +00001827 (VT == N0.getValueType() ||
1828 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001829 N0.getOpcode() == ISD::AND) {
1830 auto &DL = DAG.getDataLayout();
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001831 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001832 EVT ShiftTy = DCI.isBeforeLegalize()
1833 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001834 : getShiftAmountTy(N0.getValueType(), DL);
Eli Friedman65919b52009-07-26 23:47:17 +00001835 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1836 // Perform the xform if the AND RHS is a single bit.
Evan Cheng16b75ce2010-01-07 20:58:44 +00001837 if (AndRHS->getAPIntValue().isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001838 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1839 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001840 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1841 ShiftTy)));
Eli Friedman65919b52009-07-26 23:47:17 +00001842 }
Evan Cheng16b75ce2010-01-07 20:58:44 +00001843 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001844 // (X & 8) == 8 --> (X & 8) >> 3
1845 // Perform the xform if C1 is a single bit.
1846 if (C1.isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001847 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1848 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001849 DAG.getConstant(C1.logBase2(), dl,
1850 ShiftTy)));
Evan Cheng92658d52007-02-08 22:13:59 +00001851 }
1852 }
Eli Friedman65919b52009-07-26 23:47:17 +00001853 }
Mehdi Amini44ede332015-07-09 02:09:04 +00001854 }
Evan Chengf579bec2012-07-17 06:53:39 +00001855
Evan Cheng47d7be92012-07-17 07:47:50 +00001856 if (C1.getMinSignedBits() <= 64 &&
1857 !isLegalICmpImmediate(C1.getSExtValue())) {
Evan Chengf579bec2012-07-17 06:53:39 +00001858 // (X & -256) == 256 -> (X >> 8) == 1
1859 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1860 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001861 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Chengf579bec2012-07-17 06:53:39 +00001862 const APInt &AndRHSC = AndRHS->getAPIntValue();
1863 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1864 unsigned ShiftBits = AndRHSC.countTrailingZeros();
Mehdi Amini44ede332015-07-09 02:09:04 +00001865 auto &DL = DAG.getDataLayout();
1866 EVT ShiftTy = DCI.isBeforeLegalize()
1867 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001868 : getShiftAmountTy(N0.getValueType(), DL);
Evan Chengf579bec2012-07-17 06:53:39 +00001869 EVT CmpTy = N0.getValueType();
1870 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001871 DAG.getConstant(ShiftBits, dl,
1872 ShiftTy));
1873 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
Evan Chengf579bec2012-07-17 06:53:39 +00001874 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1875 }
1876 }
Evan Cheng780f9b52012-07-17 08:31:11 +00001877 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1878 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1879 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1880 // X < 0x100000000 -> (X >> 32) < 1
1881 // X >= 0x100000000 -> (X >> 32) >= 1
1882 // X <= 0x0ffffffff -> (X >> 32) < 1
1883 // X > 0x0ffffffff -> (X >> 32) >= 1
1884 unsigned ShiftBits;
1885 APInt NewC = C1;
1886 ISD::CondCode NewCond = Cond;
1887 if (AdjOne) {
1888 ShiftBits = C1.countTrailingOnes();
1889 NewC = NewC + 1;
1890 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1891 } else {
1892 ShiftBits = C1.countTrailingZeros();
1893 }
1894 NewC = NewC.lshr(ShiftBits);
Pawel Bylica8011da92015-05-20 17:21:09 +00001895 if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
1896 isLegalICmpImmediate(NewC.getSExtValue())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001897 auto &DL = DAG.getDataLayout();
1898 EVT ShiftTy = DCI.isBeforeLegalize()
1899 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001900 : getShiftAmountTy(N0.getValueType(), DL);
Evan Cheng780f9b52012-07-17 08:31:11 +00001901 EVT CmpTy = N0.getValueType();
1902 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001903 DAG.getConstant(ShiftBits, dl, ShiftTy));
1904 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
Evan Cheng780f9b52012-07-17 08:31:11 +00001905 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1906 }
Evan Chengf579bec2012-07-17 06:53:39 +00001907 }
1908 }
Evan Cheng92658d52007-02-08 22:13:59 +00001909 }
1910
Gabor Greiff304a7a2008-08-28 21:40:38 +00001911 if (isa<ConstantFPSDNode>(N0.getNode())) {
Evan Cheng92658d52007-02-08 22:13:59 +00001912 // Constant fold or commute setcc.
Dale Johannesenf1163e92009-02-03 00:47:48 +00001913 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001914 if (O.getNode()) return O;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001915 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
Chris Lattner3b6a8212007-12-29 08:37:08 +00001916 // If the RHS of an FP comparison is a constant, simplify it away in
1917 // some cases.
1918 if (CFP->getValueAPF().isNaN()) {
1919 // If an operand is known to be a nan, we can fold it.
1920 switch (ISD::getUnorderedFlavor(Cond)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001921 default: llvm_unreachable("Unknown flavor!");
Chris Lattner3b6a8212007-12-29 08:37:08 +00001922 case 0: // Known false.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001923 return DAG.getConstant(0, dl, VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001924 case 1: // Known true.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001925 return DAG.getConstant(1, dl, VT);
Chris Lattner96317d22007-12-30 21:21:10 +00001926 case 2: // Undefined.
Dale Johannesen84935752009-02-06 23:05:02 +00001927 return DAG.getUNDEF(VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001928 }
1929 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001930
Chris Lattner3b6a8212007-12-29 08:37:08 +00001931 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1932 // constant if knowing that the operand is non-nan is enough. We prefer to
1933 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1934 // materialize 0.0.
1935 if (Cond == ISD::SETO || Cond == ISD::SETUO)
Dale Johannesenf1163e92009-02-03 00:47:48 +00001936 return DAG.getSetCC(dl, VT, N0, N0, Cond);
Dan Gohman832800a2009-09-26 15:24:17 +00001937
1938 // If the condition is not legal, see if we can find an equivalent one
1939 // which is legal.
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001940 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
Dan Gohman832800a2009-09-26 15:24:17 +00001941 // If the comparison was an awkward floating-point == or != and one of
1942 // the comparison operands is infinity or negative infinity, convert the
1943 // condition to a less-awkward <= or >=.
1944 if (CFP->getValueAPF().isInfinity()) {
1945 if (CFP->getValueAPF().isNegative()) {
1946 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001947 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001948 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1949 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001950 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001951 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1952 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001953 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001954 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1955 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001956 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001957 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1958 } else {
1959 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001960 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001961 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1962 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001963 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001964 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1965 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001966 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001967 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1968 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001969 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001970 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1971 }
1972 }
1973 }
Evan Cheng92658d52007-02-08 22:13:59 +00001974 }
1975
1976 if (N0 == N1) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00001977 // The sext(setcc()) => setcc() optimization relies on the appropriate
1978 // constant being emitted.
Nadav Rotema8e15b02012-09-06 11:13:55 +00001979 uint64_t EqVal = 0;
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001980 switch (getBooleanContents(N0.getValueType())) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00001981 case UndefinedBooleanContent:
1982 case ZeroOrOneBooleanContent:
1983 EqVal = ISD::isTrueWhenEqual(Cond);
1984 break;
1985 case ZeroOrNegativeOneBooleanContent:
1986 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1987 break;
1988 }
1989
Evan Cheng92658d52007-02-08 22:13:59 +00001990 // We can always fold X == X for integer setcc's.
Chad Rosier2a02fe12012-04-03 20:11:24 +00001991 if (N0.getValueType().isInteger()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001992 return DAG.getConstant(EqVal, dl, VT);
Chad Rosier2a02fe12012-04-03 20:11:24 +00001993 }
Evan Cheng92658d52007-02-08 22:13:59 +00001994 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1995 if (UOF == 2) // FP operators that are undefined on NaNs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001996 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001997 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001998 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001999 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2000 // if it is not already.
2001 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
Micah Villmowb67d7a32012-07-31 18:07:43 +00002002 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
Patrik Hagglunddeee9002012-12-19 10:09:26 +00002003 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002004 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
Evan Cheng92658d52007-02-08 22:13:59 +00002005 }
2006
2007 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002008 N0.getValueType().isInteger()) {
Evan Cheng92658d52007-02-08 22:13:59 +00002009 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2010 N0.getOpcode() == ISD::XOR) {
2011 // Simplify (X+Y) == (X+Z) --> Y == Z
2012 if (N0.getOpcode() == N1.getOpcode()) {
2013 if (N0.getOperand(0) == N1.getOperand(0))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002014 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002015 if (N0.getOperand(1) == N1.getOperand(1))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002016 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002017 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2018 // If X op Y == Y op X, try other combinations.
2019 if (N0.getOperand(0) == N1.getOperand(1))
Wesley Peck527da1b2010-11-23 03:31:01 +00002020 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
Dale Johannesenf1163e92009-02-03 00:47:48 +00002021 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002022 if (N0.getOperand(1) == N1.getOperand(0))
Wesley Peck527da1b2010-11-23 03:31:01 +00002023 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00002024 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002025 }
2026 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002027
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002028 // If RHS is a legal immediate value for a compare instruction, we need
2029 // to be careful about increasing register pressure needlessly.
2030 bool LegalRHSImm = false;
2031
Sanjay Patel7a7abc92015-12-29 21:49:08 +00002032 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2033 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Cheng92658d52007-02-08 22:13:59 +00002034 // Turn (X+C1) == C2 --> X == C2-C1
Gabor Greiff304a7a2008-08-28 21:40:38 +00002035 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002036 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohmaneffb8942008-09-12 16:56:44 +00002037 DAG.getConstant(RHSC->getAPIntValue()-
2038 LHSR->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002039 dl, N0.getValueType()), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002040 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002041
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002042 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
Evan Cheng92658d52007-02-08 22:13:59 +00002043 if (N0.getOpcode() == ISD::XOR)
2044 // If we know that all of the inverted bits are zero, don't bother
2045 // performing the inversion.
Dan Gohman1f372ed2008-02-25 21:11:39 +00002046 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2047 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00002048 DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002049 DAG.getConstant(LHSR->getAPIntValue() ^
2050 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002051 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002052 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002053 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002054
Evan Cheng92658d52007-02-08 22:13:59 +00002055 // Turn (C1-X) == C2 --> X == C1-C2
Sanjay Patel7a7abc92015-12-29 21:49:08 +00002056 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00002057 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002058 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00002059 DAG.getSetCC(dl, VT, N0.getOperand(1),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002060 DAG.getConstant(SUBC->getAPIntValue() -
2061 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002062 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002063 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002064 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002065 }
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002066
2067 // Could RHSC fold directly into a compare?
2068 if (RHSC->getValueType(0).getSizeInBits() <= 64)
2069 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
Evan Cheng92658d52007-02-08 22:13:59 +00002070 }
2071
2072 // Simplify (X+Z) == X --> Z == 0
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002073 // Don't do this if X is an immediate that can fold into a cmp
2074 // instruction and X+Z has other uses. It could be an induction variable
2075 // chain, and the transform would increase register pressure.
2076 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2077 if (N0.getOperand(0) == N1)
2078 return DAG.getSetCC(dl, VT, N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002079 DAG.getConstant(0, dl, N0.getValueType()), Cond);
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002080 if (N0.getOperand(1) == N1) {
2081 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2082 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002083 DAG.getConstant(0, dl, N0.getValueType()),
2084 Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002085 if (N0.getNode()->hasOneUse()) {
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002086 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002087 auto &DL = DAG.getDataLayout();
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002088 // (Z-X) == X --> Z == X<<1
Mehdi Amini9639d652015-07-09 02:09:20 +00002089 SDValue SH = DAG.getNode(
2090 ISD::SHL, dl, N1.getValueType(), N1,
2091 DAG.getConstant(1, dl,
2092 getShiftAmountTy(N1.getValueType(), DL)));
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002093 if (!DCI.isCalledByLegalizer())
2094 DCI.AddToWorklist(SH.getNode());
2095 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2096 }
Evan Cheng92658d52007-02-08 22:13:59 +00002097 }
2098 }
2099 }
2100
2101 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2102 N1.getOpcode() == ISD::XOR) {
2103 // Simplify X == (X+Z) --> Z == 0
Craig Topper3f194c82012-12-19 06:43:58 +00002104 if (N1.getOperand(0) == N0)
Dale Johannesenf1163e92009-02-03 00:47:48 +00002105 return DAG.getSetCC(dl, VT, N1.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002106 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002107 if (N1.getOperand(1) == N0) {
2108 if (DAG.isCommutativeBinOp(N1.getOpcode()))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002109 return DAG.getSetCC(dl, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002110 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002111 if (N1.getNode()->hasOneUse()) {
Evan Cheng92658d52007-02-08 22:13:59 +00002112 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002113 auto &DL = DAG.getDataLayout();
Evan Cheng92658d52007-02-08 22:13:59 +00002114 // X == (Z-X) --> X<<1 == Z
Mehdi Amini9639d652015-07-09 02:09:20 +00002115 SDValue SH = DAG.getNode(
2116 ISD::SHL, dl, N1.getValueType(), N0,
2117 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
Evan Cheng92658d52007-02-08 22:13:59 +00002118 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002119 DCI.AddToWorklist(SH.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002120 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002121 }
2122 }
2123 }
Dan Gohmane58ab792009-01-29 01:59:02 +00002124
Sanjay Patel91592562016-05-09 16:42:50 +00002125 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2126 return V;
Evan Cheng92658d52007-02-08 22:13:59 +00002127 }
2128
2129 // Fold away ALL boolean setcc's.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002130 SDValue Temp;
Owen Anderson9f944592009-08-11 20:47:22 +00002131 if (N0.getValueType() == MVT::i1 && foldBooleans) {
Evan Cheng92658d52007-02-08 22:13:59 +00002132 switch (Cond) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00002133 default: llvm_unreachable("Unknown integer setcc!");
Bob Wilsonc5890052009-01-22 17:39:32 +00002134 case ISD::SETEQ: // X == Y -> ~(X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002135 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2136 N0 = DAG.getNOT(dl, Temp, MVT::i1);
Evan Cheng92658d52007-02-08 22:13:59 +00002137 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002138 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002139 break;
2140 case ISD::SETNE: // X != Y --> (X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002141 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
Evan Cheng92658d52007-02-08 22:13:59 +00002142 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002143 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2144 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
Owen Anderson9f944592009-08-11 20:47:22 +00002145 Temp = DAG.getNOT(dl, N0, MVT::i1);
2146 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002147 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002148 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002149 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002150 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2151 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
Owen Anderson9f944592009-08-11 20:47:22 +00002152 Temp = DAG.getNOT(dl, N1, MVT::i1);
2153 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002154 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002155 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002156 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002157 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2158 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
Owen Anderson9f944592009-08-11 20:47:22 +00002159 Temp = DAG.getNOT(dl, N0, MVT::i1);
2160 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002161 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002162 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002163 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002164 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2165 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
Owen Anderson9f944592009-08-11 20:47:22 +00002166 Temp = DAG.getNOT(dl, N1, MVT::i1);
2167 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002168 break;
2169 }
Owen Anderson9f944592009-08-11 20:47:22 +00002170 if (VT != MVT::i1) {
Evan Cheng92658d52007-02-08 22:13:59 +00002171 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002172 DCI.AddToWorklist(N0.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002173 // FIXME: If running after legalize, we probably can't do this.
Dale Johannesenf1163e92009-02-03 00:47:48 +00002174 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
Evan Cheng92658d52007-02-08 22:13:59 +00002175 }
2176 return N0;
2177 }
2178
2179 // Could not fold it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002180 return SDValue();
Evan Cheng92658d52007-02-08 22:13:59 +00002181}
2182
Sanjay Patelac6e9102015-12-29 22:11:50 +00002183/// Returns true (and the GlobalValue and the offset) if the node is a
2184/// GlobalAddress + offset.
Chris Lattner46c01a32011-02-13 22:25:43 +00002185bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
Evan Cheng2609d5e2008-05-12 19:56:52 +00002186 int64_t &Offset) const {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002187 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
Dan Gohmane38cc012008-06-09 22:05:52 +00002188 GA = GASD->getGlobal();
2189 Offset += GASD->getOffset();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002190 return true;
2191 }
2192
2193 if (N->getOpcode() == ISD::ADD) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002194 SDValue N1 = N->getOperand(0);
2195 SDValue N2 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002196 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002197 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002198 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002199 return true;
2200 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00002201 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002202 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002203 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002204 return true;
2205 }
2206 }
2207 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002208
Evan Cheng2609d5e2008-05-12 19:56:52 +00002209 return false;
2210}
2211
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002212SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2213 DAGCombinerInfo &DCI) const {
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002214 // Default implementation: no optimization.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002215 return SDValue();
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002216}
2217
Chris Lattneree1dadb2006-02-04 02:13:02 +00002218//===----------------------------------------------------------------------===//
2219// Inline Assembler Implementation Methods
2220//===----------------------------------------------------------------------===//
2221
2222TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002223TargetLowering::getConstraintType(StringRef Constraint) const {
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002224 unsigned S = Constraint.size();
2225
2226 if (S == 1) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002227 switch (Constraint[0]) {
2228 default: break;
2229 case 'r': return C_RegisterClass;
2230 case 'm': // memory
2231 case 'o': // offsetable
2232 case 'V': // not offsetable
2233 return C_Memory;
2234 case 'i': // Simple Integer or Relocatable Constant
2235 case 'n': // Simple Integer
John Thompsonc467aa22010-09-21 22:04:54 +00002236 case 'E': // Floating Point Constant
2237 case 'F': // Floating Point Constant
Chris Lattnerd6855142007-03-25 02:14:49 +00002238 case 's': // Relocatable Constant
John Thompsonc467aa22010-09-21 22:04:54 +00002239 case 'p': // Address.
Chris Lattner3d7efa22007-03-25 04:35:41 +00002240 case 'X': // Allow ANY value.
Chris Lattnerd6855142007-03-25 02:14:49 +00002241 case 'I': // Target registers.
2242 case 'J':
2243 case 'K':
2244 case 'L':
2245 case 'M':
2246 case 'N':
2247 case 'O':
2248 case 'P':
John Thompsonc467aa22010-09-21 22:04:54 +00002249 case '<':
2250 case '>':
Chris Lattnerd6855142007-03-25 02:14:49 +00002251 return C_Other;
2252 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002253 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002254
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002255 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002256 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002257 return C_Memory;
Chris Lattner843e4452007-03-25 02:18:14 +00002258 return C_Register;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002259 }
Chris Lattnerd6855142007-03-25 02:14:49 +00002260 return C_Unknown;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002261}
2262
Sanjay Patelac6e9102015-12-29 22:11:50 +00002263/// Try to replace an X constraint, which matches anything, with another that
2264/// has more specific requirements based on the type of the corresponding
2265/// operand.
Owen Anderson53aa7a92009-08-10 22:56:29 +00002266const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
Duncan Sands13237ac2008-06-06 12:08:01 +00002267 if (ConstraintVT.isInteger())
Chris Lattner724539c2008-04-26 23:02:14 +00002268 return "r";
Duncan Sands13237ac2008-06-06 12:08:01 +00002269 if (ConstraintVT.isFloatingPoint())
Chris Lattner724539c2008-04-26 23:02:14 +00002270 return "f"; // works for many targets
Craig Topperc0196b12014-04-14 00:51:57 +00002271 return nullptr;
Dale Johannesen2b3bc302008-01-29 02:21:21 +00002272}
2273
Sanjay Patelac6e9102015-12-29 22:11:50 +00002274/// Lower the specified operand into the Ops vector.
2275/// If it is invalid, don't add anything to Ops.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002276void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
Eric Christopherde9399b2011-06-02 23:16:42 +00002277 std::string &Constraint,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002278 std::vector<SDValue> &Ops,
Chris Lattner724539c2008-04-26 23:02:14 +00002279 SelectionDAG &DAG) const {
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002280
Eric Christopherde9399b2011-06-02 23:16:42 +00002281 if (Constraint.length() > 1) return;
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002282
Eric Christopherde9399b2011-06-02 23:16:42 +00002283 char ConstraintLetter = Constraint[0];
Chris Lattneree1dadb2006-02-04 02:13:02 +00002284 switch (ConstraintLetter) {
Chris Lattnera9f917a2007-02-17 06:00:35 +00002285 default: break;
Dale Johannesen4646aa32007-11-05 21:20:28 +00002286 case 'X': // Allows any operand; labels (basic block) use this.
2287 if (Op.getOpcode() == ISD::BasicBlock) {
2288 Ops.push_back(Op);
2289 return;
2290 }
2291 // fall through
Chris Lattneree1dadb2006-02-04 02:13:02 +00002292 case 'i': // Simple Integer or Relocatable Constant
2293 case 'n': // Simple Integer
Dale Johannesen4646aa32007-11-05 21:20:28 +00002294 case 's': { // Relocatable Constant
Chris Lattner44a2ed62007-05-03 16:54:34 +00002295 // These operands are interested in values of the form (GV+C), where C may
2296 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2297 // is possible and fine if either GV or C are missing.
2298 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2299 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
Wesley Peck527da1b2010-11-23 03:31:01 +00002300
Chris Lattner44a2ed62007-05-03 16:54:34 +00002301 // If we have "(add GV, C)", pull out GV/C
2302 if (Op.getOpcode() == ISD::ADD) {
2303 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2304 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
Craig Topperc0196b12014-04-14 00:51:57 +00002305 if (!C || !GA) {
Chris Lattner44a2ed62007-05-03 16:54:34 +00002306 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2307 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2308 }
Richard Trieu7a083812016-02-18 22:09:30 +00002309 if (!C || !GA) {
2310 C = nullptr;
2311 GA = nullptr;
2312 }
Chris Lattner44a2ed62007-05-03 16:54:34 +00002313 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002314
Chris Lattner44a2ed62007-05-03 16:54:34 +00002315 // If we find a valid operand, map to the TargetXXX version so that the
2316 // value itself doesn't get selected.
2317 if (GA) { // Either &GV or &GV+C
2318 if (ConstraintLetter != 'n') {
2319 int64_t Offs = GA->getOffset();
Dan Gohmaneffb8942008-09-12 16:56:44 +00002320 if (C) Offs += C->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002321 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002322 C ? SDLoc(C) : SDLoc(),
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002323 Op.getValueType(), Offs));
Chris Lattner44a2ed62007-05-03 16:54:34 +00002324 }
James Y Knight46f91c82015-07-13 16:36:22 +00002325 return;
Chris Lattner44a2ed62007-05-03 16:54:34 +00002326 }
2327 if (C) { // just C, no GV.
Chris Lattnera9f917a2007-02-17 06:00:35 +00002328 // Simple constants are not allowed for 's'.
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002329 if (ConstraintLetter != 's') {
Dale Johannesen65577522009-02-12 20:58:09 +00002330 // gcc prints these as sign extended. Sign extend value to 64 bits
2331 // now; without this it would get ZExt'd later in
2332 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2333 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002334 SDLoc(C), MVT::i64));
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002335 }
James Y Knight46f91c82015-07-13 16:36:22 +00002336 return;
Chris Lattnera9f917a2007-02-17 06:00:35 +00002337 }
Chris Lattnera9f917a2007-02-17 06:00:35 +00002338 break;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002339 }
Chris Lattner44a2ed62007-05-03 16:54:34 +00002340 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002341}
2342
Eric Christopher11e4df72015-02-26 22:38:43 +00002343std::pair<unsigned, const TargetRegisterClass *>
2344TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002345 StringRef Constraint,
Eric Christopher11e4df72015-02-26 22:38:43 +00002346 MVT VT) const {
Will Dietzae726a92013-10-13 03:08:49 +00002347 if (Constraint.empty() || Constraint[0] != '{')
Craig Topperc0196b12014-04-14 00:51:57 +00002348 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
Chris Lattner7ed31012006-02-01 01:29:47 +00002349 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2350
2351 // Remove the braces from around the name.
Benjamin Kramer68e49452009-11-12 20:36:59 +00002352 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002353
Hal Finkel943f76d2012-12-18 17:50:58 +00002354 std::pair<unsigned, const TargetRegisterClass*> R =
Craig Topperc0196b12014-04-14 00:51:57 +00002355 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
Hal Finkel943f76d2012-12-18 17:50:58 +00002356
Chris Lattner7ad77df2006-02-22 00:56:39 +00002357 // Figure out which register class contains this reg.
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002358 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
Chris Lattner7ad77df2006-02-22 00:56:39 +00002359 E = RI->regclass_end(); RCI != E; ++RCI) {
2360 const TargetRegisterClass *RC = *RCI;
Wesley Peck527da1b2010-11-23 03:31:01 +00002361
2362 // If none of the value types for this register class are valid, we
Chris Lattner2e124af2006-02-22 23:00:51 +00002363 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Jakob Stoklund Olesen35163e22011-10-12 01:24:51 +00002364 if (!isLegalRC(RC))
2365 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002366
2367 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002368 I != E; ++I) {
Tom Stellard52686e42016-04-11 16:21:12 +00002369 if (RegName.equals_lower(RI->getRegAsmName(*I))) {
Hal Finkel943f76d2012-12-18 17:50:58 +00002370 std::pair<unsigned, const TargetRegisterClass*> S =
2371 std::make_pair(*I, RC);
2372
2373 // If this register class has the requested value type, return it,
2374 // otherwise keep searching and return the first class found
2375 // if no other is found which explicitly has the requested type.
2376 if (RC->hasType(VT))
2377 return S;
2378 else if (!R.second)
2379 R = S;
2380 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002381 }
Chris Lattner32fef532006-01-26 20:37:03 +00002382 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002383
Hal Finkel943f76d2012-12-18 17:50:58 +00002384 return R;
Chris Lattner32fef532006-01-26 20:37:03 +00002385}
Evan Chengaf598d22006-03-13 23:18:16 +00002386
2387//===----------------------------------------------------------------------===//
Chris Lattner47935152008-04-27 00:09:47 +00002388// Constraint Selection.
2389
Sanjay Patelac6e9102015-12-29 22:11:50 +00002390/// Return true of this is an input operand that is a matching constraint like
2391/// "4".
Chris Lattner860df6e2008-10-17 16:47:46 +00002392bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
Chris Lattneref890172008-10-17 16:21:11 +00002393 assert(!ConstraintCode.empty() && "No known constraint!");
Guy Benyei83c74e92013-02-12 21:21:59 +00002394 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
Chris Lattneref890172008-10-17 16:21:11 +00002395}
2396
Sanjay Patelac6e9102015-12-29 22:11:50 +00002397/// If this is an input matching constraint, this method returns the output
2398/// operand it matches.
Chris Lattneref890172008-10-17 16:21:11 +00002399unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2400 assert(!ConstraintCode.empty() && "No known constraint!");
2401 return atoi(ConstraintCode.c_str());
2402}
2403
Sanjay Patelac6e9102015-12-29 22:11:50 +00002404/// Split up the constraint string from the inline assembly value into the
2405/// specific constraints and their prefixes, and also tie in the associated
2406/// operand values.
John Thompson1094c802010-09-13 18:15:37 +00002407/// If this returns an empty vector, and if the constraint string itself
2408/// isn't empty, there was an error parsing.
Eric Christopher11e4df72015-02-26 22:38:43 +00002409TargetLowering::AsmOperandInfoVector
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002410TargetLowering::ParseConstraints(const DataLayout &DL,
2411 const TargetRegisterInfo *TRI,
Eric Christopher11e4df72015-02-26 22:38:43 +00002412 ImmutableCallSite CS) const {
Sanjay Patelac6e9102015-12-29 22:11:50 +00002413 /// Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00002414 AsmOperandInfoVector ConstraintOperands;
John Thompson1094c802010-09-13 18:15:37 +00002415 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
John Thompsonc467aa22010-09-21 22:04:54 +00002416 unsigned maCount = 0; // Largest number of multiple alternative constraints.
John Thompson1094c802010-09-13 18:15:37 +00002417
2418 // Do a prepass over the constraints, canonicalizing them, and building up the
2419 // ConstraintOperands list.
John Thompson1094c802010-09-13 18:15:37 +00002420 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2421 unsigned ResNo = 0; // ResNo - The result number of the next output.
2422
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00002423 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2424 ConstraintOperands.emplace_back(std::move(CI));
John Thompson1094c802010-09-13 18:15:37 +00002425 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2426
John Thompsonc467aa22010-09-21 22:04:54 +00002427 // Update multiple alternative constraint count.
2428 if (OpInfo.multipleAlternatives.size() > maCount)
2429 maCount = OpInfo.multipleAlternatives.size();
2430
John Thompsone8360b72010-10-29 17:29:13 +00002431 OpInfo.ConstraintVT = MVT::Other;
John Thompson1094c802010-09-13 18:15:37 +00002432
2433 // Compute the value type for each operand.
2434 switch (OpInfo.Type) {
2435 case InlineAsm::isOutput:
2436 // Indirect outputs just consume an argument.
2437 if (OpInfo.isIndirect) {
2438 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2439 break;
2440 }
2441
2442 // The return value of the call is this value. As such, there is no
2443 // corresponding argument.
2444 assert(!CS.getType()->isVoidTy() &&
2445 "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00002446 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002447 OpInfo.ConstraintVT =
2448 getSimpleValueType(DL, STy->getElementType(ResNo));
John Thompson1094c802010-09-13 18:15:37 +00002449 } else {
2450 assert(ResNo == 0 && "Asm only has one result!");
Mehdi Amini44ede332015-07-09 02:09:04 +00002451 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
John Thompson1094c802010-09-13 18:15:37 +00002452 }
2453 ++ResNo;
2454 break;
2455 case InlineAsm::isInput:
2456 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2457 break;
2458 case InlineAsm::isClobber:
2459 // Nothing to do.
2460 break;
2461 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002462
John Thompsone8360b72010-10-29 17:29:13 +00002463 if (OpInfo.CallOperandVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00002464 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
John Thompsone8360b72010-10-29 17:29:13 +00002465 if (OpInfo.isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00002466 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002467 if (!PtrTy)
2468 report_fatal_error("Indirect operand for inline asm not a pointer!");
2469 OpTy = PtrTy->getElementType();
2470 }
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002471
Eric Christopher44804282011-05-09 20:04:43 +00002472 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00002473 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00002474 if (STy->getNumElements() == 1)
2475 OpTy = STy->getElementType(0);
2476
John Thompsone8360b72010-10-29 17:29:13 +00002477 // If OpTy is not a single value, it may be a struct/union that we
2478 // can tile with integers.
2479 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002480 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002481 switch (BitSize) {
2482 default: break;
2483 case 1:
2484 case 8:
2485 case 16:
2486 case 32:
2487 case 64:
2488 case 128:
Dale Johannesenf11ea9c2010-11-09 01:15:07 +00002489 OpInfo.ConstraintVT =
Patrik Hagglundf9934612012-12-19 15:19:11 +00002490 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
John Thompsone8360b72010-10-29 17:29:13 +00002491 break;
2492 }
Micah Villmow89021e42012-10-09 16:06:12 +00002493 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002494 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
Matt Arsenaulta98c3b12013-10-10 19:09:05 +00002495 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
John Thompsone8360b72010-10-29 17:29:13 +00002496 } else {
Patrik Hagglundf9934612012-12-19 15:19:11 +00002497 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
John Thompsone8360b72010-10-29 17:29:13 +00002498 }
2499 }
John Thompson1094c802010-09-13 18:15:37 +00002500 }
2501
2502 // If we have multiple alternative constraints, select the best alternative.
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002503 if (!ConstraintOperands.empty()) {
John Thompson1094c802010-09-13 18:15:37 +00002504 if (maCount) {
2505 unsigned bestMAIndex = 0;
2506 int bestWeight = -1;
2507 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2508 int weight = -1;
2509 unsigned maIndex;
2510 // Compute the sums of the weights for each alternative, keeping track
2511 // of the best (highest weight) one so far.
2512 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2513 int weightSum = 0;
2514 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2515 cIndex != eIndex; ++cIndex) {
2516 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2517 if (OpInfo.Type == InlineAsm::isClobber)
2518 continue;
John Thompson1094c802010-09-13 18:15:37 +00002519
John Thompsone8360b72010-10-29 17:29:13 +00002520 // If this is an output operand with a matching input operand,
2521 // look up the matching input. If their types mismatch, e.g. one
2522 // is an integer, the other is floating point, or their sizes are
2523 // different, flag it as an maCantMatch.
John Thompson1094c802010-09-13 18:15:37 +00002524 if (OpInfo.hasMatchingInput()) {
2525 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompson1094c802010-09-13 18:15:37 +00002526 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2527 if ((OpInfo.ConstraintVT.isInteger() !=
2528 Input.ConstraintVT.isInteger()) ||
2529 (OpInfo.ConstraintVT.getSizeInBits() !=
2530 Input.ConstraintVT.getSizeInBits())) {
2531 weightSum = -1; // Can't match.
2532 break;
2533 }
John Thompson1094c802010-09-13 18:15:37 +00002534 }
2535 }
John Thompson1094c802010-09-13 18:15:37 +00002536 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2537 if (weight == -1) {
2538 weightSum = -1;
2539 break;
2540 }
2541 weightSum += weight;
2542 }
2543 // Update best.
2544 if (weightSum > bestWeight) {
2545 bestWeight = weightSum;
2546 bestMAIndex = maIndex;
2547 }
2548 }
2549
2550 // Now select chosen alternative in each constraint.
2551 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2552 cIndex != eIndex; ++cIndex) {
2553 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2554 if (cInfo.Type == InlineAsm::isClobber)
2555 continue;
2556 cInfo.selectAlternative(bestMAIndex);
2557 }
2558 }
2559 }
2560
2561 // Check and hook up tied operands, choose constraint code to use.
2562 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2563 cIndex != eIndex; ++cIndex) {
2564 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
Wesley Peck527da1b2010-11-23 03:31:01 +00002565
John Thompson1094c802010-09-13 18:15:37 +00002566 // If this is an output operand with a matching input operand, look up the
2567 // matching input. If their types mismatch, e.g. one is an integer, the
2568 // other is floating point, or their sizes are different, flag it as an
2569 // error.
2570 if (OpInfo.hasMatchingInput()) {
2571 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompsone8360b72010-10-29 17:29:13 +00002572
John Thompson1094c802010-09-13 18:15:37 +00002573 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Eric Christopher11e4df72015-02-26 22:38:43 +00002574 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2575 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2576 OpInfo.ConstraintVT);
2577 std::pair<unsigned, const TargetRegisterClass *> InputRC =
2578 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2579 Input.ConstraintVT);
John Thompson1094c802010-09-13 18:15:37 +00002580 if ((OpInfo.ConstraintVT.isInteger() !=
2581 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00002582 (MatchRC.second != InputRC.second)) {
John Thompson1094c802010-09-13 18:15:37 +00002583 report_fatal_error("Unsupported asm: input constraint"
2584 " with a matching output constraint of"
2585 " incompatible type!");
2586 }
John Thompson1094c802010-09-13 18:15:37 +00002587 }
2588 }
2589 }
2590
2591 return ConstraintOperands;
2592}
2593
Sanjay Patelac6e9102015-12-29 22:11:50 +00002594/// Return an integer indicating how general CT is.
Chris Lattner47935152008-04-27 00:09:47 +00002595static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2596 switch (CT) {
Chris Lattner47935152008-04-27 00:09:47 +00002597 case TargetLowering::C_Other:
2598 case TargetLowering::C_Unknown:
2599 return 0;
2600 case TargetLowering::C_Register:
2601 return 1;
2602 case TargetLowering::C_RegisterClass:
2603 return 2;
2604 case TargetLowering::C_Memory:
2605 return 3;
2606 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002607 llvm_unreachable("Invalid constraint type");
Chris Lattner47935152008-04-27 00:09:47 +00002608}
2609
John Thompsone8360b72010-10-29 17:29:13 +00002610/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002611/// This object must already have been set up with the operand type
2612/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002613TargetLowering::ConstraintWeight
2614 TargetLowering::getMultipleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002615 AsmOperandInfo &info, int maIndex) const {
John Thompsone8360b72010-10-29 17:29:13 +00002616 InlineAsm::ConstraintCodeVector *rCodes;
John Thompsonc467aa22010-09-21 22:04:54 +00002617 if (maIndex >= (int)info.multipleAlternatives.size())
2618 rCodes = &info.Codes;
2619 else
2620 rCodes = &info.multipleAlternatives[maIndex].Codes;
John Thompsone8360b72010-10-29 17:29:13 +00002621 ConstraintWeight BestWeight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002622
2623 // Loop over the options, keeping track of the most general one.
John Thompsonc467aa22010-09-21 22:04:54 +00002624 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
John Thompsone8360b72010-10-29 17:29:13 +00002625 ConstraintWeight weight =
2626 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
John Thompson1094c802010-09-13 18:15:37 +00002627 if (weight > BestWeight)
2628 BestWeight = weight;
2629 }
2630
2631 return BestWeight;
2632}
2633
John Thompsone8360b72010-10-29 17:29:13 +00002634/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002635/// This object must already have been set up with the operand type
2636/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002637TargetLowering::ConstraintWeight
2638 TargetLowering::getSingleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002639 AsmOperandInfo &info, const char *constraint) const {
John Thompsone8360b72010-10-29 17:29:13 +00002640 ConstraintWeight weight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002641 Value *CallOperandVal = info.CallOperandVal;
2642 // If we don't have a value, we can't do a match,
2643 // but allow it at the lowest weight.
Craig Topperc0196b12014-04-14 00:51:57 +00002644 if (!CallOperandVal)
John Thompsone8360b72010-10-29 17:29:13 +00002645 return CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002646 // Look at the constraint type.
2647 switch (*constraint) {
2648 case 'i': // immediate integer.
2649 case 'n': // immediate integer with a known value.
John Thompsone8360b72010-10-29 17:29:13 +00002650 if (isa<ConstantInt>(CallOperandVal))
2651 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002652 break;
2653 case 's': // non-explicit intregal immediate.
John Thompsone8360b72010-10-29 17:29:13 +00002654 if (isa<GlobalValue>(CallOperandVal))
2655 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002656 break;
John Thompsone8360b72010-10-29 17:29:13 +00002657 case 'E': // immediate float if host format.
2658 case 'F': // immediate float.
2659 if (isa<ConstantFP>(CallOperandVal))
2660 weight = CW_Constant;
2661 break;
2662 case '<': // memory operand with autodecrement.
2663 case '>': // memory operand with autoincrement.
John Thompson1094c802010-09-13 18:15:37 +00002664 case 'm': // memory operand.
2665 case 'o': // offsettable memory operand
2666 case 'V': // non-offsettable memory operand
John Thompsone8360b72010-10-29 17:29:13 +00002667 weight = CW_Memory;
John Thompson1094c802010-09-13 18:15:37 +00002668 break;
John Thompsone8360b72010-10-29 17:29:13 +00002669 case 'r': // general register.
John Thompson1094c802010-09-13 18:15:37 +00002670 case 'g': // general register, memory operand or immediate integer.
John Thompsone8360b72010-10-29 17:29:13 +00002671 // note: Clang converts "g" to "imr".
2672 if (CallOperandVal->getType()->isIntegerTy())
2673 weight = CW_Register;
John Thompson1094c802010-09-13 18:15:37 +00002674 break;
John Thompsone8360b72010-10-29 17:29:13 +00002675 case 'X': // any operand.
John Thompson1094c802010-09-13 18:15:37 +00002676 default:
John Thompsone8360b72010-10-29 17:29:13 +00002677 weight = CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002678 break;
2679 }
2680 return weight;
2681}
2682
Sanjay Patelac6e9102015-12-29 22:11:50 +00002683/// If there are multiple different constraints that we could pick for this
2684/// operand (e.g. "imr") try to pick the 'best' one.
Chris Lattner58b9ece2008-04-27 01:49:46 +00002685/// This is somewhat tricky: constraints fall into four classes:
Chris Lattner47935152008-04-27 00:09:47 +00002686/// Other -> immediates and magic values
2687/// Register -> one specific register
2688/// RegisterClass -> a group of regs
2689/// Memory -> memory
2690/// Ideally, we would pick the most specific constraint possible: if we have
2691/// something that fits into a register, we would pick it. The problem here
2692/// is that if we have something that could either be in a register or in
2693/// memory that use of the register could cause selection of *other*
2694/// operands to fail: they might only succeed if we pick memory. Because of
2695/// this the heuristic we use is:
2696///
2697/// 1) If there is an 'other' constraint, and if the operand is valid for
2698/// that constraint, use it. This makes us take advantage of 'i'
2699/// constraints when available.
2700/// 2) Otherwise, pick the most general constraint present. This prefers
2701/// 'm' over 'r', for example.
2702///
2703static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
Dale Johannesence97d552010-06-25 21:55:36 +00002704 const TargetLowering &TLI,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002705 SDValue Op, SelectionDAG *DAG) {
Chris Lattner47935152008-04-27 00:09:47 +00002706 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2707 unsigned BestIdx = 0;
2708 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2709 int BestGenerality = -1;
Dale Johannesen17feb072010-06-28 22:09:45 +00002710
Chris Lattner47935152008-04-27 00:09:47 +00002711 // Loop over the options, keeping track of the most general one.
2712 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2713 TargetLowering::ConstraintType CType =
2714 TLI.getConstraintType(OpInfo.Codes[i]);
Dale Johannesen17feb072010-06-28 22:09:45 +00002715
Chris Lattner22379732008-04-27 00:37:18 +00002716 // If this is an 'other' constraint, see if the operand is valid for it.
2717 // For example, on X86 we might have an 'rI' constraint. If the operand
2718 // is an integer in the range [0..31] we want to use I (saving a load
2719 // of a register), otherwise we must use 'r'.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002720 if (CType == TargetLowering::C_Other && Op.getNode()) {
Chris Lattner22379732008-04-27 00:37:18 +00002721 assert(OpInfo.Codes[i].size() == 1 &&
2722 "Unhandled multi-letter 'other' constraint");
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002723 std::vector<SDValue> ResultOps;
Eric Christopherde9399b2011-06-02 23:16:42 +00002724 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
Chris Lattner22379732008-04-27 00:37:18 +00002725 ResultOps, *DAG);
2726 if (!ResultOps.empty()) {
2727 BestType = CType;
2728 BestIdx = i;
2729 break;
2730 }
2731 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002732
Dale Johannesen17feb072010-06-28 22:09:45 +00002733 // Things with matching constraints can only be registers, per gcc
2734 // documentation. This mainly affects "g" constraints.
2735 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2736 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002737
Chris Lattner47935152008-04-27 00:09:47 +00002738 // This constraint letter is more general than the previous one, use it.
2739 int Generality = getConstraintGenerality(CType);
2740 if (Generality > BestGenerality) {
2741 BestType = CType;
2742 BestIdx = i;
2743 BestGenerality = Generality;
2744 }
2745 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002746
Chris Lattner47935152008-04-27 00:09:47 +00002747 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2748 OpInfo.ConstraintType = BestType;
2749}
2750
Sanjay Patelac6e9102015-12-29 22:11:50 +00002751/// Determines the constraint code and constraint type to use for the specific
2752/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
Chris Lattner22379732008-04-27 00:37:18 +00002753void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
Wesley Peck527da1b2010-11-23 03:31:01 +00002754 SDValue Op,
Chris Lattner22379732008-04-27 00:37:18 +00002755 SelectionDAG *DAG) const {
Chris Lattner47935152008-04-27 00:09:47 +00002756 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
Wesley Peck527da1b2010-11-23 03:31:01 +00002757
Chris Lattner47935152008-04-27 00:09:47 +00002758 // Single-letter constraints ('r') are very common.
2759 if (OpInfo.Codes.size() == 1) {
2760 OpInfo.ConstraintCode = OpInfo.Codes[0];
2761 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2762 } else {
Dale Johannesence97d552010-06-25 21:55:36 +00002763 ChooseConstraint(OpInfo, *this, Op, DAG);
Chris Lattner47935152008-04-27 00:09:47 +00002764 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002765
Chris Lattner47935152008-04-27 00:09:47 +00002766 // 'X' matches anything.
2767 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2768 // Labels and constants are handled elsewhere ('X' is the only thing
Dale Johannesen4e331152009-07-07 23:26:33 +00002769 // that matches labels). For Functions, the type here is the type of
Dale Johannesenade297d2009-07-20 23:27:39 +00002770 // the result, which is not what we want to look at; leave them alone.
2771 Value *v = OpInfo.CallOperandVal;
Dale Johannesen4e331152009-07-07 23:26:33 +00002772 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2773 OpInfo.CallOperandVal = v;
Chris Lattner47935152008-04-27 00:09:47 +00002774 return;
Dale Johannesen4e331152009-07-07 23:26:33 +00002775 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002776
Chris Lattner47935152008-04-27 00:09:47 +00002777 // Otherwise, try to resolve it to something we know about by looking at
2778 // the actual operand type.
2779 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2780 OpInfo.ConstraintCode = Repl;
2781 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2782 }
2783 }
2784}
2785
David Majnemer0fc86702013-06-08 23:51:45 +00002786/// \brief Given an exact SDIV by a constant, create a multiplication
Benjamin Kramer9960a252011-07-08 10:31:30 +00002787/// with the multiplicative inverse of the constant.
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002788static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002789 const SDLoc &dl, SelectionDAG &DAG,
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002790 std::vector<SDNode *> &Created) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002791 assert(d != 0 && "Division by zero!");
2792
2793 // Shift the value upfront if it is even, so the LSB is one.
2794 unsigned ShAmt = d.countTrailingZeros();
2795 if (ShAmt) {
2796 // TODO: For UDIV use SRL instead of SRA.
NAKAMURA Takumie4529982015-05-06 14:03:22 +00002797 SDValue Amt =
Mehdi Amini9639d652015-07-09 02:09:20 +00002798 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2799 DAG.getDataLayout()));
Sanjay Patelf1340482015-06-16 16:25:43 +00002800 SDNodeFlags Flags;
2801 Flags.setExact(true);
2802 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002803 Created.push_back(Op1.getNode());
Benjamin Kramer9960a252011-07-08 10:31:30 +00002804 d = d.ashr(ShAmt);
2805 }
2806
2807 // Calculate the multiplicative inverse, using Newton's method.
2808 APInt t, xn = d;
2809 while ((t = d*xn) != 1)
2810 xn *= APInt(d.getBitWidth(), 2) - t;
2811
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002812 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2813 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2814 Created.push_back(Mul.getNode());
2815 return Mul;
Benjamin Kramer9960a252011-07-08 10:31:30 +00002816}
2817
Steve King5cdbd202015-08-25 02:31:21 +00002818SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2819 SelectionDAG &DAG,
2820 std::vector<SDNode *> *Created) const {
2821 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2822 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2823 if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2824 return SDValue(N,0); // Lower SDIV as SDIV
2825 return SDValue();
2826}
2827
David Majnemer0fc86702013-06-08 23:51:45 +00002828/// \brief Given an ISD::SDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002829/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002830/// multiplying by a magic number.
2831/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002832SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2833 SelectionDAG &DAG, bool IsAfterLegalization,
2834 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002835 assert(Created && "No vector to hold sdiv ops.");
2836
Owen Anderson53aa7a92009-08-10 22:56:29 +00002837 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002838 SDLoc dl(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00002839
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002840 // Check to see if we can do this.
Eli Friedmanc8228d22008-11-30 06:35:39 +00002841 // FIXME: We should be more aggressive here.
2842 if (!isTypeLegal(VT))
2843 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002844
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002845 // If the sdiv has an 'exact' bit we can use a simpler lowering.
2846 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
2847 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
2848
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002849 APInt::ms magics = Divisor.magic();
Wesley Peck527da1b2010-11-23 03:31:01 +00002850
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002851 // Multiply the numerator (operand 0) by the magic value
Eli Friedmanc8228d22008-11-30 06:35:39 +00002852 // FIXME: We should support doing a MUL in a wider type
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002853 SDValue Q;
Richard Osborne561fac42011-11-07 17:09:05 +00002854 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2855 isOperationLegalOrCustom(ISD::MULHS, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002856 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002857 DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002858 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2859 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002860 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
Dan Gohmana1603612007-10-08 18:33:35 +00002861 N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002862 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002863 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002864 return SDValue(); // No mulhs or equvialent
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002865 // If d > 0 and m < 0, add the numerator
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002866 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002867 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002868 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002869 }
2870 // If d < 0 and m > 0, subtract the numerator.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002871 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002872 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002873 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002874 }
Mehdi Amini9639d652015-07-09 02:09:20 +00002875 auto &DL = DAG.getDataLayout();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002876 // Shift right algebraic if shift value is nonzero
2877 if (magics.s > 0) {
Mehdi Amini9639d652015-07-09 02:09:20 +00002878 Q = DAG.getNode(
2879 ISD::SRA, dl, VT, Q,
2880 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002881 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002882 }
2883 // Extract the sign bit and add it to the quotient
Mehdi Amini9639d652015-07-09 02:09:20 +00002884 SDValue T =
2885 DAG.getNode(ISD::SRL, dl, VT, Q,
2886 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
2887 getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002888 Created->push_back(T.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002889 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002890}
2891
David Majnemer0fc86702013-06-08 23:51:45 +00002892/// \brief Given an ISD::UDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002893/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002894/// multiplying by a magic number.
2895/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002896SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2897 SelectionDAG &DAG, bool IsAfterLegalization,
2898 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002899 assert(Created && "No vector to hold udiv ops.");
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002900
Owen Anderson53aa7a92009-08-10 22:56:29 +00002901 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002902 SDLoc dl(N);
Mehdi Amini9639d652015-07-09 02:09:20 +00002903 auto &DL = DAG.getDataLayout();
Eli Friedman1b7fc152008-11-30 06:02:26 +00002904
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002905 // Check to see if we can do this.
Eli Friedman1b7fc152008-11-30 06:02:26 +00002906 // FIXME: We should be more aggressive here.
2907 if (!isTypeLegal(VT))
2908 return SDValue();
2909
2910 // FIXME: We should use a narrower constant when the upper
2911 // bits are known to be zero.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002912 APInt::mu magics = Divisor.magicu();
Benjamin Kramercfcea122011-03-17 20:39:14 +00002913
2914 SDValue Q = N->getOperand(0);
2915
2916 // If the divisor is even, we can avoid using the expensive fixup by shifting
2917 // the divided value upfront.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002918 if (magics.a != 0 && !Divisor[0]) {
2919 unsigned Shift = Divisor.countTrailingZeros();
Mehdi Amini9639d652015-07-09 02:09:20 +00002920 Q = DAG.getNode(
2921 ISD::SRL, dl, VT, Q,
2922 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002923 Created->push_back(Q.getNode());
Benjamin Kramercfcea122011-03-17 20:39:14 +00002924
2925 // Get magic number for the shifted divisor.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002926 magics = Divisor.lshr(Shift).magicu(Shift);
Benjamin Kramercfcea122011-03-17 20:39:14 +00002927 assert(magics.a == 0 && "Should use cheap fixup now");
2928 }
Eli Friedman1b7fc152008-11-30 06:02:26 +00002929
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002930 // Multiply the numerator (operand 0) by the magic value
Eli Friedman1b7fc152008-11-30 06:02:26 +00002931 // FIXME: We should support doing a MUL in a wider type
Richard Osborne561fac42011-11-07 17:09:05 +00002932 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2933 isOperationLegalOrCustom(ISD::MULHU, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002934 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002935 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2936 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
Benjamin Kramercfcea122011-03-17 20:39:14 +00002937 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002938 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002939 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002940 return SDValue(); // No mulhu or equvialent
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002941
2942 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002943
2944 if (magics.a == 0) {
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002945 assert(magics.s < Divisor.getBitWidth() &&
Eli Friedman1b7fc152008-11-30 06:02:26 +00002946 "We shouldn't generate an undefined shift!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002947 return DAG.getNode(
2948 ISD::SRL, dl, VT, Q,
2949 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002950 } else {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002951 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002952 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002953 NPQ = DAG.getNode(
2954 ISD::SRL, dl, VT, NPQ,
2955 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002956 Created->push_back(NPQ.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002957 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002958 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002959 return DAG.getNode(
2960 ISD::SRL, dl, VT, NPQ,
2961 DAG.getConstant(magics.s - 1, dl,
2962 getShiftAmountTy(NPQ.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002963 }
2964}
Bill Wendling908bf812014-01-06 00:43:20 +00002965
2966bool TargetLowering::
2967verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
2968 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
2969 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
2970 "be a constant integer");
2971 return true;
2972 }
2973
2974 return false;
2975}
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002976
2977//===----------------------------------------------------------------------===//
2978// Legalization Utilities
2979//===----------------------------------------------------------------------===//
2980
2981bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
2982 SelectionDAG &DAG, SDValue LL, SDValue LH,
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002983 SDValue RL, SDValue RH) const {
Tom Stellardb3a7fa22014-04-11 16:11:58 +00002984 EVT VT = N->getValueType(0);
2985 SDLoc dl(N);
2986
2987 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
2988 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
2989 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
2990 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
2991 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
2992 unsigned OuterBitSize = VT.getSizeInBits();
2993 unsigned InnerBitSize = HiLoVT.getSizeInBits();
2994 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
2995 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
2996
2997 // LL, LH, RL, and RH must be either all NULL or all set to a value.
2998 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
2999 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3000
3001 if (!LL.getNode() && !RL.getNode() &&
3002 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3003 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
3004 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
3005 }
3006
3007 if (!LL.getNode())
3008 return false;
3009
3010 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3011 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
3012 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
3013 // The inputs are both zero-extended.
3014 if (HasUMUL_LOHI) {
3015 // We can emit a umul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003016 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3017 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003018 Hi = SDValue(Lo.getNode(), 1);
3019 return true;
3020 }
3021 if (HasMULHU) {
3022 // We can emit a mulhu+mul.
3023 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3024 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3025 return true;
3026 }
3027 }
3028 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
3029 // The input values are both sign-extended.
3030 if (HasSMUL_LOHI) {
3031 // We can emit a smul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003032 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3033 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003034 Hi = SDValue(Lo.getNode(), 1);
3035 return true;
3036 }
3037 if (HasMULHS) {
3038 // We can emit a mulhs+mul.
3039 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3040 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
3041 return true;
3042 }
3043 }
3044
3045 if (!LH.getNode() && !RH.getNode() &&
3046 isOperationLegalOrCustom(ISD::SRL, VT) &&
3047 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +00003048 auto &DL = DAG.getDataLayout();
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003049 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
Mehdi Amini9639d652015-07-09 02:09:20 +00003050 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL));
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003051 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
3052 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3053 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
3054 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3055 }
3056
3057 if (!LH.getNode())
3058 return false;
3059
3060 if (HasUMUL_LOHI) {
3061 // Lo,Hi = umul LHS, RHS.
3062 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
3063 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
3064 Lo = UMulLOHI;
3065 Hi = UMulLOHI.getValue(1);
3066 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3067 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3068 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3069 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3070 return true;
3071 }
3072 if (HasMULHU) {
3073 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3074 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3075 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3076 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3077 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3078 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3079 return true;
3080 }
3081 }
3082 return false;
3083}
Jan Veselyeca89d22014-07-10 22:40:18 +00003084
3085bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3086 SelectionDAG &DAG) const {
3087 EVT VT = Node->getOperand(0).getValueType();
3088 EVT NVT = Node->getValueType(0);
3089 SDLoc dl(SDValue(Node, 0));
3090
3091 // FIXME: Only f32 to i64 conversions are supported.
3092 if (VT != MVT::f32 || NVT != MVT::i64)
3093 return false;
3094
3095 // Expand f32 -> i64 conversion
3096 // This algorithm comes from compiler-rt's implementation of fixsfdi:
3097 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3098 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3099 VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003100 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3101 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3102 SDValue Bias = DAG.getConstant(127, dl, IntVT);
3103 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
Jan Veselyeca89d22014-07-10 22:40:18 +00003104 IntVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003105 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3106 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003107
3108 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3109
Mehdi Amini9639d652015-07-09 02:09:20 +00003110 auto &DL = DAG.getDataLayout();
3111 SDValue ExponentBits = DAG.getNode(
3112 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3113 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003114 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3115
Mehdi Amini9639d652015-07-09 02:09:20 +00003116 SDValue Sign = DAG.getNode(
3117 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3118 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003119 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3120
3121 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3122 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003123 DAG.getConstant(0x00800000, dl, IntVT));
Jan Veselyeca89d22014-07-10 22:40:18 +00003124
3125 R = DAG.getZExtOrTrunc(R, dl, NVT);
3126
Mehdi Amini9639d652015-07-09 02:09:20 +00003127 R = DAG.getSelectCC(
3128 dl, Exponent, ExponentLoBit,
3129 DAG.getNode(ISD::SHL, dl, NVT, R,
3130 DAG.getZExtOrTrunc(
3131 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3132 dl, getShiftAmountTy(IntVT, DL))),
3133 DAG.getNode(ISD::SRL, dl, NVT, R,
3134 DAG.getZExtOrTrunc(
3135 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3136 dl, getShiftAmountTy(IntVT, DL))),
3137 ISD::SETGT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003138
3139 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3140 DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3141 Sign);
3142
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003143 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3144 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003145 return true;
3146}
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003147
Matt Arsenaulta4b1b6e2016-03-30 21:15:10 +00003148SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3149 SelectionDAG &DAG) const {
3150 SDLoc SL(LD);
3151 SDValue Chain = LD->getChain();
3152 SDValue BasePTR = LD->getBasePtr();
3153 EVT SrcVT = LD->getMemoryVT();
3154 ISD::LoadExtType ExtType = LD->getExtensionType();
3155
3156 unsigned NumElem = SrcVT.getVectorNumElements();
3157
3158 EVT SrcEltVT = SrcVT.getScalarType();
3159 EVT DstEltVT = LD->getValueType(0).getScalarType();
3160
3161 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3162 assert(SrcEltVT.isByteSized());
3163
3164 EVT PtrVT = BasePTR.getValueType();
3165
3166 SmallVector<SDValue, 8> Vals;
3167 SmallVector<SDValue, 8> LoadChains;
3168
3169 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3170 SDValue ScalarLoad = DAG.getExtLoad(
3171 ExtType, SL, DstEltVT,
3172 Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Stride),
3173 SrcEltVT,
3174 LD->isVolatile(), LD->isNonTemporal(), LD->isInvariant(),
3175 MinAlign(LD->getAlignment(), Idx * Stride), LD->getAAInfo());
3176
3177 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3178 DAG.getConstant(Stride, SL, PtrVT));
3179
3180 Vals.push_back(ScalarLoad.getValue(0));
3181 LoadChains.push_back(ScalarLoad.getValue(1));
3182 }
3183
3184 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3185 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, SL, LD->getValueType(0), Vals);
3186
3187 return DAG.getMergeValues({ Value, NewChain }, SL);
3188}
3189
Matt Arsenault46ba3162016-03-30 21:15:18 +00003190// FIXME: This relies on each element having a byte size, otherwise the stride
3191// is 0 and just overwrites the same location. ExpandStore currently expects
3192// this broken behavior.
3193SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3194 SelectionDAG &DAG) const {
3195 SDLoc SL(ST);
3196
3197 SDValue Chain = ST->getChain();
3198 SDValue BasePtr = ST->getBasePtr();
3199 SDValue Value = ST->getValue();
3200 EVT StVT = ST->getMemoryVT();
3201
3202 unsigned Alignment = ST->getAlignment();
3203 bool isVolatile = ST->isVolatile();
3204 bool isNonTemporal = ST->isNonTemporal();
3205 AAMDNodes AAInfo = ST->getAAInfo();
3206
3207 // The type of the data we want to save
3208 EVT RegVT = Value.getValueType();
3209 EVT RegSclVT = RegVT.getScalarType();
3210
3211 // The type of data as saved in memory.
3212 EVT MemSclVT = StVT.getScalarType();
3213
3214 EVT PtrVT = BasePtr.getValueType();
3215
3216 // Store Stride in bytes
3217 unsigned Stride = MemSclVT.getSizeInBits() / 8;
3218 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3219 unsigned NumElem = StVT.getVectorNumElements();
3220
3221 // Extract each of the elements from the original vector and save them into
3222 // memory individually.
3223 SmallVector<SDValue, 8> Stores;
3224 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3225 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3226 DAG.getConstant(Idx, SL, IdxVT));
3227
3228 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3229 DAG.getConstant(Idx * Stride, SL, PtrVT));
3230
3231 // This scalar TruncStore may be illegal, but we legalize it later.
3232 SDValue Store = DAG.getTruncStore(
3233 Chain, SL, Elt, Ptr,
3234 ST->getPointerInfo().getWithOffset(Idx * Stride), MemSclVT,
3235 isVolatile, isNonTemporal, MinAlign(Alignment, Idx * Stride),
3236 AAInfo);
3237
3238 Stores.push_back(Store);
3239 }
3240
3241 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3242}
3243
Matt Arsenault7846d882016-04-21 18:19:11 +00003244std::pair<SDValue, SDValue>
3245TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3246 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3247 "unaligned indexed loads not implemented!");
3248 SDValue Chain = LD->getChain();
3249 SDValue Ptr = LD->getBasePtr();
3250 EVT VT = LD->getValueType(0);
3251 EVT LoadedVT = LD->getMemoryVT();
3252 SDLoc dl(LD);
3253 if (VT.isFloatingPoint() || VT.isVector()) {
3254 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3255 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3256 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3257 // Scalarize the load and let the individual components be handled.
3258 SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3259 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3260 }
3261
3262 // Expand to a (misaligned) integer load of the same size,
3263 // then bitconvert to floating point or vector.
3264 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3265 LD->getMemOperand());
3266 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3267 if (LoadedVT != VT)
3268 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3269 ISD::ANY_EXTEND, dl, VT, Result);
3270
3271 return std::make_pair(Result, newLoad.getValue(1));
3272 }
3273
3274 // Copy the value to a (aligned) stack slot using (unaligned) integer
3275 // loads and stores, then do a (aligned) load from the stack slot.
3276 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3277 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3278 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3279 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3280
3281 // Make sure the stack slot is also aligned for the register type.
3282 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3283
3284 SmallVector<SDValue, 8> Stores;
3285 SDValue StackPtr = StackBase;
3286 unsigned Offset = 0;
3287
3288 EVT PtrVT = Ptr.getValueType();
3289 EVT StackPtrVT = StackPtr.getValueType();
3290
3291 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3292 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3293
3294 // Do all but one copies using the full register width.
3295 for (unsigned i = 1; i < NumRegs; i++) {
3296 // Load one integer register's worth from the original location.
3297 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
3298 LD->getPointerInfo().getWithOffset(Offset),
3299 LD->isVolatile(), LD->isNonTemporal(),
3300 LD->isInvariant(),
3301 MinAlign(LD->getAlignment(), Offset),
3302 LD->getAAInfo());
3303 // Follow the load with a store to the stack slot. Remember the store.
3304 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3305 MachinePointerInfo(), false, false, 0));
3306 // Increment the pointers.
3307 Offset += RegBytes;
3308 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3309 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3310 StackPtrIncrement);
3311 }
3312
3313 // The last copy may be partial. Do an extending load.
3314 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3315 8 * (LoadedBytes - Offset));
3316 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3317 LD->getPointerInfo().getWithOffset(Offset),
3318 MemVT, LD->isVolatile(),
3319 LD->isNonTemporal(),
3320 LD->isInvariant(),
3321 MinAlign(LD->getAlignment(), Offset),
3322 LD->getAAInfo());
3323 // Follow the load with a store to the stack slot. Remember the store.
3324 // On big-endian machines this requires a truncating store to ensure
3325 // that the bits end up in the right place.
3326 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3327 MachinePointerInfo(), MemVT,
3328 false, false, 0));
3329
3330 // The order of the stores doesn't matter - say it with a TokenFactor.
3331 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3332
3333 // Finally, perform the original load only redirected to the stack slot.
3334 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3335 MachinePointerInfo(), LoadedVT, false,false, false,
3336 0);
3337
3338 // Callers expect a MERGE_VALUES node.
3339 return std::make_pair(Load, TF);
3340 }
3341
3342 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3343 "Unaligned load of unsupported type.");
3344
3345 // Compute the new VT that is half the size of the old one. This is an
3346 // integer MVT.
3347 unsigned NumBits = LoadedVT.getSizeInBits();
3348 EVT NewLoadedVT;
3349 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3350 NumBits >>= 1;
3351
3352 unsigned Alignment = LD->getAlignment();
3353 unsigned IncrementSize = NumBits / 8;
3354 ISD::LoadExtType HiExtType = LD->getExtensionType();
3355
3356 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3357 if (HiExtType == ISD::NON_EXTLOAD)
3358 HiExtType = ISD::ZEXTLOAD;
3359
3360 // Load the value in two parts
3361 SDValue Lo, Hi;
3362 if (DAG.getDataLayout().isLittleEndian()) {
3363 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3364 NewLoadedVT, LD->isVolatile(),
3365 LD->isNonTemporal(), LD->isInvariant(), Alignment,
3366 LD->getAAInfo());
3367 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3368 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3369 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3370 LD->getPointerInfo().getWithOffset(IncrementSize),
3371 NewLoadedVT, LD->isVolatile(),
3372 LD->isNonTemporal(),LD->isInvariant(),
3373 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
3374 } else {
3375 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3376 NewLoadedVT, LD->isVolatile(),
3377 LD->isNonTemporal(), LD->isInvariant(), Alignment,
3378 LD->getAAInfo());
3379 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3380 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3381 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3382 LD->getPointerInfo().getWithOffset(IncrementSize),
3383 NewLoadedVT, LD->isVolatile(),
3384 LD->isNonTemporal(), LD->isInvariant(),
3385 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
3386 }
3387
3388 // aggregate the two parts
3389 SDValue ShiftAmount =
3390 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3391 DAG.getDataLayout()));
3392 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3393 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3394
3395 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3396 Hi.getValue(1));
3397
3398 return std::make_pair(Result, TF);
3399}
3400
3401SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3402 SelectionDAG &DAG) const {
3403 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3404 "unaligned indexed stores not implemented!");
3405 SDValue Chain = ST->getChain();
3406 SDValue Ptr = ST->getBasePtr();
3407 SDValue Val = ST->getValue();
3408 EVT VT = Val.getValueType();
3409 int Alignment = ST->getAlignment();
3410
3411 SDLoc dl(ST);
3412 if (ST->getMemoryVT().isFloatingPoint() ||
3413 ST->getMemoryVT().isVector()) {
3414 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3415 if (isTypeLegal(intVT)) {
3416 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3417 // Scalarize the store and let the individual components be handled.
3418 SDValue Result = scalarizeVectorStore(ST, DAG);
3419
3420 return Result;
3421 }
3422 // Expand to a bitconvert of the value to the integer type of the
3423 // same size, then a (misaligned) int store.
3424 // FIXME: Does not handle truncating floating point stores!
3425 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3426 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3427 ST->isVolatile(), ST->isNonTemporal(), Alignment);
3428 return Result;
3429 }
3430 // Do a (aligned) store to a stack slot, then copy from the stack slot
3431 // to the final destination using (unaligned) integer loads and stores.
3432 EVT StoredVT = ST->getMemoryVT();
3433 MVT RegVT =
3434 getRegisterType(*DAG.getContext(),
3435 EVT::getIntegerVT(*DAG.getContext(),
3436 StoredVT.getSizeInBits()));
3437 EVT PtrVT = Ptr.getValueType();
3438 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3439 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3440 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3441
3442 // Make sure the stack slot is also aligned for the register type.
3443 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3444
3445 // Perform the original store, only redirected to the stack slot.
3446 SDValue Store = DAG.getTruncStore(Chain, dl,
3447 Val, StackPtr, MachinePointerInfo(),
3448 StoredVT, false, false, 0);
3449
3450 EVT StackPtrVT = StackPtr.getValueType();
3451
3452 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3453 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3454 SmallVector<SDValue, 8> Stores;
3455 unsigned Offset = 0;
3456
3457 // Do all but one copies using the full register width.
3458 for (unsigned i = 1; i < NumRegs; i++) {
3459 // Load one integer register's worth from the stack slot.
3460 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
3461 MachinePointerInfo(),
3462 false, false, false, 0);
3463 // Store it to the final location. Remember the store.
3464 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3465 ST->getPointerInfo().getWithOffset(Offset),
3466 ST->isVolatile(), ST->isNonTemporal(),
3467 MinAlign(ST->getAlignment(), Offset)));
3468 // Increment the pointers.
3469 Offset += RegBytes;
3470 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3471 StackPtr, StackPtrIncrement);
3472 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3473 }
3474
3475 // The last store may be partial. Do a truncating store. On big-endian
3476 // machines this requires an extending load from the stack slot to ensure
3477 // that the bits are in the right place.
3478 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3479 8 * (StoredBytes - Offset));
3480
3481 // Load from the stack slot.
3482 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3483 MachinePointerInfo(),
3484 MemVT, false, false, false, 0);
3485
3486 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3487 ST->getPointerInfo()
3488 .getWithOffset(Offset),
3489 MemVT, ST->isVolatile(),
3490 ST->isNonTemporal(),
3491 MinAlign(ST->getAlignment(), Offset),
3492 ST->getAAInfo()));
3493 // The order of the stores doesn't matter - say it with a TokenFactor.
3494 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3495 return Result;
3496 }
3497
3498 assert(ST->getMemoryVT().isInteger() &&
3499 !ST->getMemoryVT().isVector() &&
3500 "Unaligned store of unknown type.");
3501 // Get the half-size VT
3502 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3503 int NumBits = NewStoredVT.getSizeInBits();
3504 int IncrementSize = NumBits / 8;
3505
3506 // Divide the stored value in two parts.
3507 SDValue ShiftAmount =
3508 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3509 DAG.getDataLayout()));
3510 SDValue Lo = Val;
3511 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3512
3513 // Store the two parts
3514 SDValue Store1, Store2;
3515 Store1 = DAG.getTruncStore(Chain, dl,
3516 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3517 Ptr, ST->getPointerInfo(), NewStoredVT,
3518 ST->isVolatile(), ST->isNonTemporal(), Alignment);
3519
3520 EVT PtrVT = Ptr.getValueType();
3521 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3522 DAG.getConstant(IncrementSize, dl, PtrVT));
3523 Alignment = MinAlign(Alignment, IncrementSize);
3524 Store2 = DAG.getTruncStore(
3525 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3526 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT,
3527 ST->isVolatile(), ST->isNonTemporal(), Alignment, ST->getAAInfo());
3528
3529 SDValue Result =
3530 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3531 return Result;
3532}
3533
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003534//===----------------------------------------------------------------------===//
3535// Implementation of Emulated TLS Model
3536//===----------------------------------------------------------------------===//
3537
3538SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3539 SelectionDAG &DAG) const {
3540 // Access to address of TLS varialbe xyz is lowered to a function call:
3541 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3542 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3543 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3544 SDLoc dl(GA);
3545
3546 ArgListTy Args;
3547 ArgListEntry Entry;
3548 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3549 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3550 StringRef EmuTlsVarName(NameString);
3551 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
Chih-Hung Hsieh57886402016-01-13 23:56:37 +00003552 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003553 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3554 Entry.Ty = VoidPtrType;
3555 Args.push_back(Entry);
3556
3557 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3558
3559 TargetLowering::CallLoweringInfo CLI(DAG);
3560 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00003561 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003562 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3563
3564 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3565 // At last for X86 targets, maybe good for other targets too?
3566 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3567 MFI->setAdjustsStack(true); // Is this only for X86 target?
3568 MFI->setHasCalls(true);
3569
3570 assert((GA->getOffset() == 0) &&
3571 "Emulated TLS must have zero offset in GlobalAddressSDNode");
3572 return CallResult.first;
3573}