1 //===-- X86SelectionDAGInfo.cpp - X86 SelectionDAG Info -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the X86SelectionDAGInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86SelectionDAGInfo.h"
14 #include "X86ISelLowering.h"
15 #include "X86InstrInfo.h"
16 #include "X86RegisterInfo.h"
17 #include "X86Subtarget.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/CodeGen/TargetLowering.h"
21 #include "llvm/IR/DerivedTypes.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "x86-selectiondag-info"
26 
27 bool X86SelectionDAGInfo::isBaseRegConflictPossible(
28     SelectionDAG &DAG, ArrayRef<MCPhysReg> ClobberSet) const {
29   // We cannot use TRI->hasBasePointer() until *after* we select all basic
30   // blocks.  Legalization may introduce new stack temporaries with large
31   // alignment requirements.  Fall back to generic code if there are any
32   // dynamic stack adjustments (hopefully rare) and the base pointer would
33   // conflict if we had to use it.
34   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
35   if (!MFI.hasVarSizedObjects() && !MFI.hasOpaqueSPAdjustment())
36     return false;
37 
38   const X86RegisterInfo *TRI = static_cast<const X86RegisterInfo *>(
39       DAG.getSubtarget().getRegisterInfo());
40   Register BaseReg = TRI->getBaseRegister();
41   for (unsigned R : ClobberSet)
42     if (BaseReg == R)
43       return true;
44   return false;
45 }
46 
47 SDValue X86SelectionDAGInfo::EmitTargetCodeForMemset(
48     SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Val,
49     SDValue Size, unsigned Align, bool isVolatile,
50     MachinePointerInfo DstPtrInfo) const {
51   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
52   const X86Subtarget &Subtarget =
53       DAG.getMachineFunction().getSubtarget<X86Subtarget>();
54 
55 #ifndef NDEBUG
56   // If the base register might conflict with our physical registers, bail out.
57   const MCPhysReg ClobberSet[] = {X86::RCX, X86::RAX, X86::RDI,
58                                   X86::ECX, X86::EAX, X86::EDI};
59   assert(!isBaseRegConflictPossible(DAG, ClobberSet));
60 #endif
61 
62   // If to a segment-relative address space, use the default lowering.
63   if (DstPtrInfo.getAddrSpace() >= 256)
64     return SDValue();
65 
66   // If not DWORD aligned or size is more than the threshold, call the library.
67   // The libc version is likely to be faster for these cases. It can use the
68   // address value and run time information about the CPU.
69   if ((Align & 3) != 0 || !ConstantSize ||
70       ConstantSize->getZExtValue() > Subtarget.getMaxInlineSizeThreshold()) {
71     // Check to see if there is a specialized entry-point for memory zeroing.
72     ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Val);
73 
74     if (const char *bzeroName = (ValC && ValC->isNullValue())
75         ? DAG.getTargetLoweringInfo().getLibcallName(RTLIB::BZERO)
76         : nullptr) {
77       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
78       EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
79       Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
80       TargetLowering::ArgListTy Args;
81       TargetLowering::ArgListEntry Entry;
82       Entry.Node = Dst;
83       Entry.Ty = IntPtrTy;
84       Args.push_back(Entry);
85       Entry.Node = Size;
86       Args.push_back(Entry);
87 
88       TargetLowering::CallLoweringInfo CLI(DAG);
89       CLI.setDebugLoc(dl)
90           .setChain(Chain)
91           .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
92                         DAG.getExternalSymbol(bzeroName, IntPtr),
93                         std::move(Args))
94           .setDiscardResult();
95 
96       std::pair<SDValue,SDValue> CallResult = TLI.LowerCallTo(CLI);
97       return CallResult.second;
98     }
99 
100     // Otherwise have the target-independent code call memset.
101     return SDValue();
102   }
103 
104   uint64_t SizeVal = ConstantSize->getZExtValue();
105   SDValue InFlag;
106   EVT AVT;
107   SDValue Count;
108   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Val);
109   unsigned BytesLeft = 0;
110   if (ValC) {
111     unsigned ValReg;
112     uint64_t Val = ValC->getZExtValue() & 255;
113 
114     // If the value is a constant, then we can potentially use larger sets.
115     switch (Align & 3) {
116     case 2:   // WORD aligned
117       AVT = MVT::i16;
118       ValReg = X86::AX;
119       Val = (Val << 8) | Val;
120       break;
121     case 0:  // DWORD aligned
122       AVT = MVT::i32;
123       ValReg = X86::EAX;
124       Val = (Val << 8)  | Val;
125       Val = (Val << 16) | Val;
126       if (Subtarget.is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
127         AVT = MVT::i64;
128         ValReg = X86::RAX;
129         Val = (Val << 32) | Val;
130       }
131       break;
132     default:  // Byte aligned
133       AVT = MVT::i8;
134       ValReg = X86::AL;
135       Count = DAG.getIntPtrConstant(SizeVal, dl);
136       break;
137     }
138 
139     if (AVT.bitsGT(MVT::i8)) {
140       unsigned UBytes = AVT.getSizeInBits() / 8;
141       Count = DAG.getIntPtrConstant(SizeVal / UBytes, dl);
142       BytesLeft = SizeVal % UBytes;
143     }
144 
145     Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, dl, AVT),
146                              InFlag);
147     InFlag = Chain.getValue(1);
148   } else {
149     AVT = MVT::i8;
150     Count  = DAG.getIntPtrConstant(SizeVal, dl);
151     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Val, InFlag);
152     InFlag = Chain.getValue(1);
153   }
154 
155   bool Use64BitRegs = Subtarget.isTarget64BitLP64();
156   Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RCX : X86::ECX,
157                            Count, InFlag);
158   InFlag = Chain.getValue(1);
159   Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RDI : X86::EDI,
160                            Dst, InFlag);
161   InFlag = Chain.getValue(1);
162 
163   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
164   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
165   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops);
166 
167   if (BytesLeft) {
168     // Handle the last 1 - 7 bytes.
169     unsigned Offset = SizeVal - BytesLeft;
170     EVT AddrVT = Dst.getValueType();
171     EVT SizeVT = Size.getValueType();
172 
173     Chain = DAG.getMemset(Chain, dl,
174                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
175                                       DAG.getConstant(Offset, dl, AddrVT)),
176                           Val, DAG.getConstant(BytesLeft, dl, SizeVT),
177                           llvm::Align(Align), isVolatile, false,
178                           DstPtrInfo.getWithOffset(Offset));
179   }
180 
181   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
182   return Chain;
183 }
184 
185 /// Emit a single REP MOVS{B,W,D,Q} instruction.
186 static SDValue emitRepmovs(const X86Subtarget &Subtarget, SelectionDAG &DAG,
187                            const SDLoc &dl, SDValue Chain, SDValue Dst,
188                            SDValue Src, SDValue Size, MVT AVT) {
189   const bool Use64BitRegs = Subtarget.isTarget64BitLP64();
190   const unsigned CX = Use64BitRegs ? X86::RCX : X86::ECX;
191   const unsigned DI = Use64BitRegs ? X86::RDI : X86::EDI;
192   const unsigned SI = Use64BitRegs ? X86::RSI : X86::ESI;
193 
194   SDValue InFlag;
195   Chain = DAG.getCopyToReg(Chain, dl, CX, Size, InFlag);
196   InFlag = Chain.getValue(1);
197   Chain = DAG.getCopyToReg(Chain, dl, DI, Dst, InFlag);
198   InFlag = Chain.getValue(1);
199   Chain = DAG.getCopyToReg(Chain, dl, SI, Src, InFlag);
200   InFlag = Chain.getValue(1);
201 
202   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
203   SDValue Ops[] = {Chain, DAG.getValueType(AVT), InFlag};
204   return DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops);
205 }
206 
207 /// Emit a single REP MOVSB instruction for a particular constant size.
208 static SDValue emitRepmovsB(const X86Subtarget &Subtarget, SelectionDAG &DAG,
209                             const SDLoc &dl, SDValue Chain, SDValue Dst,
210                             SDValue Src, uint64_t Size) {
211   return emitRepmovs(Subtarget, DAG, dl, Chain, Dst, Src,
212                      DAG.getIntPtrConstant(Size, dl), MVT::i8);
213 }
214 
215 /// Returns the best type to use with repmovs depending on alignment.
216 static MVT getOptimalRepmovsType(const X86Subtarget &Subtarget,
217                                  uint64_t Align) {
218   assert((Align != 0) && "Align is normalized");
219   assert(isPowerOf2_64(Align) && "Align is a power of 2");
220   switch (Align) {
221   case 1:
222     return MVT::i8;
223   case 2:
224     return MVT::i16;
225   case 4:
226     return MVT::i32;
227   default:
228     return Subtarget.is64Bit() ? MVT::i64 : MVT::i32;
229   }
230 }
231 
232 /// Returns a REP MOVS instruction, possibly with a few load/stores to implement
233 /// a constant size memory copy. In some cases where we know REP MOVS is
234 /// inefficient we return an empty SDValue so the calling code can either
235 /// generate a load/store sequence or call the runtime memcpy function.
236 static SDValue emitConstantSizeRepmov(
237     SelectionDAG &DAG, const X86Subtarget &Subtarget, const SDLoc &dl,
238     SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, EVT SizeVT,
239     unsigned Align, bool isVolatile, bool AlwaysInline,
240     MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo) {
241 
242   /// TODO: Revisit next line: big copy with ERMSB on march >= haswell are very
243   /// efficient.
244   if (!AlwaysInline && Size > Subtarget.getMaxInlineSizeThreshold())
245     return SDValue();
246 
247   /// If we have enhanced repmovs we use it.
248   if (Subtarget.hasERMSB())
249     return emitRepmovsB(Subtarget, DAG, dl, Chain, Dst, Src, Size);
250 
251   assert(!Subtarget.hasERMSB() && "No efficient RepMovs");
252   /// We assume runtime memcpy will do a better job for unaligned copies when
253   /// ERMS is not present.
254   if (!AlwaysInline && (Align & 3) != 0)
255     return SDValue();
256 
257   const MVT BlockType = getOptimalRepmovsType(Subtarget, Align);
258   const uint64_t BlockBytes = BlockType.getSizeInBits() / 8;
259   const uint64_t BlockCount = Size / BlockBytes;
260   const uint64_t BytesLeft = Size % BlockBytes;
261   SDValue RepMovs =
262       emitRepmovs(Subtarget, DAG, dl, Chain, Dst, Src,
263                   DAG.getIntPtrConstant(BlockCount, dl), BlockType);
264 
265   /// RepMov can process the whole length.
266   if (BytesLeft == 0)
267     return RepMovs;
268 
269   assert(BytesLeft && "We have leftover at this point");
270 
271   /// In case we optimize for size we use repmovsb even if it's less efficient
272   /// so we can save the loads/stores of the leftover.
273   if (DAG.getMachineFunction().getFunction().hasMinSize())
274     return emitRepmovsB(Subtarget, DAG, dl, Chain, Dst, Src, Size);
275 
276   // Handle the last 1 - 7 bytes.
277   SmallVector<SDValue, 4> Results;
278   Results.push_back(RepMovs);
279   unsigned Offset = Size - BytesLeft;
280   EVT DstVT = Dst.getValueType();
281   EVT SrcVT = Src.getValueType();
282   Results.push_back(DAG.getMemcpy(
283       Chain, dl,
284       DAG.getNode(ISD::ADD, dl, DstVT, Dst, DAG.getConstant(Offset, dl, DstVT)),
285       DAG.getNode(ISD::ADD, dl, SrcVT, Src, DAG.getConstant(Offset, dl, SrcVT)),
286       DAG.getConstant(BytesLeft, dl, SizeVT), llvm::Align(Align), isVolatile,
287       /*AlwaysInline*/ true, /*isTailCall*/ false,
288       DstPtrInfo.getWithOffset(Offset), SrcPtrInfo.getWithOffset(Offset)));
289   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Results);
290 }
291 
292 SDValue X86SelectionDAGInfo::EmitTargetCodeForMemcpy(
293     SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
294     SDValue Size, unsigned Align, bool isVolatile, bool AlwaysInline,
295     MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo) const {
296   // If to a segment-relative address space, use the default lowering.
297   if (DstPtrInfo.getAddrSpace() >= 256 || SrcPtrInfo.getAddrSpace() >= 256)
298     return SDValue();
299 
300   // If the base registers conflict with our physical registers, use the default
301   // lowering.
302   const MCPhysReg ClobberSet[] = {X86::RCX, X86::RSI, X86::RDI,
303                                   X86::ECX, X86::ESI, X86::EDI};
304   if (isBaseRegConflictPossible(DAG, ClobberSet))
305     return SDValue();
306 
307   const X86Subtarget &Subtarget =
308       DAG.getMachineFunction().getSubtarget<X86Subtarget>();
309 
310   /// Handle constant sizes,
311   if (ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size))
312     return emitConstantSizeRepmov(DAG, Subtarget, dl, Chain, Dst, Src,
313                                   ConstantSize->getZExtValue(),
314                                   Size.getValueType(), Align, isVolatile,
315                                   AlwaysInline, DstPtrInfo, SrcPtrInfo);
316 
317   return SDValue();
318 }
319