blob: a5e1fea3bf42a1a0efa569a47f39d618afd5e4d6 [file] [log] [blame]
Chris Lattner5930d3d2005-11-16 22:59:19 +00001//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
Chris Lattner655e7df2005-11-16 01:54:32 +00002//
3// 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.
Chris Lattner655e7df2005-11-16 01:54:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a DAG pattern matching instruction selector for X86,
11// converting from a legalized dag to a X86 dag.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
Evan Chengbc7a0f442006-01-11 06:09:51 +000016#include "X86InstrBuilder.h"
Evan Chengf55b7382008-01-05 00:41:47 +000017#include "X86MachineFunctionInfo.h"
Chris Lattner7c551262006-01-11 01:15:34 +000018#include "X86RegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000019#include "X86Subtarget.h"
Evan Cheng2dd2c652006-03-13 23:20:37 +000020#include "X86TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/Statistic.h"
Evan Cheng73a1ad92006-01-10 20:26:56 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner7c551262006-01-11 01:15:34 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000026#include "llvm/CodeGen/SelectionDAGISel.h"
Peter Collingbourne235c2752016-12-08 19:01:00 +000027#include "llvm/IR/ConstantRange.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000028#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Type.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000032#include "llvm/Support/Debug.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000033#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000034#include "llvm/Support/KnownBits.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000035#include "llvm/Support/MathExtras.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000039#include <stdint.h>
Chris Lattner655e7df2005-11-16 01:54:32 +000040using namespace llvm;
41
Chandler Carruth84e68b22014-04-22 02:41:26 +000042#define DEBUG_TYPE "x86-isel"
43
Chris Lattner1ef9cd42006-12-19 22:59:26 +000044STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45
Chris Lattner655e7df2005-11-16 01:54:32 +000046//===----------------------------------------------------------------------===//
47// Pattern Matcher Implementation
48//===----------------------------------------------------------------------===//
49
50namespace {
Sanjay Patelb5723d02015-10-13 15:12:27 +000051 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
52 /// numbers for the leaves of the matched tree.
Chris Lattner3f0f71b2005-11-19 02:11:08 +000053 struct X86ISelAddressMode {
54 enum {
55 RegBase,
Chris Lattneraa2372562006-05-24 17:04:05 +000056 FrameIndexBase
Chris Lattner3f0f71b2005-11-19 02:11:08 +000057 } BaseType;
58
Dan Gohman0fd54fb2010-04-29 23:30:41 +000059 // This is really a union, discriminated by BaseType!
60 SDValue Base_Reg;
61 int Base_FrameIndex;
Chris Lattner3f0f71b2005-11-19 02:11:08 +000062
63 unsigned Scale;
Chad Rosier24c19d22012-08-01 18:39:17 +000064 SDValue IndexReg;
Dan Gohman059c4fa2008-11-11 15:52:29 +000065 int32_t Disp;
Rafael Espindola3b2df102009-04-08 21:14:34 +000066 SDValue Segment;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000067 const GlobalValue *GV;
68 const Constant *CP;
69 const BlockAddress *BlockAddr;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000070 const char *ES;
Rafael Espindola36b718f2015-06-22 17:46:53 +000071 MCSymbol *MCSym;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000072 int JT;
Evan Cheng77d86ff2006-02-25 10:09:08 +000073 unsigned Align; // CP alignment.
Chris Lattnerbd7e26d2009-06-26 05:51:45 +000074 unsigned char SymbolFlags; // X86II::MO_*
Chris Lattner3f0f71b2005-11-19 02:11:08 +000075
76 X86ISelAddressMode()
Rafael Espindola36b718f2015-06-22 17:46:53 +000077 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
78 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
79 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
Dan Gohman4e3e3de2009-02-07 00:43:41 +000080
81 bool hasSymbolicDisplacement() const {
Craig Topper062a2ba2014-04-25 05:30:21 +000082 return GV != nullptr || CP != nullptr || ES != nullptr ||
Rafael Espindola36b718f2015-06-22 17:46:53 +000083 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
Dan Gohman4e3e3de2009-02-07 00:43:41 +000084 }
Chad Rosier24c19d22012-08-01 18:39:17 +000085
Chris Lattnerfea81da2009-06-27 04:16:01 +000086 bool hasBaseOrIndexReg() const {
Tim Northover97347a82013-09-19 11:33:53 +000087 return BaseType == FrameIndexBase ||
Craig Topper062a2ba2014-04-25 05:30:21 +000088 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
Chris Lattnerfea81da2009-06-27 04:16:01 +000089 }
Chad Rosier24c19d22012-08-01 18:39:17 +000090
Jatin Bhateja908c8b32017-09-15 05:29:51 +000091 bool hasComplexAddressingMode() const {
92 return Disp && IndexReg.getNode() != nullptr &&
93 Base_Reg.getNode() != nullptr;
94 }
95
Sanjay Patelb5723d02015-10-13 15:12:27 +000096 /// Return true if this addressing mode is already RIP-relative.
Chris Lattnerfea81da2009-06-27 04:16:01 +000097 bool isRIPRelative() const {
98 if (BaseType != RegBase) return false;
99 if (RegisterSDNode *RegNode =
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000100 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
Chris Lattnerfea81da2009-06-27 04:16:01 +0000101 return RegNode->getReg() == X86::RIP;
102 return false;
103 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000104
Jatin Bhateja908c8b32017-09-15 05:29:51 +0000105 bool isLegalScale() {
106 return (Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8);
107 }
108
Chris Lattnerfea81da2009-06-27 04:16:01 +0000109 void setBaseReg(SDValue Reg) {
110 BaseType = RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000111 Base_Reg = Reg;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000112 }
Dan Gohman4e3e3de2009-02-07 00:43:41 +0000113
Manman Ren19f49ac2012-09-11 22:23:19 +0000114#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesendafdbf72008-08-11 23:46:25 +0000115 void dump() {
David Greenedbdb1b22010-01-05 01:29:08 +0000116 dbgs() << "X86ISelAddressMode " << this << '\n';
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000117 dbgs() << "Base_Reg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000118 if (Base_Reg.getNode())
Chad Rosier24c19d22012-08-01 18:39:17 +0000119 Base_Reg.getNode()->dump();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000120 else
David Greenedbdb1b22010-01-05 01:29:08 +0000121 dbgs() << "nul";
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000122 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000123 << " Scale" << Scale << '\n'
124 << "IndexReg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000125 if (IndexReg.getNode())
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000126 IndexReg.getNode()->dump();
127 else
Chad Rosier24c19d22012-08-01 18:39:17 +0000128 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000129 dbgs() << " Disp " << Disp << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000130 << "GV ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000131 if (GV)
132 GV->dump();
133 else
David Greenedbdb1b22010-01-05 01:29:08 +0000134 dbgs() << "nul";
135 dbgs() << " CP ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000136 if (CP)
137 CP->dump();
138 else
David Greenedbdb1b22010-01-05 01:29:08 +0000139 dbgs() << "nul";
140 dbgs() << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000141 << "ES ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000142 if (ES)
David Greenedbdb1b22010-01-05 01:29:08 +0000143 dbgs() << ES;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000144 else
David Greenedbdb1b22010-01-05 01:29:08 +0000145 dbgs() << "nul";
Rafael Espindola36b718f2015-06-22 17:46:53 +0000146 dbgs() << " MCSym ";
147 if (MCSym)
148 dbgs() << MCSym;
149 else
150 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000151 dbgs() << " JT" << JT << " Align" << Align << '\n';
Dale Johannesendafdbf72008-08-11 23:46:25 +0000152 }
Manman Ren742534c2012-09-06 19:06:06 +0000153#endif
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000154 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000155}
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000156
157namespace {
Chris Lattner655e7df2005-11-16 01:54:32 +0000158 //===--------------------------------------------------------------------===//
Sanjay Patelb5723d02015-10-13 15:12:27 +0000159 /// ISel - X86-specific code to select X86 machine instructions for
Chris Lattner655e7df2005-11-16 01:54:32 +0000160 /// SelectionDAG operations.
161 ///
Craig Topper26eec092014-03-31 06:22:15 +0000162 class X86DAGToDAGISel final : public SelectionDAGISel {
Sanjay Patelb5723d02015-10-13 15:12:27 +0000163 /// Keep a pointer to the X86Subtarget around so that we can
Chris Lattner655e7df2005-11-16 01:54:32 +0000164 /// make the right decision when generating code for different targets.
165 const X86Subtarget *Subtarget;
Evan Cheng5588de92006-02-18 00:15:05 +0000166
Sanjay Patelb5723d02015-10-13 15:12:27 +0000167 /// If true, selector should try to optimize for code size instead of
168 /// performance.
Evan Cheng7d6fa972008-09-26 23:41:32 +0000169 bool OptForSize;
170
Hans Wennborg4ae51192016-03-25 01:10:56 +0000171 /// If true, selector should try to optimize for minimum code size.
172 bool OptForMinSize;
173
Jatin Bhateja908c8b32017-09-15 05:29:51 +0000174 /// If true, selector should try to aggresively fold operands into AM.
175 bool OptForAggressingFolding;
176
Chris Lattner655e7df2005-11-16 01:54:32 +0000177 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000178 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Hans Wennborg4ae51192016-03-25 01:10:56 +0000179 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
Jatin Bhateja908c8b32017-09-15 05:29:51 +0000180 OptForMinSize(false), OptForAggressingFolding(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000181
Mehdi Amini117296c2016-10-01 02:56:57 +0000182 StringRef getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000183 return "X86 DAG->DAG Instruction Selection";
184 }
185
Eric Christopher4f09c592014-05-22 01:53:26 +0000186 bool runOnMachineFunction(MachineFunction &MF) override {
187 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000188 Subtarget = &MF.getSubtarget<X86Subtarget>();
Eric Christopher4f09c592014-05-22 01:53:26 +0000189 SelectionDAGISel::runOnMachineFunction(MF);
190 return true;
191 }
192
Craig Topper2d9361e2014-03-09 07:44:38 +0000193 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000194
Craig Topper2d9361e2014-03-09 07:44:38 +0000195 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000196
Craig Topper2d9361e2014-03-09 07:44:38 +0000197 void PreprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000198
Jatin Bhateja908c8b32017-09-15 05:29:51 +0000199 void setAggressiveOperandFolding(bool val = false) {
200 OptForAggressingFolding = val;
201 }
202
203 bool getAggressiveOperandFolding() { return OptForAggressingFolding; }
204
Chris Lattner655e7df2005-11-16 01:54:32 +0000205// Include the pieces autogenerated from the target description.
206#include "X86GenDAGISel.inc"
207
208 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000209 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000210
Sanjay Patel85030aa2015-10-13 16:23:00 +0000211 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
212 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
213 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
214 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000215 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000216 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000217 unsigned Depth);
Jatin Bhateja908c8b32017-09-15 05:29:51 +0000218 bool matchAddressLEA(SDValue N, X86ISelAddressMode &AM);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000219 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
220 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000221 SDValue &Scale, SDValue &Index, SDValue &Disp,
222 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000223 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000224 SDValue &Scale, SDValue &Index, SDValue &Disp,
225 SDValue &Segment);
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +0000226 template <class GatherScatterSDNode>
227 bool selectAddrOfGatherScatterNode(GatherScatterSDNode *Parent, SDValue N,
228 SDValue &Base, SDValue &Scale,
229 SDValue &Index, SDValue &Disp,
230 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000231 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
232 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000233 SDValue &Scale, SDValue &Index, SDValue &Disp,
234 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000235 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000236 SDValue &Scale, SDValue &Index, SDValue &Disp,
237 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000238 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000239 SDValue &Scale, SDValue &Index, SDValue &Disp,
240 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000241 bool selectScalarSSELoad(SDNode *Root, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000242 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000243 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000244 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000245 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000246 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000247
Sanjay Patel85030aa2015-10-13 16:23:00 +0000248 bool tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000249 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000250 SDValue &Index, SDValue &Disp,
251 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000252
Sanjay Patelb5723d02015-10-13 15:12:27 +0000253 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000254 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000255 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000256 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000257
Sanjay Patel85030aa2015-10-13 16:23:00 +0000258 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000259
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000260 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000261 SDValue &Base, SDValue &Scale,
262 SDValue &Index, SDValue &Disp,
263 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000264 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000265 ? CurDAG->getTargetFrameIndex(
266 AM.Base_FrameIndex,
267 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000268 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000269 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000270 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000271 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000272 // is 32-bit.
273 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000274 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000275 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000276 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000277 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000278 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000279 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000280 else if (AM.ES) {
281 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000282 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000283 } else if (AM.MCSym) {
284 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
285 assert(AM.SymbolFlags == 0 && "oo");
286 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000287 } else if (AM.JT != -1) {
288 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000289 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000290 } else if (AM.BlockAddr)
291 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
292 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000293 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000294 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000295
296 if (AM.Segment.getNode())
297 Segment = AM.Segment;
298 else
Owen Anderson9f944592009-08-11 20:47:22 +0000299 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000300 }
301
Michael Kuperstein243c0732015-08-11 14:10:58 +0000302 // Utility function to determine whether we should avoid selecting
303 // immediate forms of instructions for better code size or not.
304 // At a high level, we'd like to avoid such instructions when
305 // we have similar constants used within the same basic block
306 // that can be kept in a register.
307 //
308 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
309 uint32_t UseCount = 0;
310
311 // Do not want to hoist if we're not optimizing for size.
312 // TODO: We'd like to remove this restriction.
313 // See the comment in X86InstrInfo.td for more info.
314 if (!OptForSize)
315 return false;
316
317 // Walk all the users of the immediate.
318 for (SDNode::use_iterator UI = N->use_begin(),
319 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000320
Michael Kuperstein243c0732015-08-11 14:10:58 +0000321 SDNode *User = *UI;
322
323 // This user is already selected. Count it as a legitimate use and
324 // move on.
325 if (User->isMachineOpcode()) {
326 UseCount++;
327 continue;
328 }
329
330 // We want to count stores of immediates as real uses.
331 if (User->getOpcode() == ISD::STORE &&
332 User->getOperand(1).getNode() == N) {
333 UseCount++;
334 continue;
335 }
336
337 // We don't currently match users that have > 2 operands (except
338 // for stores, which are handled above)
339 // Those instruction won't match in ISEL, for now, and would
340 // be counted incorrectly.
341 // This may change in the future as we add additional instruction
342 // types.
343 if (User->getNumOperands() != 2)
344 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000345
Michael Kuperstein243c0732015-08-11 14:10:58 +0000346 // Immediates that are used for offsets as part of stack
347 // manipulation should be left alone. These are typically
348 // used to indicate SP offsets for argument passing and
349 // will get pulled into stores/pushes (implicitly).
350 if (User->getOpcode() == X86ISD::ADD ||
351 User->getOpcode() == ISD::ADD ||
352 User->getOpcode() == X86ISD::SUB ||
353 User->getOpcode() == ISD::SUB) {
354
355 // Find the other operand of the add/sub.
356 SDValue OtherOp = User->getOperand(0);
357 if (OtherOp.getNode() == N)
358 OtherOp = User->getOperand(1);
359
360 // Don't count if the other operand is SP.
361 RegisterSDNode *RegNode;
362 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
363 (RegNode = dyn_cast_or_null<RegisterSDNode>(
364 OtherOp->getOperand(1).getNode())))
365 if ((RegNode->getReg() == X86::ESP) ||
366 (RegNode->getReg() == X86::RSP))
367 continue;
368 }
369
370 // ... otherwise, count this and move on.
371 UseCount++;
372 }
373
374 // If we have more than 1 use, then recommend for hoisting.
375 return (UseCount > 1);
376 }
377
Sanjay Patelb5723d02015-10-13 15:12:27 +0000378 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000379 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000380 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000381 }
382
Sanjay Patelb5723d02015-10-13 15:12:27 +0000383 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000384 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000385 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000386 }
Evan Chengd49cc362006-02-10 22:24:32 +0000387
Sanjay Patelb5723d02015-10-13 15:12:27 +0000388 /// Return an SDNode that returns the value of the global base register.
389 /// Output instructions required to initialize the global base register,
390 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000391 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000392
Sanjay Patelb5723d02015-10-13 15:12:27 +0000393 /// Return a reference to the TargetMachine, casted to the target-specific
394 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000395 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000396 return static_cast<const X86TargetMachine &>(TM);
397 }
398
Sanjay Patelb5723d02015-10-13 15:12:27 +0000399 /// Return a reference to the TargetInstrInfo, casted to the target-specific
400 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000401 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000402 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000403 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000404
405 /// \brief Address-mode matching performs shift-of-and to and-of-shift
406 /// reassociation in order to expose more scaled addressing
407 /// opportunities.
408 bool ComplexPatternFuncMutatesDAG() const override {
409 return true;
410 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000411
412 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
413
414 /// Returns whether this is a relocatable immediate in the range
415 /// [-2^Width .. 2^Width-1].
416 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
417 if (auto *CN = dyn_cast<ConstantSDNode>(N))
418 return isInt<Width>(CN->getSExtValue());
419 return isSExtAbsoluteSymbolRef(Width, N);
420 }
Craig Topper4de6f582017-08-19 23:21:22 +0000421
422 // Indicates we should prefer to use a non-temporal load for this load.
423 bool useNonTemporalLoad(LoadSDNode *N) const {
424 if (!N->isNonTemporal())
425 return false;
426
427 unsigned StoreSize = N->getMemoryVT().getStoreSize();
428
429 if (N->getAlignment() < StoreSize)
430 return false;
431
432 switch (StoreSize) {
433 default: llvm_unreachable("Unsupported store size");
434 case 16:
435 return Subtarget->hasSSE41();
436 case 32:
437 return Subtarget->hasAVX2();
438 case 64:
439 return Subtarget->hasAVX512();
440 }
441 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000442
443 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000444
445 bool matchBEXTRFromAnd(SDNode *Node);
Chris Lattner655e7df2005-11-16 01:54:32 +0000446 };
Jatin Bhateja908c8b32017-09-15 05:29:51 +0000447
448 class X86AggressiveOperandFolding {
449 public:
450 explicit X86AggressiveOperandFolding(X86DAGToDAGISel &ISel, bool val)
451 : Selector(&ISel) {
452 Selector->setAggressiveOperandFolding(val);
453 }
454 ~X86AggressiveOperandFolding() {
455 Selector->setAggressiveOperandFolding(false);
456 }
457
458 private:
459 X86DAGToDAGISel *Selector;
460 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000461}
462
Evan Cheng72bb66a2006-08-08 00:31:00 +0000463
Evan Cheng5e73ff22010-02-15 19:41:07 +0000464bool
465X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000466 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000467
Evan Cheng5e73ff22010-02-15 19:41:07 +0000468 if (!N.hasOneUse())
469 return false;
470
471 if (N.getOpcode() != ISD::LOAD)
472 return true;
473
474 // If N is a load, do additional profitability checks.
475 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000476 switch (U->getOpcode()) {
477 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000478 case X86ISD::ADD:
479 case X86ISD::SUB:
480 case X86ISD::AND:
481 case X86ISD::XOR:
482 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000483 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000484 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000485 case ISD::AND:
486 case ISD::OR:
487 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000488 SDValue Op1 = U->getOperand(1);
489
Evan Cheng83bdb382008-11-27 00:49:46 +0000490 // If the other operand is a 8-bit immediate we should fold the immediate
491 // instead. This reduces code size.
492 // e.g.
493 // movl 4(%esp), %eax
494 // addl $4, %eax
495 // vs.
496 // movl $4, %eax
497 // addl 4(%esp), %eax
498 // The former is 2 bytes shorter. In case where the increment is 1, then
499 // the saving can be 4 bytes (by using incl %eax).
Rafael Espindolabb834f02009-04-10 10:09:34 +0000500 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
Dan Gohman2293eb62009-03-14 02:07:16 +0000501 if (Imm->getAPIntValue().isSignedIntN(8))
502 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000503
504 // If the other operand is a TLS address, we should fold it instead.
505 // This produces
506 // movl %gs:0, %eax
507 // leal i@NTPOFF(%eax), %eax
508 // instead of
509 // movl $i@NTPOFF, %eax
510 // addl %gs:0, %eax
511 // if the block also has an access to a second TLS address this will save
512 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000513 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000514 if (Op1.getOpcode() == X86ISD::Wrapper) {
515 SDValue Val = Op1.getOperand(0);
516 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
517 return false;
518 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000519 }
520 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000521 }
522
523 return true;
524}
525
Sanjay Patelb5723d02015-10-13 15:12:27 +0000526/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000527/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000528static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
529 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000530 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000531 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000532 if (Chain.getNode() == Load.getNode())
533 Ops.push_back(Load.getOperand(0));
534 else {
535 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000536 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000537 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
538 if (Chain.getOperand(i).getNode() == Load.getNode())
539 Ops.push_back(Load.getOperand(0));
540 else
541 Ops.push_back(Chain.getOperand(i));
542 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000543 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000544 Ops.clear();
545 Ops.push_back(NewChain);
546 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000547 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000548 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000549 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000550 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000551
Evan Chengf00f1e52008-08-25 21:27:18 +0000552 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000553 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000554 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000555 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000556}
557
Sanjay Patelb5723d02015-10-13 15:12:27 +0000558/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000559/// moved below CALLSEQ_START and the chains leading up to the call.
560/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000561/// In the case of a tail call, there isn't a callseq node between the call
562/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000563static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000564 // The transformation is somewhat dangerous if the call's chain was glued to
565 // the call. After MoveBelowOrigChain the load is moved between the call and
566 // the chain, this can create a cycle if the load is not folded. So it is
567 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000568 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000569 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000570 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000571 if (!LD ||
572 LD->isVolatile() ||
573 LD->getAddressingMode() != ISD::UNINDEXED ||
574 LD->getExtensionType() != ISD::NON_EXTLOAD)
575 return false;
576
577 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000578 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000579 if (!Chain.hasOneUse())
580 return false;
581 Chain = Chain.getOperand(0);
582 }
Evan Chengd703df62010-03-14 03:48:46 +0000583
584 if (!Chain.getNumOperands())
585 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000586 // Since we are not checking for AA here, conservatively abort if the chain
587 // writes to memory. It's not safe to move the callee (a load) across a store.
588 if (isa<MemSDNode>(Chain.getNode()) &&
589 cast<MemSDNode>(Chain.getNode())->writeMem())
590 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000591 if (Chain.getOperand(0).getNode() == Callee.getNode())
592 return true;
593 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000594 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
595 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000596 return true;
597 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000598}
599
Chris Lattner8d637042010-03-02 23:12:51 +0000600void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000601 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Sanjay Patel68b03252015-08-10 16:47:47 +0000602 OptForSize = MF->getFunction()->optForSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000603 OptForMinSize = MF->getFunction()->optForMinSize();
604 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000605
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000606 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
607 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000608 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000609
Evan Chengd703df62010-03-14 03:48:46 +0000610 if (OptLevel != CodeGenOpt::None &&
Michael Liao96b42602013-03-28 23:13:21 +0000611 // Only does this when target favors doesn't favor register indirect
612 // call.
Craig Topper62c47a22017-08-29 05:14:27 +0000613 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000614 (N->getOpcode() == X86ISD::TC_RETURN &&
Nick Lewyckyf41a80e2013-01-13 19:03:55 +0000615 // Only does this if load can be folded into TC_RETURN.
Evan Cheng847ad442012-10-05 01:48:22 +0000616 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000617 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000618 /// Also try moving call address load from outside callseq_start to just
619 /// before the call to allow it to be folded.
620 ///
621 /// [Load chain]
622 /// ^
623 /// |
624 /// [Load]
625 /// ^ ^
626 /// | |
627 /// / \--
628 /// / |
629 ///[CALLSEQ_START] |
630 /// ^ |
631 /// | |
632 /// [LOAD/C2Reg] |
633 /// | |
634 /// \ /
635 /// \ /
636 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000637 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000638 SDValue Chain = N->getOperand(0);
639 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000640 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000641 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000642 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000643 ++NumLoadMoved;
644 continue;
645 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000646
Chris Lattner8d637042010-03-02 23:12:51 +0000647 // Lower fpround and fpextend nodes that target the FP stack to be store and
648 // load to the stack. This is a gross hack. We would like to simply mark
649 // these as being illegal, but when we do that, legalize produces these when
650 // it expands calls, then expands these in the same legalize pass. We would
651 // like dag combine to be able to hack on these between the call expansion
652 // and the node legalization. As such this pass basically does "really
653 // late" legalization of these inline with the X86 isel pass.
654 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000655 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
656 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000657
Craig Topper83e042a2013-08-15 05:57:07 +0000658 MVT SrcVT = N->getOperand(0).getSimpleValueType();
659 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000660
661 // If any of the sources are vectors, no fp stack involved.
662 if (SrcVT.isVector() || DstVT.isVector())
663 continue;
664
665 // If the source and destination are SSE registers, then this is a legal
666 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000667 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000668 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000669 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
670 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000671 if (SrcIsSSE && DstIsSSE)
672 continue;
673
Chris Lattnerd587e582008-03-09 07:05:32 +0000674 if (!SrcIsSSE && !DstIsSSE) {
675 // If this is an FPStack extension, it is a noop.
676 if (N->getOpcode() == ISD::FP_EXTEND)
677 continue;
678 // If this is a value-preserving FPStack truncation, it is a noop.
679 if (N->getConstantOperandVal(1))
680 continue;
681 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000682
Chris Lattnera91f77e2008-01-24 08:07:48 +0000683 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
684 // FPStack has extload and truncstore. SSE can fold direct loads into other
685 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000686 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000687 if (N->getOpcode() == ISD::FP_ROUND)
688 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
689 else
690 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000691
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000692 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000693 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000694
Chris Lattnera91f77e2008-01-24 08:07:48 +0000695 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000696 SDValue Store =
697 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
698 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000699 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000700 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000701
702 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
703 // extload we created. This will cause general havok on the dag because
704 // anything below the conversion could be folded into other existing nodes.
705 // To avoid invalidating 'I', back it up to the convert node.
706 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000707 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000708
Chris Lattnera91f77e2008-01-24 08:07:48 +0000709 // Now that we did that, the node is dead. Increment the iterator to the
710 // next node to process, then delete N.
711 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000712 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000713 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000714}
715
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000716
Sanjay Patelb5723d02015-10-13 15:12:27 +0000717/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000718void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000719 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000720 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000721 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000722
723 TargetLowering::CallLoweringInfo CLI(*CurDAG);
724 CLI.setChain(CurDAG->getRoot())
725 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000726 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000727 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000728 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
729 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
730 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000731 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000732}
733
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000734void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000735 // If this is main, emit special code for main.
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000736 if (const Function *Fn = MF->getFunction())
737 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
Sanjay Patel85030aa2015-10-13 16:23:00 +0000738 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000739}
740
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000741static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000742 // On 64-bit platforms, we can run into an issue where a frame index
743 // includes a displacement that, when added to the explicit displacement,
744 // will overflow the displacement field. Assuming that the frame index
745 // displacement fits into a 31-bit integer (which is only slightly more
746 // aggressive than the current fundamental assumption that it fits into
747 // a 32-bit integer), a 31-bit disp should always be safe.
748 return isInt<31>(Val);
749}
750
Sanjay Patel85030aa2015-10-13 16:23:00 +0000751bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000752 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000753 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000754 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000755 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000756 int64_t Val = AM.Disp + Offset;
757 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000758 if (Subtarget->is64Bit()) {
759 if (!X86::isOffsetSuitableForCodeModel(Val, M,
760 AM.hasSymbolicDisplacement()))
761 return true;
762 // In addition to the checks required for a register base, check that
763 // we do not try to use an unsafe Disp with a frame index.
764 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
765 !isDispSafeForFrameIndex(Val))
766 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000767 }
Eli Friedman344ec792011-07-13 21:29:53 +0000768 AM.Disp = Val;
769 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000770
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000771}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000772
Sanjay Patel85030aa2015-10-13 16:23:00 +0000773bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000774 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000775
Chris Lattner8a236b62010-09-22 04:39:11 +0000776 // load gs:0 -> GS segment register.
777 // load fs:0 -> FS segment register.
778 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000779 // This optimization is valid because the GNU TLS model defines that
780 // gs:0 (or fs:0 on X86-64) contains its own address.
781 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000782 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000783 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000784 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
785 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000786 switch (N->getPointerInfo().getAddrSpace()) {
787 case 256:
788 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
789 return false;
790 case 257:
791 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
792 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000793 // Address space 258 is not handled here, because it is not used to
794 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000795 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000796
Rafael Espindola3b2df102009-04-08 21:14:34 +0000797 return true;
798}
799
Sanjay Patelb5723d02015-10-13 15:12:27 +0000800/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
801/// mode. These wrap things that will resolve down into a symbol reference.
802/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000803bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000804 // If the addressing mode already has a symbol as the displacement, we can
805 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000806 if (AM.hasSymbolicDisplacement())
807 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000808
809 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000810 CodeModel::Model M = TM.getCodeModel();
811
Chris Lattnerfea81da2009-06-27 04:16:01 +0000812 // Handle X86-64 rip-relative addresses. We check this before checking direct
813 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000814 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000815 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
816 // they cannot be folded into immediate fields.
817 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000818 (M == CodeModel::Small || M == CodeModel::Kernel)) {
819 // Base and index reg must be 0 in order to use %rip as base.
820 if (AM.hasBaseOrIndexReg())
821 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000822 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000823 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000824 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000825 AM.SymbolFlags = G->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000826 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000827 AM = Backup;
828 return true;
829 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000830 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000831 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000832 AM.CP = CP->getConstVal();
833 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000834 AM.SymbolFlags = CP->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000835 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000836 AM = Backup;
837 return true;
838 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000839 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
840 AM.ES = S->getSymbol();
841 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000842 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
843 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000844 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000845 AM.JT = J->getIndex();
846 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000847 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
848 X86ISelAddressMode Backup = AM;
849 AM.BlockAddr = BA->getBlockAddress();
850 AM.SymbolFlags = BA->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000851 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
Michael Liaoabb87d42012-09-12 21:43:09 +0000852 AM = Backup;
853 return true;
854 }
855 } else
856 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000857
Chris Lattnerfea81da2009-06-27 04:16:01 +0000858 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000859 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000860 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000861 }
862
863 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000864 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
865 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000866 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000867 M == CodeModel::Small || M == CodeModel::Kernel) {
868 assert(N.getOpcode() != X86ISD::WrapperRIP &&
869 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000870 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
871 AM.GV = G->getGlobal();
872 AM.Disp += G->getOffset();
873 AM.SymbolFlags = G->getTargetFlags();
874 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
875 AM.CP = CP->getConstVal();
876 AM.Align = CP->getAlignment();
877 AM.Disp += CP->getOffset();
878 AM.SymbolFlags = CP->getTargetFlags();
879 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
880 AM.ES = S->getSymbol();
881 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000882 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
883 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000884 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000885 AM.JT = J->getIndex();
886 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000887 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
888 AM.BlockAddr = BA->getBlockAddress();
889 AM.Disp += BA->getOffset();
890 AM.SymbolFlags = BA->getTargetFlags();
891 } else
892 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000893 return false;
894 }
895
896 return true;
897}
898
Sanjay Patelb5723d02015-10-13 15:12:27 +0000899/// Add the specified node to the specified addressing mode, returning true if
900/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000901bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
902 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +0000903 return true;
904
905 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
906 // a smaller encoding and avoids a scaled-index.
907 if (AM.Scale == 2 &&
908 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000909 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000910 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +0000911 AM.Scale = 1;
912 }
913
Dan Gohman05046082009-08-20 18:23:44 +0000914 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
915 // because it has a smaller encoding.
916 // TODO: Which other code models can use this?
917 if (TM.getCodeModel() == CodeModel::Small &&
918 Subtarget->is64Bit() &&
919 AM.Scale == 1 &&
920 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000921 AM.Base_Reg.getNode() == nullptr &&
922 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +0000923 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +0000924 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000925 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +0000926
Dan Gohman824ab402009-07-22 23:26:55 +0000927 return false;
928}
929
Sanjay Patelefab8b02015-10-21 18:56:06 +0000930bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
931 unsigned Depth) {
932 // Add an artificial use to this node so that we can keep track of
933 // it if it gets CSE'd with a different node.
934 HandleSDNode Handle(N);
935
936 X86ISelAddressMode Backup = AM;
937 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
938 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
939 return false;
940 AM = Backup;
941
942 // Try again after commuting the operands.
943 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
944 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
945 return false;
946 AM = Backup;
947
948 // If we couldn't fold both operands into the address at the same time,
949 // see if we can just put each operand into a register and fold at least
950 // the add.
951 if (AM.BaseType == X86ISelAddressMode::RegBase &&
952 !AM.Base_Reg.getNode() &&
953 !AM.IndexReg.getNode()) {
954 N = Handle.getValue();
955 AM.Base_Reg = N.getOperand(0);
956 AM.IndexReg = N.getOperand(1);
957 AM.Scale = 1;
958 return false;
959 }
960 N = Handle.getValue();
961 return true;
962}
963
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000964// Insert a node into the DAG at least before the Pos node's position. This
965// will reposition the node as needed, and will assign it a node ID that is <=
966// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
967// IDs! The selection DAG must no longer depend on their uniqueness when this
968// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000969static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000970 if (N.getNode()->getNodeId() == -1 ||
971 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000972 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000973 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
974 }
975}
976
Adam Nemet0c7caf42014-09-16 17:14:10 +0000977// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
978// safe. This allows us to convert the shift and and into an h-register
979// extract and a scaled index. Returns false if the simplification is
980// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000981static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
982 uint64_t Mask,
983 SDValue Shift, SDValue X,
984 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +0000985 if (Shift.getOpcode() != ISD::SRL ||
986 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
987 !Shift.hasOneUse())
988 return true;
989
990 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
991 if (ScaleLog <= 0 || ScaleLog >= 4 ||
992 Mask != (0xffu << ScaleLog))
993 return true;
994
Craig Topper83e042a2013-08-15 05:57:07 +0000995 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000996 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000997 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
998 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +0000999 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1000 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001001 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001002 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1003
Chandler Carrutheb21da02012-01-12 01:34:44 +00001004 // Insert the new nodes into the topological ordering. We must do this in
1005 // a valid topological ordering as nothing is going to go back and re-sort
1006 // these nodes. We continually insert before 'N' in sequence as this is
1007 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1008 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001009 insertDAGNode(DAG, N, Eight);
1010 insertDAGNode(DAG, N, Srl);
1011 insertDAGNode(DAG, N, NewMask);
1012 insertDAGNode(DAG, N, And);
1013 insertDAGNode(DAG, N, ShlCount);
1014 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001015 DAG.ReplaceAllUsesWith(N, Shl);
1016 AM.IndexReg = And;
1017 AM.Scale = (1 << ScaleLog);
1018 return false;
1019}
1020
Chandler Carruthaa01e662012-01-11 09:35:00 +00001021// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1022// allows us to fold the shift into this addressing mode. Returns false if the
1023// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001024static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1025 uint64_t Mask,
1026 SDValue Shift, SDValue X,
1027 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001028 if (Shift.getOpcode() != ISD::SHL ||
1029 !isa<ConstantSDNode>(Shift.getOperand(1)))
1030 return true;
1031
1032 // Not likely to be profitable if either the AND or SHIFT node has more
1033 // than one use (unless all uses are for address computation). Besides,
1034 // isel mechanism requires their node ids to be reused.
1035 if (!N.hasOneUse() || !Shift.hasOneUse())
1036 return true;
1037
1038 // Verify that the shift amount is something we can fold.
1039 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1040 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1041 return true;
1042
Craig Topper83e042a2013-08-15 05:57:07 +00001043 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001044 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001045 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001046 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1047 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1048
Chandler Carrutheb21da02012-01-12 01:34:44 +00001049 // Insert the new nodes into the topological ordering. We must do this in
1050 // a valid topological ordering as nothing is going to go back and re-sort
1051 // these nodes. We continually insert before 'N' in sequence as this is
1052 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1053 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001054 insertDAGNode(DAG, N, NewMask);
1055 insertDAGNode(DAG, N, NewAnd);
1056 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001057 DAG.ReplaceAllUsesWith(N, NewShift);
1058
1059 AM.Scale = 1 << ShiftAmt;
1060 AM.IndexReg = NewAnd;
1061 return false;
1062}
1063
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001064// Implement some heroics to detect shifts of masked values where the mask can
1065// be replaced by extending the shift and undoing that in the addressing mode
1066// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1067// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1068// the addressing mode. This results in code such as:
1069//
1070// int f(short *y, int *lookup_table) {
1071// ...
1072// return *y + lookup_table[*y >> 11];
1073// }
1074//
1075// Turning into:
1076// movzwl (%rdi), %eax
1077// movl %eax, %ecx
1078// shrl $11, %ecx
1079// addl (%rsi,%rcx,4), %eax
1080//
1081// Instead of:
1082// movzwl (%rdi), %eax
1083// movl %eax, %ecx
1084// shrl $9, %ecx
1085// andl $124, %rcx
1086// addl (%rsi,%rcx), %eax
1087//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001088// Note that this function assumes the mask is provided as a mask *after* the
1089// value is shifted. The input chain may or may not match that, but computing
1090// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001091static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1092 uint64_t Mask,
1093 SDValue Shift, SDValue X,
1094 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001095 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1096 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001097 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001098
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001099 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001100 unsigned MaskLZ = countLeadingZeros(Mask);
1101 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001102
1103 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001104 // from the trailing zeros of the mask.
1105 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001106
1107 // There is nothing we can do here unless the mask is removing some bits.
1108 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1109 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1110
1111 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001112 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001113
1114 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001115 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001116 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1117 if (MaskLZ < ScaleDown)
1118 return true;
1119 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001120
1121 // The final check is to ensure that any masked out high bits of X are
1122 // already known to be zero. Otherwise, the mask has a semantic impact
1123 // other than masking out a couple of low bits. Unfortunately, because of
1124 // the mask, zero extensions will be removed from operands in some cases.
1125 // This code works extra hard to look through extensions because we can
1126 // replace them with zero extensions cheaply if necessary.
1127 bool ReplacingAnyExtend = false;
1128 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001129 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1130 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001131 // Assume that we'll replace the any-extend with a zero-extend, and
1132 // narrow the search to the extended value.
1133 X = X.getOperand(0);
1134 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1135 ReplacingAnyExtend = true;
1136 }
Craig Topper83e042a2013-08-15 05:57:07 +00001137 APInt MaskedHighBits =
1138 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001139 KnownBits Known;
1140 DAG.computeKnownBits(X, Known);
1141 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001142
1143 // We've identified a pattern that can be transformed into a single shift
1144 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001145 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001146 if (ReplacingAnyExtend) {
1147 assert(X.getValueType() != VT);
1148 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001149 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001150 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001151 X = NewX;
1152 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001153 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001154 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001155 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001156 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001157 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001158
1159 // Insert the new nodes into the topological ordering. We must do this in
1160 // a valid topological ordering as nothing is going to go back and re-sort
1161 // these nodes. We continually insert before 'N' in sequence as this is
1162 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1163 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001164 insertDAGNode(DAG, N, NewSRLAmt);
1165 insertDAGNode(DAG, N, NewSRL);
1166 insertDAGNode(DAG, N, NewSHLAmt);
1167 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001168 DAG.ReplaceAllUsesWith(N, NewSHL);
1169
1170 AM.Scale = 1 << AMShiftAmt;
1171 AM.IndexReg = NewSRL;
1172 return false;
1173}
Jatin Bhateja908c8b32017-09-15 05:29:51 +00001174
Sanjay Patel85030aa2015-10-13 16:23:00 +00001175bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001176 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001177 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001178 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001179 dbgs() << "MatchAddress: ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001180 AM.dump();
1181 });
Jatin Bhateja908c8b32017-09-15 05:29:51 +00001182
1183 // Limit recursion. For aggressive operand folding recurse
1184 // till depth 8 which is the maximum legal scale value.
1185 unsigned MaxDepth = getAggressiveOperandFolding() ? 8 : 5;
1186 if (Depth > MaxDepth)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001187 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001188
Chris Lattnerfea81da2009-06-27 04:16:01 +00001189 // If this is already a %rip relative address, we can only merge immediates
1190 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001191 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001192 if (AM.isRIPRelative()) {
1193 // FIXME: JumpTable and ExternalSymbol address currently don't like
1194 // displacements. It isn't very important, but this should be fixed for
1195 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001196 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1197 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001198
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001199 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001200 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001201 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001202 return true;
1203 }
1204
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001205 switch (N.getOpcode()) {
1206 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001207 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001208 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001209 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1210 // Use the symbol and don't prefix it.
1211 AM.MCSym = ESNode->getMCSymbol();
1212 return false;
1213 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001214 break;
1215 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001216 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001217 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001218 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001219 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001220 break;
1221 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001222
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001223 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001224 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001225 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001226 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001227 break;
1228
Rafael Espindola3b2df102009-04-08 21:14:34 +00001229 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001230 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001231 return false;
1232 break;
1233
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001234 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001235 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001236 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001237 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001238 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001239 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001240 return false;
1241 }
1242 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001243
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001244 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001245 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001246 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001247
Simon Pilgrim7f032312017-05-12 13:08:45 +00001248 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001249 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001250 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1251 // that the base operand remains free for further matching. If
1252 // the base doesn't end up getting used, a post-processing step
1253 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001254 if (Val == 1 || Val == 2 || Val == 3) {
1255 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001256 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001257
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001258 // Okay, we know that we have a scale by now. However, if the scaled
1259 // value is an add of something and a constant, we can fold the
1260 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001261 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001262 AM.IndexReg = ShVal.getOperand(0);
1263 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001264 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001265 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001266 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001267 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001268
1269 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001270 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001271 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001272 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001273 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001274
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001275 case ISD::SRL: {
1276 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001277 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001278
1279 SDValue And = N.getOperand(0);
1280 if (And.getOpcode() != ISD::AND) break;
1281 SDValue X = And.getOperand(0);
1282
1283 // We only handle up to 64-bit values here as those are what matter for
1284 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001285 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001286
1287 // The mask used for the transform is expected to be post-shift, but we
1288 // found the shift first so just apply the shift to the mask before passing
1289 // it down.
1290 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1291 !isa<ConstantSDNode>(And.getOperand(1)))
1292 break;
1293 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1294
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001295 // Try to fold the mask and shift into the scale, and return false if we
1296 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001297 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001298 return false;
1299 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001300 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001301
Dan Gohmanbf474952007-10-22 20:22:24 +00001302 case ISD::SMUL_LOHI:
1303 case ISD::UMUL_LOHI:
1304 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001305 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001306 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001307 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001308 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001309 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001310 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001311 AM.Base_Reg.getNode() == nullptr &&
1312 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001313 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001314 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1315 CN->getZExtValue() == 9) {
1316 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001317
Simon Pilgrim7f032312017-05-12 13:08:45 +00001318 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001319 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001320
1321 // Okay, we know that we have a scale by now. However, if the scaled
1322 // value is an add of something and a constant, we can fold the
1323 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001324 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001325 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1326 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001327 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001328 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001329 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001330 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001331 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001332 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001333 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001334 }
1335
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001336 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001337 return false;
1338 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001339 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001340 break;
1341
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001342 case ISD::SUB: {
1343 // Given A-B, if A can be completely folded into the address and
1344 // the index field with the index field unused, use -B as the index.
1345 // This is a win if a has multiple parts that can be folded into
1346 // the address. Also, this saves a mov if the base register has
1347 // other uses, since it avoids a two-address sub instruction, however
1348 // it costs an additional mov if the index register has other uses.
1349
Dan Gohman99ba4da2010-06-18 01:24:29 +00001350 // Add an artificial use to this node so that we can keep track of
1351 // it if it gets CSE'd with a different node.
1352 HandleSDNode Handle(N);
1353
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001354 // Test if the LHS of the sub can be folded.
1355 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001356 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001357 AM = Backup;
1358 break;
1359 }
1360 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001361 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001362 AM = Backup;
1363 break;
1364 }
Evan Cheng68333f52010-03-17 23:58:35 +00001365
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001366 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001367 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001368 // If the RHS involves a register with multiple uses, this
1369 // transformation incurs an extra mov, due to the neg instruction
1370 // clobbering its operand.
1371 if (!RHS.getNode()->hasOneUse() ||
1372 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1373 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1374 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1375 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001376 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001377 ++Cost;
1378 // If the base is a register with multiple uses, this
1379 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001380 // FIXME: Don't rely on DELETED_NODEs.
1381 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1382 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001383 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001384 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1385 --Cost;
1386 // If the folded LHS was interesting, this transformation saves
1387 // address arithmetic.
1388 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1389 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1390 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1391 --Cost;
1392 // If it doesn't look like it may be an overall win, don't do it.
1393 if (Cost >= 0) {
1394 AM = Backup;
1395 break;
1396 }
1397
1398 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001399 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001400 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1401 AM.IndexReg = Neg;
1402 AM.Scale = 1;
1403
1404 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001405 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1406 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001407 return false;
1408 }
1409
Sanjay Patelefab8b02015-10-21 18:56:06 +00001410 case ISD::ADD:
1411 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001412 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001413 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001414
Sanjay Patel533c10c2015-11-09 23:31:38 +00001415 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001416 // We want to look through a transform in InstCombine and DAGCombiner that
1417 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001418 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001419 // An 'lea' can then be used to match the shift (multiply) and add:
1420 // and $1, %esi
1421 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001422 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1423 !matchAdd(N, AM, Depth))
1424 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001425 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001426
Evan Cheng827d30d2007-12-13 00:43:27 +00001427 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001428 // Perform some heroic transforms on an and of a constant-count shift
1429 // with a constant to enable use of the scaled offset field.
1430
Evan Cheng827d30d2007-12-13 00:43:27 +00001431 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001432 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001433
Chandler Carruthaa01e662012-01-11 09:35:00 +00001434 SDValue Shift = N.getOperand(0);
1435 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001436 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001437
1438 // We only handle up to 64-bit values here as those are what matter for
1439 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001440 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001441
Chandler Carruthb0049f42012-01-11 09:35:04 +00001442 if (!isa<ConstantSDNode>(N.getOperand(1)))
1443 break;
1444 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001445
Chandler Carruth51d30762012-01-11 08:48:20 +00001446 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001447 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001448 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001449
Chandler Carruth51d30762012-01-11 08:48:20 +00001450 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001451 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001452 return false;
1453
Chandler Carruthaa01e662012-01-11 09:35:00 +00001454 // Try to swap the mask and shift to place shifts which can be done as
1455 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001456 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001457 return false;
1458 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001459 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001460 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001461
Sanjay Patel85030aa2015-10-13 16:23:00 +00001462 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001463}
1464
Sanjay Patelb5723d02015-10-13 15:12:27 +00001465/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001466/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001467bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001468 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001469 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001470 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001471 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001472 AM.IndexReg = N;
1473 AM.Scale = 1;
1474 return false;
1475 }
1476
Jatin Bhateja908c8b32017-09-15 05:29:51 +00001477 if (OptLevel != CodeGenOpt::None && getAggressiveOperandFolding() &&
1478 AM.BaseType == X86ISelAddressMode::RegBase) {
1479 if (AM.Base_Reg == N) {
1480 SDValue Base_Reg = AM.Base_Reg;
1481 AM.Base_Reg = AM.IndexReg;
1482 AM.IndexReg = Base_Reg;
1483 AM.Scale++;
1484 return false;
1485 } else if (AM.IndexReg == N) {
1486 AM.Scale++;
1487 return false;
1488 }
1489 }
1490
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001491 // Otherwise, we cannot select it.
1492 return true;
1493 }
1494
1495 // Default, generate it as a register.
1496 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001497 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001498 return false;
1499}
1500
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001501template <class GatherScatterSDNode>
1502bool X86DAGToDAGISel::selectAddrOfGatherScatterNode(
1503 GatherScatterSDNode *Mgs, SDValue N, SDValue &Base, SDValue &Scale,
1504 SDValue &Index, SDValue &Disp, SDValue &Segment) {
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001505 X86ISelAddressMode AM;
1506 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001507 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001508 if (AddrSpace == 256)
1509 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1510 if (AddrSpace == 257)
1511 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001512 if (AddrSpace == 258)
1513 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001514
1515 SDLoc DL(N);
1516 Base = Mgs->getBasePtr();
1517 Index = Mgs->getIndex();
Sanjay Patel5f6bb6c2016-09-14 15:43:44 +00001518 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001519 Scale = getI8Imm(ScalarSize/8, DL);
1520
1521 // If Base is 0, the whole address is in index and the Scale is 1
Daniel Jasper232778a2015-04-30 09:01:21 +00001522 if (isa<ConstantSDNode>(Base)) {
Mehdi Amini42152362015-10-21 06:11:01 +00001523 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
Daniel Jasper232778a2015-04-30 09:01:21 +00001524 "Unexpected base in gather/scatter");
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001525 Scale = getI8Imm(1, DL);
1526 Base = CurDAG->getRegister(0, MVT::i32);
1527 }
1528 if (AM.Segment.getNode())
1529 Segment = AM.Segment;
1530 else
1531 Segment = CurDAG->getRegister(0, MVT::i32);
1532 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1533 return true;
1534}
1535
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001536bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1537 SDValue &Scale, SDValue &Index,
1538 SDValue &Disp, SDValue &Segment) {
1539 if (auto Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent))
1540 return selectAddrOfGatherScatterNode<MaskedGatherScatterSDNode>(
1541 Mgs, N, Base, Scale, Index, Disp, Segment);
1542 if (auto X86Gather = dyn_cast<X86MaskedGatherSDNode>(Parent))
1543 return selectAddrOfGatherScatterNode<X86MaskedGatherSDNode>(
1544 X86Gather, N, Base, Scale, Index, Disp, Segment);
1545 return false;
1546}
1547
Sanjay Patelb5723d02015-10-13 15:12:27 +00001548/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001549/// It returns the operands which make up the maximal addressing mode it can
1550/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001551///
1552/// Parent is the parent node of the addr operand that is being matched. It
1553/// is always a load, store, atomic node, or null. It is only null when
1554/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001555bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001556 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001557 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001558 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001559
Chris Lattner8a236b62010-09-22 04:39:11 +00001560 if (Parent &&
1561 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1562 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001563 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001564 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001565 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1566 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1567 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001568 unsigned AddrSpace =
1569 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001570 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001571 if (AddrSpace == 256)
1572 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1573 if (AddrSpace == 257)
1574 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001575 if (AddrSpace == 258)
1576 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001577 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001578
Sanjay Patel85030aa2015-10-13 16:23:00 +00001579 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001580 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001581
Craig Topper83e042a2013-08-15 05:57:07 +00001582 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001583 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001584 if (!AM.Base_Reg.getNode())
1585 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001586 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001587
Gabor Greiff304a7a2008-08-28 21:40:38 +00001588 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001589 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001590
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001591 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001592 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001593}
1594
Craig Topper8078dd22017-08-21 16:04:04 +00001595// We can only fold a load if all nodes between it and the root node have a
1596// single use. If there are additional uses, we could end up duplicating the
1597// load.
1598static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *N) {
1599 SDNode *User = *N->use_begin();
1600 while (User != Root) {
1601 if (!User->hasOneUse())
1602 return false;
1603 User = *User->use_begin();
1604 }
1605
1606 return true;
1607}
1608
Sanjay Patelb5723d02015-10-13 15:12:27 +00001609/// Match a scalar SSE load. In particular, we want to match a load whose top
1610/// elements are either undef or zeros. The load flavor is derived from the
1611/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001612///
1613/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001614/// PatternChainNode: this is the matched node that has a chain input and
1615/// output.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001616bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001617 SDValue N, SDValue &Base,
1618 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001619 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001620 SDValue &PatternNodeWithChain) {
Craig Topper36ecce92016-12-12 07:57:24 +00001621 // We can allow a full vector load here since narrowing a load is ok.
1622 if (ISD::isNON_EXTLoad(N.getNode())) {
1623 PatternNodeWithChain = N;
1624 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001625 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1626 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001627 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1628 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1629 Segment);
1630 }
1631 }
1632
1633 // We can also match the special zero extended load opcode.
1634 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1635 PatternNodeWithChain = N;
1636 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001637 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1638 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001639 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1640 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1641 Segment);
1642 }
1643 }
1644
Craig Topper991d1ca2016-11-26 17:29:25 +00001645 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1646 // once. Otherwise the load might get duplicated and the chain output of the
1647 // duplicate load will not be observed by all dependencies.
1648 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001649 PatternNodeWithChain = N.getOperand(0);
1650 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001651 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001652 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1653 hasSingleUsesFromRoot(Root, N.getNode())) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001654 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001655 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1656 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001657 }
1658 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001659
1660 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001661 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001662 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001663 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001664 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001665 N.getOperand(0).getNode()->hasOneUse()) {
1666 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1667 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001668 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001669 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1670 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Toppere266e122016-11-26 18:43:24 +00001671 // Okay, this is a zero extending load. Fold it.
1672 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1673 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1674 Segment);
1675 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001676 }
Craig Toppere266e122016-11-26 18:43:24 +00001677
Chris Lattner398195e2006-10-07 21:55:32 +00001678 return false;
1679}
1680
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001681
Sanjay Patel85030aa2015-10-13 16:23:00 +00001682bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001683 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1684 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001685 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001686 return false;
1687
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001688 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001689 return true;
1690 }
1691
1692 // In static codegen with small code model, we can get the address of a label
1693 // into a register with 'movl'. TableGen has already made sure we're looking
1694 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001695 assert(N->getOpcode() == X86ISD::Wrapper &&
1696 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001697 N = N.getOperand(0);
1698
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001699 // At least GNU as does not accept 'movl' for TPOFF relocations.
1700 // FIXME: We could use 'movl' when we know we are targeting MC.
1701 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001702 return false;
1703
1704 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001705 if (N->getOpcode() != ISD::TargetGlobalAddress)
1706 return TM.getCodeModel() == CodeModel::Small;
1707
1708 Optional<ConstantRange> CR =
1709 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1710 if (!CR)
1711 return TM.getCodeModel() == CodeModel::Small;
1712
1713 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001714}
1715
Sanjay Patel85030aa2015-10-13 16:23:00 +00001716bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001717 SDValue &Scale, SDValue &Index,
1718 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001719 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1720 SDLoc DL(N);
Jatin Bhateja908c8b32017-09-15 05:29:51 +00001721
Sanjay Patel85030aa2015-10-13 16:23:00 +00001722 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001723 return false;
1724
Tim Northover6833e3f2013-06-10 20:43:49 +00001725 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1726 if (RN && RN->getReg() == 0)
1727 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001728 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001729 // Base could already be %rip, particularly in the x32 ABI.
1730 Base = SDValue(CurDAG->getMachineNode(
1731 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001732 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001733 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001734 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001735 0);
1736 }
1737
1738 RN = dyn_cast<RegisterSDNode>(Index);
1739 if (RN && RN->getReg() == 0)
1740 Index = CurDAG->getRegister(0, MVT::i64);
1741 else {
1742 assert(Index.getValueType() == MVT::i32 &&
1743 "Expect to be extending 32-bit registers for use in LEA");
1744 Index = SDValue(CurDAG->getMachineNode(
1745 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001746 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001747 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001748 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1749 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001750 0);
1751 }
1752
1753 return true;
1754}
1755
Jatin Bhateja908c8b32017-09-15 05:29:51 +00001756bool X86DAGToDAGISel::matchAddressLEA(SDValue N, X86ISelAddressMode &AM) {
1757 // Avoid enabling aggressive operand folding when node N is a part of loop.
1758 X86AggressiveOperandFolding Enable(*this, !CurDAG->IsDAGPartOfLoop);
1759
1760 bool matchRes = matchAddress(N, AM);
1761
1762 // Check for legality of scale when recursion unwinds back to the top.
1763 if (!matchRes) {
1764 if (!AM.isLegalScale())
1765 return true;
1766
1767 // Avoid creating costly complex LEAs having scale less than 2
1768 // within loop.
1769 if(CurDAG->IsDAGPartOfLoop && Subtarget->slow3OpsLEA() &&
1770 AM.Scale <= 2 && AM.hasComplexAddressingMode() &&
1771 (!AM.hasSymbolicDisplacement() && N.getOpcode() < ISD::BUILTIN_OP_END))
1772 return true;
1773 }
1774
1775 return matchRes;
1776}
1777
1778
Sanjay Patelb5723d02015-10-13 15:12:27 +00001779/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001780/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001781bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001782 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001783 SDValue &Index, SDValue &Disp,
1784 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001785 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001786
Justin Bogner32ad24d2016-04-12 21:34:24 +00001787 // Save the DL and VT before calling matchAddress, it can invalidate N.
1788 SDLoc DL(N);
1789 MVT VT = N.getSimpleValueType();
1790
Rafael Espindolabb834f02009-04-10 10:09:34 +00001791 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1792 // segments.
1793 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001794 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001795 AM.Segment = T;
Jatin Bhateja908c8b32017-09-15 05:29:51 +00001796 if (matchAddressLEA(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001797 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001798 assert (T == AM.Segment);
1799 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001800
Evan Cheng77d86ff2006-02-25 10:09:08 +00001801 unsigned Complexity = 0;
1802 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001803 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001804 Complexity = 1;
1805 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001806 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001807 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1808 Complexity = 4;
1809
Gabor Greiff304a7a2008-08-28 21:40:38 +00001810 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001811 Complexity++;
1812 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001813 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001814
Chris Lattner3e1d9172007-03-20 06:08:29 +00001815 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1816 // a simple shift.
1817 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001818 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001819
1820 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001821 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001822 // optimal (especially for code size consideration). LEA is nice because of
1823 // its three-address nature. Tweak the cost function again when we can run
1824 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001825 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001826 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001827 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001828 Complexity = 4;
1829 else
1830 Complexity += 2;
1831 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001832
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001833 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001834 Complexity++;
1835
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001836 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001837 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001838 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001839
Justin Bogner32ad24d2016-04-12 21:34:24 +00001840 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001841 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001842}
1843
Sanjay Patelb5723d02015-10-13 15:12:27 +00001844/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001845bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001846 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001847 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001848 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1849 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001850
Chris Lattner7d2b0492009-06-20 20:38:48 +00001851 X86ISelAddressMode AM;
1852 AM.GV = GA->getGlobal();
1853 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001854 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001855 AM.SymbolFlags = GA->getTargetFlags();
1856
Owen Anderson9f944592009-08-11 20:47:22 +00001857 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001858 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001859 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001860 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001861 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001862 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001863
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001864 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001865 return true;
1866}
1867
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001868bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1869 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1870 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1871 N.getValueType());
1872 return true;
1873 }
1874
Peter Collingbourne235c2752016-12-08 19:01:00 +00001875 // Keep track of the original value type and whether this value was
1876 // truncated. If we see a truncation from pointer type to VT that truncates
1877 // bits that are known to be zero, we can use a narrow reference.
1878 EVT VT = N.getValueType();
1879 bool WasTruncated = false;
1880 if (N.getOpcode() == ISD::TRUNCATE) {
1881 WasTruncated = true;
1882 N = N.getOperand(0);
1883 }
1884
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001885 if (N.getOpcode() != X86ISD::Wrapper)
1886 return false;
1887
Peter Collingbourne235c2752016-12-08 19:01:00 +00001888 // We can only use non-GlobalValues as immediates if they were not truncated,
1889 // as we do not have any range information. If we have a GlobalValue and the
1890 // address was not truncated, we can select it as an operand directly.
1891 unsigned Opc = N.getOperand(0)->getOpcode();
1892 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1893 Op = N.getOperand(0);
1894 // We can only select the operand directly if we didn't have to look past a
1895 // truncate.
1896 return !WasTruncated;
1897 }
1898
1899 // Check that the global's range fits into VT.
1900 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1901 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1902 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1903 return false;
1904
1905 // Okay, we can use a narrow reference.
1906 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1907 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001908 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001909}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001910
Sanjay Patel85030aa2015-10-13 16:23:00 +00001911bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001912 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001913 SDValue &Index, SDValue &Disp,
1914 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00001915 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1916 !IsProfitableToFold(N, P, P) ||
Dan Gohman21cea8a2010-04-17 15:26:15 +00001917 !IsLegalToFold(N, P, P, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00001918 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001919
Sanjay Patel85030aa2015-10-13 16:23:00 +00001920 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001921 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00001922}
1923
Sanjay Patelb5723d02015-10-13 15:12:27 +00001924/// Return an SDNode that returns the value of the global base register.
1925/// Output instructions required to initialize the global base register,
1926/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00001927SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00001928 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00001929 auto &DL = MF->getDataLayout();
1930 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00001931}
1932
Peter Collingbourneef089bd2017-02-09 22:02:28 +00001933bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1934 if (N->getOpcode() == ISD::TRUNCATE)
1935 N = N->getOperand(0).getNode();
1936 if (N->getOpcode() != X86ISD::Wrapper)
1937 return false;
1938
1939 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1940 if (!GA)
1941 return false;
1942
1943 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1944 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1945 CR->getSignedMax().slt(1ull << Width);
1946}
1947
Sanjay Patelb5723d02015-10-13 15:12:27 +00001948/// Test whether the given X86ISD::CMP node has any uses which require the SF
1949/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001950static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001951 // Examine each user of the node.
1952 for (SDNode::use_iterator UI = N->use_begin(),
1953 UE = N->use_end(); UI != UE; ++UI) {
1954 // Only examine CopyToReg uses.
1955 if (UI->getOpcode() != ISD::CopyToReg)
1956 return false;
1957 // Only examine CopyToReg uses that copy to EFLAGS.
1958 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1959 X86::EFLAGS)
1960 return false;
1961 // Examine each user of the CopyToReg use.
1962 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1963 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1964 // Only examine the Flag result.
1965 if (FlagUI.getUse().getResNo() != 1) continue;
1966 // Anything unusual: assume conservatively.
1967 if (!FlagUI->isMachineOpcode()) return false;
1968 // Examine the opcode of the user.
1969 switch (FlagUI->getMachineOpcode()) {
1970 // These comparisons don't treat the most significant bit specially.
1971 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1972 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1973 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1974 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00001975 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1976 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001977 case X86::CMOVA16rr: case X86::CMOVA16rm:
1978 case X86::CMOVA32rr: case X86::CMOVA32rm:
1979 case X86::CMOVA64rr: case X86::CMOVA64rm:
1980 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1981 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1982 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1983 case X86::CMOVB16rr: case X86::CMOVB16rm:
1984 case X86::CMOVB32rr: case X86::CMOVB32rm:
1985 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00001986 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1987 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1988 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001989 case X86::CMOVE16rr: case X86::CMOVE16rm:
1990 case X86::CMOVE32rr: case X86::CMOVE32rm:
1991 case X86::CMOVE64rr: case X86::CMOVE64rm:
1992 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1993 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1994 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1995 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1996 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1997 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1998 case X86::CMOVP16rr: case X86::CMOVP16rm:
1999 case X86::CMOVP32rr: case X86::CMOVP32rm:
2000 case X86::CMOVP64rr: case X86::CMOVP64rm:
2001 continue;
2002 // Anything else: assume conservatively.
2003 default: return false;
2004 }
2005 }
2006 }
2007 return true;
2008}
2009
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002010/// Test whether the given node which sets flags has any uses which require the
2011/// CF flag to be accurate.
2012static bool hasNoCarryFlagUses(SDNode *N) {
2013 // Examine each user of the node.
2014 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
2015 ++UI) {
2016 // Only check things that use the flags.
2017 if (UI.getUse().getResNo() != 1)
2018 continue;
2019 // Only examine CopyToReg uses.
2020 if (UI->getOpcode() != ISD::CopyToReg)
2021 return false;
2022 // Only examine CopyToReg uses that copy to EFLAGS.
2023 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2024 return false;
2025 // Examine each user of the CopyToReg use.
2026 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2027 FlagUI != FlagUE; ++FlagUI) {
2028 // Only examine the Flag result.
2029 if (FlagUI.getUse().getResNo() != 1)
2030 continue;
2031 // Anything unusual: assume conservatively.
2032 if (!FlagUI->isMachineOpcode())
2033 return false;
2034 // Examine the opcode of the user.
2035 switch (FlagUI->getMachineOpcode()) {
2036 // Comparisons which don't examine the CF flag.
2037 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2038 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2039 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2040 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2041 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2042 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2043 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2044 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2045 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2046 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2047 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2048 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2049 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2050 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2051 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2052 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2053 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2054 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2055 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2056 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2057 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2058 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2059 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2060 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2061 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2062 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2063 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2064 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2065 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2066 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2067 continue;
2068 // Anything else: assume conservatively.
2069 default:
2070 return false;
2071 }
2072 }
2073 }
2074 return true;
2075}
2076
Sanjay Patelb5723d02015-10-13 15:12:27 +00002077/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002078/// the {load; op; store} to modify transformation.
2079static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2080 SDValue StoredVal, SelectionDAG *CurDAG,
2081 LoadSDNode *&LoadNode,
2082 SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002083 // is the stored value result 0 of the load?
2084 if (StoredVal.getResNo() != 0) return false;
2085
2086 // are there other uses of the loaded value than the inc or dec?
2087 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2088
Joel Jones68d59e82012-03-29 05:45:48 +00002089 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002090 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002091 return false;
2092
Evan Cheng3e869f02012-04-12 19:14:21 +00002093 SDValue Load = StoredVal->getOperand(0);
2094 // Is the stored value a non-extending and non-indexed load?
2095 if (!ISD::isNormalLoad(Load.getNode())) return false;
2096
2097 // Return LoadNode by reference.
2098 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002099
2100 // Is store the only read of the loaded value?
2101 if (!Load.hasOneUse())
2102 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002103
Evan Cheng3e869f02012-04-12 19:14:21 +00002104 // Is the address of the store the same as the load?
2105 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2106 LoadNode->getOffset() != StoreNode->getOffset())
2107 return false;
2108
2109 // Check if the chain is produced by the load or is a TokenFactor with
2110 // the load output chain as an operand. Return InputChain by reference.
2111 SDValue Chain = StoreNode->getChain();
2112
2113 bool ChainCheck = false;
2114 if (Chain == Load.getValue(1)) {
2115 ChainCheck = true;
2116 InputChain = LoadNode->getChain();
2117 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2118 SmallVector<SDValue, 4> ChainOps;
2119 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2120 SDValue Op = Chain.getOperand(i);
2121 if (Op == Load.getValue(1)) {
2122 ChainCheck = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002123 // Drop Load, but keep its chain. No cycle check necessary.
2124 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002125 continue;
2126 }
Evan Cheng58a95f02012-05-16 01:54:27 +00002127
2128 // Make sure using Op as part of the chain would not cause a cycle here.
2129 // In theory, we could check whether the chain node is a predecessor of
2130 // the load. But that can be very expensive. Instead visit the uses and
2131 // make sure they all have smaller node id than the load.
2132 int LoadId = LoadNode->getNodeId();
2133 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2134 UE = UI->use_end(); UI != UE; ++UI) {
2135 if (UI.getUse().getResNo() != 0)
2136 continue;
2137 if (UI->getNodeId() > LoadId)
2138 return false;
2139 }
2140
Evan Cheng3e869f02012-04-12 19:14:21 +00002141 ChainOps.push_back(Op);
2142 }
2143
2144 if (ChainCheck)
2145 // Make a new TokenFactor with all the other input chains except
2146 // for the load.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002147 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
Craig Topper48d114b2014-04-26 18:35:24 +00002148 MVT::Other, ChainOps);
Evan Cheng3e869f02012-04-12 19:14:21 +00002149 }
2150 if (!ChainCheck)
Joel Jones68d59e82012-03-29 05:45:48 +00002151 return false;
2152
2153 return true;
2154}
2155
Chandler Carruth4b611a82017-08-25 22:50:52 +00002156// Change a chain of {load; op; store} of the same value into a simple op
2157// through memory of that value, if the uses of the modified value and its
2158// address are suitable.
2159//
2160// The tablegen pattern memory operand pattern is currently not able to match
2161// the case where the EFLAGS on the original operation are used.
2162//
2163// To move this to tablegen, we'll need to improve tablegen to allow flags to
2164// be transferred from a node in the pattern to the result node, probably with
2165// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002166// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2167// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2168// (implicit EFLAGS)]>;
2169// but maybe need something like this
2170// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2171// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2172// (transferrable EFLAGS)]>;
2173//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002174// Until then, we manually fold these and instruction select the operation
2175// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002176bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2177 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2178 SDValue StoredVal = StoreNode->getOperand(1);
2179 unsigned Opc = StoredVal->getOpcode();
2180
Chandler Carruth4b611a82017-08-25 22:50:52 +00002181 // Before we try to select anything, make sure this is memory operand size
2182 // and opcode we can handle. Note that this must match the code below that
2183 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002184 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002185 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2186 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002187 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002188 switch (Opc) {
2189 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002190 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002191 case X86ISD::INC:
2192 case X86ISD::DEC:
2193 case X86ISD::ADD:
2194 case X86ISD::SUB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002195 case X86ISD::AND:
2196 case X86ISD::OR:
2197 case X86ISD::XOR:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002198 break;
2199 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002200
Chandler Carruth03258f22017-08-25 02:04:03 +00002201 LoadSDNode *LoadNode = nullptr;
2202 SDValue InputChain;
Chandler Carruth96db3082017-08-25 02:06:36 +00002203 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2204 InputChain))
Chandler Carruth03258f22017-08-25 02:04:03 +00002205 return false;
2206
2207 SDValue Base, Scale, Index, Disp, Segment;
2208 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2209 Segment))
2210 return false;
2211
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002212 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002213 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002214 switch (MemVT.getSimpleVT().SimpleTy) {
2215 case MVT::i64:
2216 return Opc64;
2217 case MVT::i32:
2218 return Opc32;
2219 case MVT::i16:
2220 return Opc16;
2221 case MVT::i8:
2222 return Opc8;
2223 default:
2224 llvm_unreachable("Invalid size!");
2225 }
2226 };
2227
2228 MachineSDNode *Result;
2229 switch (Opc) {
2230 case X86ISD::INC:
2231 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002232 unsigned NewOpc =
2233 Opc == X86ISD::INC
2234 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2235 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002236 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2237 Result =
2238 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2239 break;
2240 }
2241 case X86ISD::ADD:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002242 case X86ISD::SUB:
2243 case X86ISD::AND:
2244 case X86ISD::OR:
2245 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002246 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2247 switch (Opc) {
2248 case X86ISD::ADD:
2249 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2250 X86::ADD8mr);
2251 case X86ISD::SUB:
2252 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2253 X86::SUB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002254 case X86ISD::AND:
2255 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2256 X86::AND8mr);
2257 case X86ISD::OR:
2258 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2259 case X86ISD::XOR:
2260 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2261 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002262 default:
2263 llvm_unreachable("Invalid opcode!");
2264 }
2265 };
2266 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2267 switch (Opc) {
2268 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002269 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002270 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002271 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002272 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002273 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002274 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002275 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002276 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002277 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002278 default:
2279 llvm_unreachable("Invalid opcode!");
2280 }
2281 };
2282 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2283 switch (Opc) {
2284 case X86ISD::ADD:
2285 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2286 X86::ADD8mi);
2287 case X86ISD::SUB:
2288 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2289 X86::SUB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002290 case X86ISD::AND:
2291 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2292 X86::AND8mi);
2293 case X86ISD::OR:
2294 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2295 X86::OR8mi);
2296 case X86ISD::XOR:
2297 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2298 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002299 default:
2300 llvm_unreachable("Invalid opcode!");
2301 }
2302 };
2303
2304 unsigned NewOpc = SelectRegOpcode(Opc);
2305 SDValue Operand = StoredVal->getOperand(1);
2306
2307 // See if the operand is a constant that we can fold into an immediate
2308 // operand.
2309 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2310 auto OperandV = OperandC->getAPIntValue();
2311
2312 // Check if we can shrink the operand enough to fit in an immediate (or
2313 // fit into a smaller immediate) by negating it and switching the
2314 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002315 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2316 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002317 (-OperandV).getMinSignedBits() <= 8) ||
2318 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2319 (-OperandV).getMinSignedBits() <= 32)) &&
2320 hasNoCarryFlagUses(StoredVal.getNode())) {
2321 OperandV = -OperandV;
2322 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2323 }
2324
2325 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2326 // the larger immediate operand.
2327 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2328 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2329 NewOpc = SelectImm8Opcode(Opc);
2330 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2331 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2332 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2333 NewOpc = SelectImmOpcode(Opc);
2334 }
2335 }
2336
2337 const SDValue Ops[] = {Base, Scale, Index, Disp,
2338 Segment, Operand, InputChain};
Chandler Carruth4b611a82017-08-25 22:50:52 +00002339 Result =
2340 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2341 break;
2342 }
2343 default:
2344 llvm_unreachable("Invalid opcode!");
2345 }
2346
Chandler Carruth03258f22017-08-25 02:04:03 +00002347 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2348 MemOp[0] = StoreNode->getMemOperand();
2349 MemOp[1] = LoadNode->getMemOperand();
Chandler Carruth03258f22017-08-25 02:04:03 +00002350 Result->setMemRefs(MemOp, MemOp + 2);
2351
2352 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2353 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2354 CurDAG->RemoveDeadNode(Node);
2355 return true;
2356}
2357
Craig Topper958106d2017-09-12 17:40:25 +00002358// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2359bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2360 MVT NVT = Node->getSimpleValueType(0);
2361 SDLoc dl(Node);
2362
2363 SDValue N0 = Node->getOperand(0);
2364 SDValue N1 = Node->getOperand(1);
2365
2366 if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2367 return false;
2368
2369 // Must have a shift right.
2370 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2371 return false;
2372
2373 // Shift can't have additional users.
2374 if (!N0->hasOneUse())
2375 return false;
2376
2377 // Only supported for 32 and 64 bits.
2378 if (NVT != MVT::i32 && NVT != MVT::i64)
2379 return false;
2380
2381 // Shift amount and RHS of and must be constant.
2382 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2383 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2384 if (!MaskCst || !ShiftCst)
2385 return false;
2386
2387 // And RHS must be a mask.
2388 uint64_t Mask = MaskCst->getZExtValue();
2389 if (!isMask_64(Mask))
2390 return false;
2391
2392 uint64_t Shift = ShiftCst->getZExtValue();
2393 uint64_t MaskSize = countPopulation(Mask);
2394
2395 // Don't interfere with something that can be handled by extracting AH.
2396 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2397 if (Shift == 8 && MaskSize == 8)
2398 return false;
2399
2400 // Make sure we are only using bits that were in the original value, not
2401 // shifted in.
2402 if (Shift + MaskSize > NVT.getSizeInBits())
2403 return false;
2404
2405 SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
2406 unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
2407 unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
2408
2409 // BMI requires the immediate to placed in a register.
2410 if (!Subtarget->hasTBM()) {
2411 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
2412 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
Craig Topper2b6bfda2017-09-13 07:53:21 +00002413 New = SDValue(CurDAG->getMachineNode(X86::MOV32ri, dl, NVT, New), 0);
2414 if (NVT == MVT::i64) {
2415 New =
2416 SDValue(CurDAG->getMachineNode(
2417 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2418 CurDAG->getTargetConstant(0, dl, MVT::i64), New,
2419 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
2420 0);
2421 }
Craig Topper958106d2017-09-12 17:40:25 +00002422 }
2423
2424 MachineSDNode *NewNode;
2425 SDValue Input = N0->getOperand(0);
2426 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2427 if (tryFoldLoad(Node, Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2428 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
2429 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
2430 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2431 // Update the chain.
2432 ReplaceUses(N1.getValue(1), SDValue(NewNode, 1));
2433 // Record the mem-refs
2434 LoadSDNode *LoadNode = cast<LoadSDNode>(Input);
2435 if (LoadNode) {
2436 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2437 MemOp[0] = LoadNode->getMemOperand();
2438 NewNode->setMemRefs(MemOp, MemOp + 1);
2439 }
2440 } else {
2441 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, Input, New);
2442 }
2443
2444 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
2445 CurDAG->RemoveDeadNode(Node);
2446 return true;
2447}
2448
Justin Bogner593741d2016-05-10 23:55:37 +00002449void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002450 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002451 unsigned Opc, MOpc;
2452 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002453 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002454
Chris Lattnerf98f1242010-03-02 06:34:30 +00002455 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
Evan Chengd49cc362006-02-10 22:24:32 +00002456
Dan Gohman17059682008-07-17 19:10:17 +00002457 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00002458 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002459 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002460 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002461 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002462
Evan Cheng10d27902006-01-06 20:36:21 +00002463 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002464 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002465 case ISD::BRIND: {
2466 if (Subtarget->isTargetNaCl())
2467 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2468 // leave the instruction alone.
2469 break;
2470 if (Subtarget->isTarget64BitILP32()) {
2471 // Converts a 32-bit register to a 64-bit, zero-extended version of
2472 // it. This is needed because x86-64 can do many things, but jmp %r32
2473 // ain't one of them.
2474 const SDValue &Target = Node->getOperand(1);
2475 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2476 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2477 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2478 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002479 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002480 SelectCode(ZextTarget.getNode());
2481 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002482 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002483 }
2484 break;
2485 }
Dan Gohman757eee82009-08-02 16:10:52 +00002486 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002487 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002488 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002489
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002490 case X86ISD::SHRUNKBLEND: {
2491 // SHRUNKBLEND selects like a regular VSELECT.
2492 SDValue VSelect = CurDAG->getNode(
2493 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2494 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002495 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002496 SelectCode(VSelect.getNode());
2497 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002498 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002499 }
Craig Topper3af251d2012-07-01 02:55:34 +00002500
Tobias Grosser85508e82015-08-19 11:35:10 +00002501 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002502 // Try to match BEXTR/BEXTRI instruction.
2503 if (matchBEXTRFromAnd(Node))
2504 return;
2505
2506 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002507 case ISD::OR:
2508 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002509
Benjamin Kramer4c816242011-04-22 15:30:40 +00002510 // For operations of the form (x << C1) op C2, check if we can use a smaller
2511 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2512 SDValue N0 = Node->getOperand(0);
2513 SDValue N1 = Node->getOperand(1);
2514
2515 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2516 break;
2517
2518 // i8 is unshrinkable, i16 should be promoted to i32.
2519 if (NVT != MVT::i32 && NVT != MVT::i64)
2520 break;
2521
2522 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2523 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2524 if (!Cst || !ShlCst)
2525 break;
2526
2527 int64_t Val = Cst->getSExtValue();
2528 uint64_t ShlVal = ShlCst->getZExtValue();
2529
2530 // Make sure that we don't change the operation by removing bits.
2531 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002532 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2533 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002534 break;
2535
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002536 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002537 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002538
2539 // Check the minimum bitwidth for the new constant.
2540 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2541 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2542 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2543 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2544 CstVT = MVT::i8;
2545 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2546 CstVT = MVT::i32;
2547
2548 // Bail if there is no smaller encoding.
2549 if (NVT == CstVT)
2550 break;
2551
Craig Topper83e042a2013-08-15 05:57:07 +00002552 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002553 default: llvm_unreachable("Unsupported VT!");
2554 case MVT::i32:
2555 assert(CstVT == MVT::i8);
2556 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002557 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002558
2559 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002560 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002561 case ISD::AND: Op = X86::AND32ri8; break;
2562 case ISD::OR: Op = X86::OR32ri8; break;
2563 case ISD::XOR: Op = X86::XOR32ri8; break;
2564 }
2565 break;
2566 case MVT::i64:
2567 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2568 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002569 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002570
2571 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002572 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002573 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2574 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2575 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2576 }
2577 break;
2578 }
2579
2580 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002581 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002582 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002583 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002584 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2585 SDValue(New, 0));
2586 else
2587 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2588 getI8Imm(ShlVal, dl));
2589 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002590 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002591 case X86ISD::UMUL8:
2592 case X86ISD::SMUL8: {
2593 SDValue N0 = Node->getOperand(0);
2594 SDValue N1 = Node->getOperand(1);
2595
2596 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2597
2598 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2599 N0, SDValue()).getValue(1);
2600
2601 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2602 SDValue Ops[] = {N1, InFlag};
2603 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2604
Justin Bogner31d7da32016-05-11 21:13:17 +00002605 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002606 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002607 }
2608
Chris Lattner364bb0a2010-12-05 07:30:36 +00002609 case X86ISD::UMUL: {
2610 SDValue N0 = Node->getOperand(0);
2611 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002612
Ted Kremenekb5241b22011-01-14 22:34:13 +00002613 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002614 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002615 default: llvm_unreachable("Unsupported VT!");
Ted Kremenekb5241b22011-01-14 22:34:13 +00002616 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2617 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2618 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2619 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002620 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002621
Chris Lattner364bb0a2010-12-05 07:30:36 +00002622 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2623 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002624
Chris Lattner364bb0a2010-12-05 07:30:36 +00002625 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2626 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002627 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002628
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002629 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002630 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002631 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002632
Dan Gohman757eee82009-08-02 16:10:52 +00002633 case ISD::SMUL_LOHI:
2634 case ISD::UMUL_LOHI: {
2635 SDValue N0 = Node->getOperand(0);
2636 SDValue N1 = Node->getOperand(1);
2637
2638 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002639 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002640 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002641 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002642 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002643 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2644 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
Michael Liaof9f7b552012-09-26 08:22:37 +00002645 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2646 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2647 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2648 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002649 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002650 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002651 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002652 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002653 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2654 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2655 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2656 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002657 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002658 }
Dan Gohman757eee82009-08-02 16:10:52 +00002659
Michael Liaof9f7b552012-09-26 08:22:37 +00002660 unsigned SrcReg, LoReg, HiReg;
2661 switch (Opc) {
2662 default: llvm_unreachable("Unknown MUL opcode!");
2663 case X86::IMUL8r:
2664 case X86::MUL8r:
2665 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2666 break;
2667 case X86::IMUL16r:
2668 case X86::MUL16r:
2669 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2670 break;
2671 case X86::IMUL32r:
2672 case X86::MUL32r:
2673 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2674 break;
2675 case X86::IMUL64r:
2676 case X86::MUL64r:
2677 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2678 break;
2679 case X86::MULX32rr:
2680 SrcReg = X86::EDX; LoReg = HiReg = 0;
2681 break;
2682 case X86::MULX64rr:
2683 SrcReg = X86::RDX; LoReg = HiReg = 0;
2684 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002685 }
2686
2687 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002688 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002689 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002690 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002691 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002692 if (foldedLoad)
2693 std::swap(N0, N1);
2694 }
2695
Michael Liaof9f7b552012-09-26 08:22:37 +00002696 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002697 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002698 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002699
2700 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002701 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002702 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002703 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2704 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002705 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2706 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002707 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002708 ResHi = SDValue(CNode, 0);
2709 ResLo = SDValue(CNode, 1);
2710 Chain = SDValue(CNode, 2);
2711 InFlag = SDValue(CNode, 3);
2712 } else {
2713 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002714 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002715 Chain = SDValue(CNode, 0);
2716 InFlag = SDValue(CNode, 1);
2717 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002718
Dan Gohman757eee82009-08-02 16:10:52 +00002719 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002720 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00002721 // Record the mem-refs
2722 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2723 if (LoadNode) {
2724 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2725 MemOp[0] = LoadNode->getMemOperand();
2726 CNode->setMemRefs(MemOp, MemOp + 1);
2727 }
Dan Gohman757eee82009-08-02 16:10:52 +00002728 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00002729 SDValue Ops[] = { N1, InFlag };
2730 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2731 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002732 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002733 ResHi = SDValue(CNode, 0);
2734 ResLo = SDValue(CNode, 1);
2735 InFlag = SDValue(CNode, 2);
2736 } else {
2737 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002738 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002739 InFlag = SDValue(CNode, 0);
2740 }
Dan Gohman757eee82009-08-02 16:10:52 +00002741 }
2742
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002743 // Prevent use of AH in a REX instruction by referencing AX instead.
2744 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2745 !SDValue(Node, 1).use_empty()) {
2746 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2747 X86::AX, MVT::i16, InFlag);
2748 InFlag = Result.getValue(2);
2749 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2750 // registers.
2751 if (!SDValue(Node, 0).use_empty())
2752 ReplaceUses(SDValue(Node, 1),
2753 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2754
2755 // Shift AX down 8 bits.
2756 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2757 Result,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002758 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2759 0);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002760 // Then truncate it down to i8.
2761 ReplaceUses(SDValue(Node, 1),
2762 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2763 }
Dan Gohman757eee82009-08-02 16:10:52 +00002764 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002765 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002766 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002767 assert(LoReg && "Register for low half is not defined!");
2768 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2769 InFlag);
2770 InFlag = ResLo.getValue(2);
2771 }
2772 ReplaceUses(SDValue(Node, 0), ResLo);
2773 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002774 }
2775 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002776 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002777 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002778 assert(HiReg && "Register for high half is not defined!");
2779 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2780 InFlag);
2781 InFlag = ResHi.getValue(2);
2782 }
2783 ReplaceUses(SDValue(Node, 1), ResHi);
2784 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002785 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002786
Craig Topper6bed9de2017-09-09 05:57:20 +00002787 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002788 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002789 }
2790
2791 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002792 case ISD::UDIVREM:
2793 case X86ISD::SDIVREM8_SEXT_HREG:
2794 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00002795 SDValue N0 = Node->getOperand(0);
2796 SDValue N1 = Node->getOperand(1);
2797
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002798 bool isSigned = (Opcode == ISD::SDIVREM ||
2799 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002800 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002801 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002802 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002803 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2804 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2805 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2806 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002807 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002808 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002809 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002810 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002811 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2812 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2813 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2814 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002815 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002816 }
Dan Gohman757eee82009-08-02 16:10:52 +00002817
Chris Lattner518b0372009-12-23 01:45:04 +00002818 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002819 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00002820 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002821 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002822 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00002823 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00002824 SExtOpcode = X86::CBW;
2825 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002826 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00002827 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002828 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00002829 SExtOpcode = X86::CWD;
2830 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002831 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00002832 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002833 SExtOpcode = X86::CDQ;
2834 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002835 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00002836 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002837 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00002838 break;
2839 }
2840
Dan Gohman757eee82009-08-02 16:10:52 +00002841 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002842 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002843 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00002844
Dan Gohman757eee82009-08-02 16:10:52 +00002845 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00002846 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002847 // Special case for div8, just use a move with zero extension to AX to
2848 // clear the upper 8 bits (AH).
2849 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002850 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002851 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2852 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002853 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00002854 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002855 Chain = Move.getValue(1);
2856 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00002857 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00002858 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002859 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002860 Chain = CurDAG->getEntryNode();
2861 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00002862 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00002863 InFlag = Chain.getValue(1);
2864 } else {
2865 InFlag =
2866 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2867 LoReg, N0, SDValue()).getValue(1);
2868 if (isSigned && !signBitIsZero) {
2869 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00002870 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002871 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002872 } else {
2873 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00002874 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00002875 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00002876 case MVT::i16:
2877 ClrNode =
2878 SDValue(CurDAG->getMachineNode(
2879 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002880 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2881 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002882 0);
2883 break;
2884 case MVT::i32:
2885 break;
2886 case MVT::i64:
2887 ClrNode =
2888 SDValue(CurDAG->getMachineNode(
2889 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002890 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2891 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2892 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002893 0);
2894 break;
2895 default:
2896 llvm_unreachable("Unexpected division source");
2897 }
2898
Chris Lattner518b0372009-12-23 01:45:04 +00002899 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00002900 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00002901 }
Evan Cheng92e27972006-01-06 23:19:29 +00002902 }
Dan Gohmana1603612007-10-08 18:33:35 +00002903
Dan Gohman757eee82009-08-02 16:10:52 +00002904 if (foldedLoad) {
2905 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2906 InFlag };
2907 SDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00002908 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00002909 InFlag = SDValue(CNode, 1);
2910 // Update the chain.
2911 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2912 } else {
2913 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002914 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002915 }
Evan Cheng92e27972006-01-06 23:19:29 +00002916
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002917 // Prevent use of AH in a REX instruction by explicitly copying it to
2918 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00002919 //
2920 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002921 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00002922 // the allocator and/or the backend get enhanced to be more robust in
2923 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002924 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2925 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2926 unsigned AHExtOpcode =
2927 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002928
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002929 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2930 MVT::Glue, AHCopy, InFlag);
2931 SDValue Result(RNode, 0);
2932 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002933
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002934 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2935 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2936 if (Node->getValueType(1) == MVT::i64) {
2937 // It's not possible to directly movsx AH to a 64bit register, because
2938 // the latter needs the REX prefix, but the former can't have it.
2939 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2940 "Unexpected i64 sext of h-register");
2941 Result =
2942 SDValue(CurDAG->getMachineNode(
2943 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002944 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2945 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2946 MVT::i32)),
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002947 0);
2948 }
2949 } else {
2950 Result =
2951 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2952 }
2953 ReplaceUses(SDValue(Node, 1), Result);
2954 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002955 }
Dan Gohman757eee82009-08-02 16:10:52 +00002956 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002957 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00002958 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2959 LoReg, NVT, InFlag);
2960 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002961 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002962 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002963 }
2964 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002965 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002966 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2967 HiReg, NVT, InFlag);
2968 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002969 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002970 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002971 }
Craig Topper6bed9de2017-09-09 05:57:20 +00002972 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002973 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002974 }
2975
Manman Ren1be131b2012-08-08 00:51:41 +00002976 case X86ISD::CMP:
2977 case X86ISD::SUB: {
2978 // Sometimes a SUB is used to perform comparison.
2979 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2980 // This node is not a CMP.
2981 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00002982 SDValue N0 = Node->getOperand(0);
2983 SDValue N1 = Node->getOperand(1);
2984
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002985 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00002986 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002987 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00002988
Dan Gohmanac33a902009-08-19 18:16:17 +00002989 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2990 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002991 // Look past the truncate if CMP is the only use of it.
Craig Topperc93d05562017-08-25 05:36:29 +00002992 if ((N0.getOpcode() == ISD::AND ||
2993 (N0.getResNo() == 0 && N0.getOpcode() == X86ISD::AND)) &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00002994 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00002995 N0.getValueType() != MVT::i8 &&
2996 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00002997 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00002998 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00002999 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00003000
3001 // For example, convert "testl %eax, $8" to "testb %al, $8"
Craig Topperfc53dc22017-08-25 05:04:34 +00003002 if (isUInt<8>(Mask) &&
3003 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
3004 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003005 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003006
3007 // On x86-32, only the ABCD registers have 8-bit subregisters.
3008 if (!Subtarget->is64Bit()) {
Craig Toppercc830f82012-02-22 07:28:11 +00003009 const TargetRegisterClass *TRC;
Craig Topper56710102013-08-15 02:33:50 +00003010 switch (N0.getSimpleValueType().SimpleTy) {
Dan Gohmanac33a902009-08-19 18:16:17 +00003011 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
3012 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
3013 default: llvm_unreachable("Unsupported TEST operand type!");
3014 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003015 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
Dan Gohman32f71d72009-09-25 18:54:59 +00003016 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
3017 Reg.getValueType(), Reg, RC), 0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003018 }
3019
3020 // Extract the l-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003021 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003022 MVT::i8, Reg);
3023
3024 // Emit a testb.
Manman Ren511c6d02012-09-28 18:53:24 +00003025 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
3026 Subreg, Imm);
3027 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3028 // one, do not call ReplaceAllUsesWith.
3029 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3030 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003031 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003032 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003033 }
3034
3035 // For example, "testl %eax, $2048" to "testb %ah, $8".
Craig Topperfc53dc22017-08-25 05:04:34 +00003036 if (isShiftedUInt<8, 8>(Mask) &&
3037 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
Dan Gohmanac33a902009-08-19 18:16:17 +00003038 // Shift the immediate right by 8 bits.
Craig Topperfc53dc22017-08-25 05:04:34 +00003039 SDValue ShiftedImm = CurDAG->getTargetConstant(Mask >> 8, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003040 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003041
3042 // Put the value in an ABCD register.
Craig Toppercc830f82012-02-22 07:28:11 +00003043 const TargetRegisterClass *TRC;
Craig Topper56710102013-08-15 02:33:50 +00003044 switch (N0.getSimpleValueType().SimpleTy) {
Dan Gohmanac33a902009-08-19 18:16:17 +00003045 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
3046 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
3047 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
3048 default: llvm_unreachable("Unsupported TEST operand type!");
3049 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003050 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
Dan Gohman32f71d72009-09-25 18:54:59 +00003051 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
3052 Reg.getValueType(), Reg, RC), 0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003053
3054 // Extract the h-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003055 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003056 MVT::i8, Reg);
3057
Jakob Stoklund Olesen729abd32011-10-08 18:28:28 +00003058 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
3059 // target GR8_NOREX registers, so make sure the register class is
3060 // forced.
Manman Ren511c6d02012-09-28 18:53:24 +00003061 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
3062 MVT::i32, Subreg, ShiftedImm);
3063 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3064 // one, do not call ReplaceAllUsesWith.
3065 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3066 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003067 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003068 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003069 }
3070
3071 // For example, "testl %eax, $32776" to "testw %ax, $32776".
Craig Topperfc53dc22017-08-25 05:04:34 +00003072 if (isUInt<16>(Mask) && N0.getValueType() != MVT::i16 &&
3073 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3074 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i16);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003075 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003076
3077 // Extract the 16-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003078 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003079 MVT::i16, Reg);
3080
3081 // Emit a testw.
Manman Ren511c6d02012-09-28 18:53:24 +00003082 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
3083 Subreg, Imm);
3084 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3085 // one, do not call ReplaceAllUsesWith.
3086 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3087 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003088 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003089 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003090 }
3091
3092 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
Craig Topperfc53dc22017-08-25 05:04:34 +00003093 if (isUInt<32>(Mask) && N0.getValueType() == MVT::i64 &&
3094 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3095 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003096 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003097
3098 // Extract the 32-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003099 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003100 MVT::i32, Reg);
3101
3102 // Emit a testl.
Manman Ren511c6d02012-09-28 18:53:24 +00003103 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
3104 Subreg, Imm);
3105 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3106 // one, do not call ReplaceAllUsesWith.
3107 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3108 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003109 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003110 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003111 }
3112 }
3113 break;
3114 }
Chandler Carruth03258f22017-08-25 02:04:03 +00003115 case ISD::STORE:
3116 if (foldLoadStoreIntoMemOperand(Node))
3117 return;
3118 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003119 }
3120
Justin Bogner593741d2016-05-10 23:55:37 +00003121 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003122}
3123
Chris Lattnerba1ed582006-06-08 18:03:49 +00003124bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003125SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003126 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003127 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003128 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003129 default:
3130 llvm_unreachable("Unexpected asm memory constraint");
3131 case InlineAsm::Constraint_i:
3132 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3133 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003134 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003135 case InlineAsm::Constraint_o: // offsetable ??
3136 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003137 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003138 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003139 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003140 return true;
3141 break;
3142 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003143
Evan Cheng2d487222006-08-26 01:05:16 +00003144 OutOps.push_back(Op0);
3145 OutOps.push_back(Op1);
3146 OutOps.push_back(Op2);
3147 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003148 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003149 return false;
3150}
3151
Sanjay Patelb5723d02015-10-13 15:12:27 +00003152/// This pass converts a legalized DAG into a X86-specific DAG,
3153/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003154FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003155 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003156 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003157}