06a141c7df7f4ac7e11eb27a38342854b7cc3246
[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/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetOptions.h"
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 final : 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   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
97
98   // Booleans always contain 0 or 1.
99   setBooleanContents(ZeroOrOneBooleanContent);
100   // WebAssembly does not produce floating-point exceptions on normal floating
101   // point operations.
102   setHasFloatingPointExceptions(false);
103   // We don't know the microarchitecture here, so just reduce register pressure.
104   setSchedulingPreference(Sched::RegPressure);
105   // Tell ISel that we have a stack pointer.
106   setStackPointerRegisterToSaveRestore(
107       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
108   // Set up the register classes.
109   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
110   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
111   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
112   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
113   // Compute derived properties from the register classes.
114   computeRegisterProperties(Subtarget->getRegisterInfo());
115
116   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
117   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
118
119   for (auto T : {MVT::f32, MVT::f64}) {
120     // Don't expand the floating-point types to constant pools.
121     setOperationAction(ISD::ConstantFP, T, Legal);
122     // Expand floating-point comparisons.
123     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
124                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
125       setCondCodeAction(CC, T, Expand);
126     // Expand floating-point library function operators.
127     for (auto Op : {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOWI, ISD::FPOW})
128       setOperationAction(Op, T, Expand);
129     // Note supported floating-point library function operators that otherwise
130     // default to expand.
131     for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
132                     ISD::FRINT})
133       setOperationAction(Op, T, Legal);
134     // Support minnan and maxnan, which otherwise default to expand.
135     setOperationAction(ISD::FMINNAN, T, Legal);
136     setOperationAction(ISD::FMAXNAN, T, Legal);
137   }
138
139   for (auto T : {MVT::i32, MVT::i64}) {
140     // Expand unavailable integer operations.
141     for (auto Op : {ISD::BSWAP, ISD::ROTL, ISD::ROTR,
142                     ISD::SMUL_LOHI, ISD::UMUL_LOHI,
143                     ISD::MULHS, ISD::MULHU, ISD::SDIVREM, ISD::UDIVREM,
144                     ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS,
145                     ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
146       setOperationAction(Op, T, Expand);
147     }
148   }
149
150   // As a special case, these operators use the type to mean the type to
151   // sign-extend from.
152   for (auto T : {MVT::i1, MVT::i8, MVT::i16})
153     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
154
155   // Dynamic stack allocation: use the default expansion.
156   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
157   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
158   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
159
160   // Expand these forms; we pattern-match the forms that we can handle in isel.
161   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
162     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
163       setOperationAction(Op, T, Expand);
164
165   // We have custom switch handling.
166   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
167
168   // WebAssembly doesn't have:
169   //  - Floating-point extending loads.
170   //  - Floating-point truncating stores.
171   //  - i1 extending loads.
172   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f64, Expand);
173   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
174   for (auto T : MVT::integer_valuetypes())
175     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
176       setLoadExtAction(Ext, T, MVT::i1, Promote);
177
178   // Trap lowers to wasm unreachable
179   setOperationAction(ISD::TRAP, MVT::Other, Legal);
180 }
181
182 FastISel *WebAssemblyTargetLowering::createFastISel(
183     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
184   return WebAssembly::createFastISel(FuncInfo, LibInfo);
185 }
186
187 bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
188     const GlobalAddressSDNode *GA) const {
189   // The WebAssembly target doesn't support folding offsets into global
190   // addresses.
191   return false;
192 }
193
194 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
195                                                       EVT VT) const {
196   return VT.getSimpleVT();
197 }
198
199 const char *
200 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
201   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
202   case WebAssemblyISD::FIRST_NUMBER:
203     break;
204 #define HANDLE_NODETYPE(NODE)                                                  \
205   case WebAssemblyISD::NODE:                                                   \
206     return "WebAssemblyISD::" #NODE;
207 #include "WebAssemblyISD.def"
208 #undef HANDLE_NODETYPE
209   }
210   return nullptr;
211 }
212
213 std::pair<unsigned, const TargetRegisterClass *>
214 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
215     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
216   // First, see if this is a constraint that directly corresponds to a
217   // WebAssembly register class.
218   if (Constraint.size() == 1) {
219     switch (Constraint[0]) {
220     case 'r':
221       return std::make_pair(0U, &WebAssembly::I32RegClass);
222     default:
223       break;
224     }
225   }
226
227   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
228 }
229
230 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
231   // Assume ctz is a relatively cheap operation.
232   return true;
233 }
234
235 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
236   // Assume clz is a relatively cheap operation.
237   return true;
238 }
239
240 //===----------------------------------------------------------------------===//
241 // WebAssembly Lowering private implementation.
242 //===----------------------------------------------------------------------===//
243
244 //===----------------------------------------------------------------------===//
245 // Lowering Code
246 //===----------------------------------------------------------------------===//
247
248 static void fail(SDLoc DL, SelectionDAG &DAG, const char *msg) {
249   MachineFunction &MF = DAG.getMachineFunction();
250   DAG.getContext()->diagnose(
251       DiagnosticInfoUnsupported(DL, *MF.getFunction(), msg, SDValue()));
252 }
253
254 SDValue
255 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
256                                      SmallVectorImpl<SDValue> &InVals) const {
257   SelectionDAG &DAG = CLI.DAG;
258   SDLoc DL = CLI.DL;
259   SDValue Chain = CLI.Chain;
260   SDValue Callee = CLI.Callee;
261   MachineFunction &MF = DAG.getMachineFunction();
262
263   CallingConv::ID CallConv = CLI.CallConv;
264   if (CallConv != CallingConv::C &&
265       CallConv != CallingConv::Fast &&
266       CallConv != CallingConv::Cold)
267     fail(DL, DAG,
268          "WebAssembly doesn't support language-specific or target-specific "
269          "calling conventions yet");
270   if (CLI.IsPatchPoint)
271     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
272
273   // WebAssembly doesn't currently support explicit tail calls. If they are
274   // required, fail. Otherwise, just disable them.
275   if ((CallConv == CallingConv::Fast && CLI.IsTailCall &&
276        MF.getTarget().Options.GuaranteedTailCallOpt) ||
277       (CLI.CS && CLI.CS->isMustTailCall()))
278     fail(DL, DAG, "WebAssembly doesn't support tail call yet");
279   CLI.IsTailCall = false;
280
281   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
282
283   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
284   if (Ins.size() > 1)
285     fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
286
287   bool IsVarArg = CLI.IsVarArg;
288   if (IsVarArg)
289     fail(DL, DAG, "WebAssembly doesn't support varargs yet");
290
291   // Analyze operands of the call, assigning locations to each operand.
292   SmallVector<CCValAssign, 16> ArgLocs;
293   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
294   unsigned NumBytes = CCInfo.getNextStackOffset();
295
296   auto PtrVT = getPointerTy(MF.getDataLayout());
297   auto Zero = DAG.getConstant(0, DL, PtrVT, true);
298   auto NB = DAG.getConstant(NumBytes, DL, PtrVT, true);
299   Chain = DAG.getCALLSEQ_START(Chain, NB, DL);
300
301   SmallVector<SDValue, 16> Ops;
302   Ops.push_back(Chain);
303   Ops.push_back(Callee);
304   Ops.append(OutVals.begin(), OutVals.end());
305
306   SmallVector<EVT, 8> Tys;
307   for (const auto &In : Ins)
308     Tys.push_back(In.VT);
309   Tys.push_back(MVT::Other);
310   SDVTList TyList = DAG.getVTList(Tys);
311   SDValue Res =
312       DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1,
313                   DL, TyList, Ops);
314   if (Ins.empty()) {
315     Chain = Res;
316   } else {
317     InVals.push_back(Res);
318     Chain = Res.getValue(1);
319   }
320
321   Chain = DAG.getCALLSEQ_END(Chain, NB, Zero, SDValue(), DL);
322
323   return Chain;
324 }
325
326 bool WebAssemblyTargetLowering::CanLowerReturn(
327     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
328     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
329   // WebAssembly can't currently handle returning tuples.
330   return Outs.size() <= 1;
331 }
332
333 SDValue WebAssemblyTargetLowering::LowerReturn(
334     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
335     const SmallVectorImpl<ISD::OutputArg> &Outs,
336     const SmallVectorImpl<SDValue> &OutVals, SDLoc DL,
337     SelectionDAG &DAG) const {
338   assert(Outs.size() <= 1 && "WebAssembly can only return up to one value");
339   if (CallConv != CallingConv::C)
340     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
341   if (IsVarArg)
342     fail(DL, DAG, "WebAssembly doesn't support varargs yet");
343
344   SmallVector<SDValue, 4> RetOps(1, Chain);
345   RetOps.append(OutVals.begin(), OutVals.end());
346   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
347
348   // Record the number and types of the return values.
349   for (const ISD::OutputArg &Out : Outs) {
350     if (Out.Flags.isByVal())
351       fail(DL, DAG, "WebAssembly hasn't implemented byval results");
352     if (Out.Flags.isInAlloca())
353       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
354     if (Out.Flags.isNest())
355       fail(DL, DAG, "WebAssembly hasn't implemented nest results");
356     if (Out.Flags.isInConsecutiveRegs())
357       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
358     if (Out.Flags.isInConsecutiveRegsLast())
359       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
360     if (!Out.IsFixed)
361       fail(DL, DAG, "WebAssembly doesn't support non-fixed results yet");
362   }
363
364   return Chain;
365 }
366
367 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
368     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
369     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
370     SmallVectorImpl<SDValue> &InVals) const {
371   MachineFunction &MF = DAG.getMachineFunction();
372
373   if (CallConv != CallingConv::C)
374     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
375   if (IsVarArg)
376     fail(DL, DAG, "WebAssembly doesn't support varargs yet");
377
378   for (const ISD::InputArg &In : Ins) {
379     if (In.Flags.isByVal())
380       fail(DL, DAG, "WebAssembly hasn't implemented byval arguments");
381     if (In.Flags.isInAlloca())
382       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
383     if (In.Flags.isNest())
384       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
385     if (In.Flags.isInConsecutiveRegs())
386       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
387     if (In.Flags.isInConsecutiveRegsLast())
388       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
389     // FIXME Do something with In.getOrigAlign()?
390     InVals.push_back(
391         In.Used
392             ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
393                           DAG.getTargetConstant(InVals.size(), DL, MVT::i32))
394             : DAG.getNode(ISD::UNDEF, DL, In.VT));
395
396     // Record the number and types of arguments.
397     MF.getInfo<WebAssemblyFunctionInfo>()->addParam(In.VT);
398   }
399
400   return Chain;
401 }
402
403 //===----------------------------------------------------------------------===//
404 //  Custom lowering hooks.
405 //===----------------------------------------------------------------------===//
406
407 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
408                                                   SelectionDAG &DAG) const {
409   switch (Op.getOpcode()) {
410   default:
411     llvm_unreachable("unimplemented operation lowering");
412     return SDValue();
413   case ISD::GlobalAddress:
414     return LowerGlobalAddress(Op, DAG);
415   case ISD::JumpTable:
416     return LowerJumpTable(Op, DAG);
417   case ISD::BR_JT:
418     return LowerBR_JT(Op, DAG);
419   }
420 }
421
422 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
423                                                       SelectionDAG &DAG) const {
424   SDLoc DL(Op);
425   const auto *GA = cast<GlobalAddressSDNode>(Op);
426   EVT VT = Op.getValueType();
427   assert(GA->getOffset() == 0 &&
428          "offsets on global addresses are forbidden by isOffsetFoldingLegal");
429   assert(GA->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
430   if (GA->getAddressSpace() != 0)
431     fail(DL, DAG, "WebAssembly only expects the 0 address space");
432   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
433                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT));
434 }
435
436 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
437                                                   SelectionDAG &DAG) const {
438   // There's no need for a Wrapper node because we always incorporate a jump
439   // table operand into a TABLESWITCH instruction, rather than ever
440   // materializing it in a register.
441   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
442   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
443                                 JT->getTargetFlags());
444 }
445
446 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
447                                               SelectionDAG &DAG) const {
448   SDLoc DL(Op);
449   SDValue Chain = Op.getOperand(0);
450   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
451   SDValue Index = Op.getOperand(2);
452   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
453
454   SmallVector<SDValue, 8> Ops;
455   Ops.push_back(Chain);
456   Ops.push_back(Index);
457
458   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
459   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
460
461   // TODO: For now, we just pick something arbitrary for a default case for now.
462   // We really want to sniff out the guard and put in the real default case (and
463   // delete the guard).
464   Ops.push_back(DAG.getBasicBlock(MBBs[0]));
465
466   // Add an operand for each case.
467   for (auto MBB : MBBs)
468     Ops.push_back(DAG.getBasicBlock(MBB));
469
470   return DAG.getNode(WebAssemblyISD::TABLESWITCH, DL, MVT::Other, Ops);
471 }
472
473 //===----------------------------------------------------------------------===//
474 //                          WebAssembly Optimization Hooks
475 //===----------------------------------------------------------------------===//
476
477 MCSection *WebAssemblyTargetObjectFile::SelectSectionForGlobal(
478     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
479     const TargetMachine &TM) const {
480   // TODO: Be more sophisticated than this.
481   return isa<Function>(GV) ? getTextSection() : getDataSection();
482 }