Missing print.
[oota-llvm.git] / lib / Target / WebAssembly / WebAssemblyISelLowering.cpp
1 //=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements the WebAssemblyTargetLowering class.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "WebAssemblyISelLowering.h"
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "WebAssemblySubtarget.h"
19 #include "WebAssemblyTargetMachine.h"
20 #include "WebAssemblyTargetObjectFile.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/DiagnosticPrinter.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetOptions.h"
34
35 using namespace llvm;
36
37 #define DEBUG_TYPE "wasm-lower"
38
39 namespace {
40 // Diagnostic information for unimplemented or unsupported feature reporting.
41 // FIXME copied from BPF and AMDGPU.
42 class DiagnosticInfoUnsupported : public DiagnosticInfo {
43 private:
44   // Debug location where this diagnostic is triggered.
45   DebugLoc DLoc;
46   const Twine &Description;
47   const Function &Fn;
48   SDValue Value;
49
50   static int KindID;
51
52   static int getKindID() {
53     if (KindID == 0)
54       KindID = llvm::getNextAvailablePluginDiagnosticKind();
55     return KindID;
56   }
57
58 public:
59   DiagnosticInfoUnsupported(SDLoc DLoc, const Function &Fn, const Twine &Desc,
60                             SDValue Value)
61       : DiagnosticInfo(getKindID(), DS_Error), DLoc(DLoc.getDebugLoc()),
62         Description(Desc), Fn(Fn), Value(Value) {}
63
64   void print(DiagnosticPrinter &DP) const override {
65     std::string Str;
66     raw_string_ostream OS(Str);
67
68     if (DLoc) {
69       auto DIL = DLoc.get();
70       StringRef Filename = DIL->getFilename();
71       unsigned Line = DIL->getLine();
72       unsigned Column = DIL->getColumn();
73       OS << Filename << ':' << Line << ':' << Column << ' ';
74     }
75
76     OS << "in function " << Fn.getName() << ' ' << *Fn.getFunctionType() << '\n'
77        << Description;
78     if (Value)
79       Value->print(OS);
80     OS << '\n';
81     OS.flush();
82     DP << Str;
83   }
84
85   static bool classof(const DiagnosticInfo *DI) {
86     return DI->getKind() == getKindID();
87   }
88 };
89
90 int DiagnosticInfoUnsupported::KindID = 0;
91 } // end anonymous namespace
92
93 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
94     const TargetMachine &TM, const WebAssemblySubtarget &STI)
95     : TargetLowering(TM), Subtarget(&STI) {
96   // Booleans always contain 0 or 1.
97   setBooleanContents(ZeroOrOneBooleanContent);
98   // WebAssembly does not produce floating-point exceptions on normal floating
99   // point operations.
100   setHasFloatingPointExceptions(false);
101   // We don't know the microarchitecture here, so just reduce register pressure.
102   setSchedulingPreference(Sched::RegPressure);
103   // Tell ISel that we have a stack pointer.
104   setStackPointerRegisterToSaveRestore(
105       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
106   // Set up the register classes.
107   addRegisterClass(MVT::i32, &WebAssembly::Int32RegClass);
108   addRegisterClass(MVT::i64, &WebAssembly::Int64RegClass);
109   addRegisterClass(MVT::f32, &WebAssembly::Float32RegClass);
110   addRegisterClass(MVT::f64, &WebAssembly::Float64RegClass);
111   // Compute derived properties from the register classes.
112   computeRegisterProperties(Subtarget->getRegisterInfo());
113
114   // FIXME: many setOperationAction are missing...
115
116   for (auto T : {MVT::f32, MVT::f64}) {
117     // Don't expand the floating-point types to constant pools.
118     setOperationAction(ISD::ConstantFP, T, Legal);
119     // Expand floating-point comparisons.
120     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
121                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
122       setCondCodeAction(CC, T, Expand);
123     // Expand floating-point library function operators.
124     for (auto Op : {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOWI, ISD::FPOW})
125       setOperationAction(Op, T, Expand);
126     // Note supported floating-point library function operators that otherwise
127     // default to expand.
128     for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
129                     ISD::FRINT})
130       setOperationAction(Op, T, Legal);
131   }
132
133   for (auto T : {MVT::i32, MVT::i64}) {
134     // Expand unavailable integer operations.
135     for (auto Op : {ISD::BSWAP, ISD::ROTL, ISD::ROTR,
136                     ISD::SMUL_LOHI, ISD::UMUL_LOHI,
137                     ISD::MULHS, ISD::MULHU, ISD::SDIVREM, ISD::UDIVREM,
138                     ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS,
139                     ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
140       setOperationAction(Op, T, Expand);
141     }
142   }
143
144   // As a special case, these operators use the type to mean the type to
145   // sign-extend from.
146   for (auto T : {MVT::i1, MVT::i8, MVT::i16})
147     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
148
149   // Dynamic stack allocation: use the default expansion.
150   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
151   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
152   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
153 }
154
155 FastISel *WebAssemblyTargetLowering::createFastISel(
156     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
157   return WebAssembly::createFastISel(FuncInfo, LibInfo);
158 }
159
160 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
161                                                       EVT VT) const {
162   return VT.getSimpleVT();
163 }
164
165 const char *
166 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
167   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
168   case WebAssemblyISD::FIRST_NUMBER:
169     break;
170 #define HANDLE_NODETYPE(NODE)                                                  \
171   case WebAssemblyISD::NODE:                                                   \
172     return "WebAssemblyISD::" #NODE;
173 #include "WebAssemblyISD.def"
174 #undef HANDLE_NODETYPE
175   }
176   return nullptr;
177 }
178
179 //===----------------------------------------------------------------------===//
180 // WebAssembly Lowering private implementation.
181 //===----------------------------------------------------------------------===//
182
183 //===----------------------------------------------------------------------===//
184 // Lowering Code
185 //===----------------------------------------------------------------------===//
186
187 static void fail(SDLoc DL, SelectionDAG &DAG, const char *msg) {
188   MachineFunction &MF = DAG.getMachineFunction();
189   DAG.getContext()->diagnose(
190       DiagnosticInfoUnsupported(DL, *MF.getFunction(), msg, SDValue()));
191 }
192
193 SDValue
194 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
195                                      SmallVectorImpl<SDValue> &InVals) const {
196   SelectionDAG &DAG = CLI.DAG;
197   SDLoc DL = CLI.DL;
198   SDValue Chain = CLI.Chain;
199   SDValue Callee = CLI.Callee;
200   MachineFunction &MF = DAG.getMachineFunction();
201
202   CallingConv::ID CallConv = CLI.CallConv;
203   if (CallConv != CallingConv::C)
204     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
205   if (CLI.IsTailCall || MF.getTarget().Options.GuaranteedTailCallOpt)
206     fail(DL, DAG, "WebAssembly doesn't support tail call yet");
207   if (CLI.IsPatchPoint)
208     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
209
210   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
211   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
212   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
213   if (IsStructRet)
214     fail(DL, DAG, "WebAssembly doesn't support struct return yet");
215   if (Outs.size() > 1)
216     fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
217
218   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
219   bool IsVarArg = CLI.IsVarArg;
220   if (IsVarArg)
221     fail(DL, DAG, "WebAssembly doesn't support varargs yet");
222   // Analyze operands of the call, assigning locations to each operand.
223   SmallVector<CCValAssign, 16> ArgLocs;
224   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
225   unsigned NumBytes = CCInfo.getNextStackOffset();
226
227   auto PtrVT = getPointerTy(MF.getDataLayout());
228   auto Zero = DAG.getConstant(0, DL, PtrVT, true);
229   auto NB = DAG.getConstant(NumBytes, DL, PtrVT, true);
230   Chain = DAG.getCALLSEQ_START(Chain, NB, DL);
231
232   SmallVector<SDValue, 16> Ops;
233   Ops.push_back(Chain);
234   Ops.push_back(Callee);
235   Ops.append(OutVals.begin(), OutVals.end());
236
237   SmallVector<EVT, 8> Tys;
238   for (const auto &In : Ins)
239     Tys.push_back(In.VT);
240   Tys.push_back(MVT::Other);
241   SDVTList TyList = DAG.getVTList(Tys);
242   SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, TyList, Ops);
243   if (!Ins.empty()) {
244     InVals.push_back(Res);
245     Chain = Res.getValue(1);
246   }
247
248   // FIXME: handle CLI.RetSExt and CLI.RetZExt?
249
250   Chain = DAG.getCALLSEQ_END(Chain, NB, Zero, SDValue(), DL);
251
252   return Chain;
253 }
254
255 bool WebAssemblyTargetLowering::CanLowerReturn(
256     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
257     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
258   // WebAssembly can't currently handle returning tuples.
259   return Outs.size() <= 1;
260 }
261
262 SDValue WebAssemblyTargetLowering::LowerReturn(
263     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
264     const SmallVectorImpl<ISD::OutputArg> &Outs,
265     const SmallVectorImpl<SDValue> &OutVals, SDLoc DL,
266     SelectionDAG &DAG) const {
267
268   assert(Outs.size() <= 1 && "WebAssembly can only return up to one value");
269   if (CallConv != CallingConv::C)
270     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
271   if (IsVarArg)
272     fail(DL, DAG, "WebAssembly doesn't support varargs yet");
273
274   SmallVector<SDValue, 4> RetOps(1, Chain);
275   RetOps.append(OutVals.begin(), OutVals.end());
276   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
277
278   return Chain;
279 }
280
281 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
282     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
283     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
284     SmallVectorImpl<SDValue> &InVals) const {
285   MachineFunction &MF = DAG.getMachineFunction();
286
287   if (CallConv != CallingConv::C)
288     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
289   if (IsVarArg)
290     fail(DL, DAG, "WebAssembly doesn't support varargs yet");
291   if (MF.getFunction()->hasStructRetAttr())
292     fail(DL, DAG, "WebAssembly doesn't support struct return yet");
293
294   unsigned ArgNo = 0;
295   for (const ISD::InputArg &In : Ins) {
296     if (In.Flags.isZExt())
297       fail(DL, DAG, "WebAssembly hasn't implemented zext arguments");
298     if (In.Flags.isSExt())
299       fail(DL, DAG, "WebAssembly hasn't implemented sext arguments");
300     if (In.Flags.isInReg())
301       fail(DL, DAG, "WebAssembly hasn't implemented inreg arguments");
302     if (In.Flags.isSRet())
303       fail(DL, DAG, "WebAssembly hasn't implemented sret arguments");
304     if (In.Flags.isByVal())
305       fail(DL, DAG, "WebAssembly hasn't implemented byval arguments");
306     if (In.Flags.isInAlloca())
307       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
308     if (In.Flags.isNest())
309       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
310     if (In.Flags.isReturned())
311       fail(DL, DAG, "WebAssembly hasn't implemented returned arguments");
312     if (In.Flags.isInConsecutiveRegs())
313       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
314     if (In.Flags.isInConsecutiveRegsLast())
315       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
316     if (In.Flags.isSplit())
317       fail(DL, DAG, "WebAssembly hasn't implemented split arguments");
318     // FIXME Do something with In.getOrigAlign()?
319     InVals.push_back(
320         In.Used
321             ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
322                           DAG.getTargetConstant(ArgNo, DL, MVT::i32))
323             : DAG.getNode(ISD::UNDEF, DL, In.VT));
324     ++ArgNo;
325   }
326
327   return Chain;
328 }
329
330 //===----------------------------------------------------------------------===//
331 //  Other Lowering Code
332 //===----------------------------------------------------------------------===//
333
334 //===----------------------------------------------------------------------===//
335 //                          WebAssembly Optimization Hooks
336 //===----------------------------------------------------------------------===//
337
338 MCSection *WebAssemblyTargetObjectFile::SelectSectionForGlobal(
339     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
340     const TargetMachine &TM) const {
341   return getDataSection();
342 }