MSP430ISelDAGToDAG.cpp revision 327952
1//===-- MSP430ISelDAGToDAG.cpp - A dag to dag inst selector for MSP430 ----===//
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// This file defines an instruction selector for the MSP430 target.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MSP430.h"
15#include "MSP430TargetMachine.h"
16#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/CodeGen/SelectionDAG.h"
21#include "llvm/CodeGen/SelectionDAGISel.h"
22#include "llvm/CodeGen/TargetLowering.h"
23#include "llvm/IR/CallingConv.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31using namespace llvm;
32
33#define DEBUG_TYPE "msp430-isel"
34
35namespace {
36  struct MSP430ISelAddressMode {
37    enum {
38      RegBase,
39      FrameIndexBase
40    } BaseType;
41
42    struct {            // This is really a union, discriminated by BaseType!
43      SDValue Reg;
44      int FrameIndex;
45    } Base;
46
47    int16_t Disp;
48    const GlobalValue *GV;
49    const Constant *CP;
50    const BlockAddress *BlockAddr;
51    const char *ES;
52    int JT;
53    unsigned Align;    // CP alignment.
54
55    MSP430ISelAddressMode()
56      : BaseType(RegBase), Disp(0), GV(nullptr), CP(nullptr),
57        BlockAddr(nullptr), ES(nullptr), JT(-1), Align(0) {
58    }
59
60    bool hasSymbolicDisplacement() const {
61      return GV != nullptr || CP != nullptr || ES != nullptr || JT != -1;
62    }
63
64#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
65    LLVM_DUMP_METHOD void dump() {
66      errs() << "MSP430ISelAddressMode " << this << '\n';
67      if (BaseType == RegBase && Base.Reg.getNode() != nullptr) {
68        errs() << "Base.Reg ";
69        Base.Reg.getNode()->dump();
70      } else if (BaseType == FrameIndexBase) {
71        errs() << " Base.FrameIndex " << Base.FrameIndex << '\n';
72      }
73      errs() << " Disp " << Disp << '\n';
74      if (GV) {
75        errs() << "GV ";
76        GV->dump();
77      } else if (CP) {
78        errs() << " CP ";
79        CP->dump();
80        errs() << " Align" << Align << '\n';
81      } else if (ES) {
82        errs() << "ES ";
83        errs() << ES << '\n';
84      } else if (JT != -1)
85        errs() << " JT" << JT << " Align" << Align << '\n';
86    }
87#endif
88  };
89}
90
91/// MSP430DAGToDAGISel - MSP430 specific code to select MSP430 machine
92/// instructions for SelectionDAG operations.
93///
94namespace {
95  class MSP430DAGToDAGISel : public SelectionDAGISel {
96  public:
97    MSP430DAGToDAGISel(MSP430TargetMachine &TM, CodeGenOpt::Level OptLevel)
98        : SelectionDAGISel(TM, OptLevel) {}
99
100    StringRef getPassName() const override {
101      return "MSP430 DAG->DAG Pattern Instruction Selection";
102    }
103
104    bool MatchAddress(SDValue N, MSP430ISelAddressMode &AM);
105    bool MatchWrapper(SDValue N, MSP430ISelAddressMode &AM);
106    bool MatchAddressBase(SDValue N, MSP430ISelAddressMode &AM);
107
108    bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
109                                      std::vector<SDValue> &OutOps) override;
110
111    // Include the pieces autogenerated from the target description.
112  #include "MSP430GenDAGISel.inc"
113
114  private:
115    void Select(SDNode *N) override;
116    bool tryIndexedLoad(SDNode *Op);
117    bool tryIndexedBinOp(SDNode *Op, SDValue N1, SDValue N2, unsigned Opc8,
118                         unsigned Opc16);
119
120    bool SelectAddr(SDValue Addr, SDValue &Base, SDValue &Disp);
121  };
122}  // end anonymous namespace
123
124/// createMSP430ISelDag - This pass converts a legalized DAG into a
125/// MSP430-specific DAG, ready for instruction scheduling.
126///
127FunctionPass *llvm::createMSP430ISelDag(MSP430TargetMachine &TM,
128                                        CodeGenOpt::Level OptLevel) {
129  return new MSP430DAGToDAGISel(TM, OptLevel);
130}
131
132
133/// MatchWrapper - Try to match MSP430ISD::Wrapper node into an addressing mode.
134/// These wrap things that will resolve down into a symbol reference.  If no
135/// match is possible, this returns true, otherwise it returns false.
136bool MSP430DAGToDAGISel::MatchWrapper(SDValue N, MSP430ISelAddressMode &AM) {
137  // If the addressing mode already has a symbol as the displacement, we can
138  // never match another symbol.
139  if (AM.hasSymbolicDisplacement())
140    return true;
141
142  SDValue N0 = N.getOperand(0);
143
144  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
145    AM.GV = G->getGlobal();
146    AM.Disp += G->getOffset();
147    //AM.SymbolFlags = G->getTargetFlags();
148  } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
149    AM.CP = CP->getConstVal();
150    AM.Align = CP->getAlignment();
151    AM.Disp += CP->getOffset();
152    //AM.SymbolFlags = CP->getTargetFlags();
153  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
154    AM.ES = S->getSymbol();
155    //AM.SymbolFlags = S->getTargetFlags();
156  } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
157    AM.JT = J->getIndex();
158    //AM.SymbolFlags = J->getTargetFlags();
159  } else {
160    AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
161    //AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
162  }
163  return false;
164}
165
166/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
167/// specified addressing mode without any further recursion.
168bool MSP430DAGToDAGISel::MatchAddressBase(SDValue N, MSP430ISelAddressMode &AM) {
169  // Is the base register already occupied?
170  if (AM.BaseType != MSP430ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
171    // If so, we cannot select it.
172    return true;
173  }
174
175  // Default, generate it as a register.
176  AM.BaseType = MSP430ISelAddressMode::RegBase;
177  AM.Base.Reg = N;
178  return false;
179}
180
181bool MSP430DAGToDAGISel::MatchAddress(SDValue N, MSP430ISelAddressMode &AM) {
182  DEBUG(errs() << "MatchAddress: "; AM.dump());
183
184  switch (N.getOpcode()) {
185  default: break;
186  case ISD::Constant: {
187    uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
188    AM.Disp += Val;
189    return false;
190  }
191
192  case MSP430ISD::Wrapper:
193    if (!MatchWrapper(N, AM))
194      return false;
195    break;
196
197  case ISD::FrameIndex:
198    if (AM.BaseType == MSP430ISelAddressMode::RegBase
199        && AM.Base.Reg.getNode() == nullptr) {
200      AM.BaseType = MSP430ISelAddressMode::FrameIndexBase;
201      AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
202      return false;
203    }
204    break;
205
206  case ISD::ADD: {
207    MSP430ISelAddressMode Backup = AM;
208    if (!MatchAddress(N.getNode()->getOperand(0), AM) &&
209        !MatchAddress(N.getNode()->getOperand(1), AM))
210      return false;
211    AM = Backup;
212    if (!MatchAddress(N.getNode()->getOperand(1), AM) &&
213        !MatchAddress(N.getNode()->getOperand(0), AM))
214      return false;
215    AM = Backup;
216
217    break;
218  }
219
220  case ISD::OR:
221    // Handle "X | C" as "X + C" iff X is known to have C bits clear.
222    if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
223      MSP430ISelAddressMode Backup = AM;
224      uint64_t Offset = CN->getSExtValue();
225      // Start with the LHS as an addr mode.
226      if (!MatchAddress(N.getOperand(0), AM) &&
227          // Address could not have picked a GV address for the displacement.
228          AM.GV == nullptr &&
229          // Check to see if the LHS & C is zero.
230          CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
231        AM.Disp += Offset;
232        return false;
233      }
234      AM = Backup;
235    }
236    break;
237  }
238
239  return MatchAddressBase(N, AM);
240}
241
242/// SelectAddr - returns true if it is able pattern match an addressing mode.
243/// It returns the operands which make up the maximal addressing mode it can
244/// match by reference.
245bool MSP430DAGToDAGISel::SelectAddr(SDValue N,
246                                    SDValue &Base, SDValue &Disp) {
247  MSP430ISelAddressMode AM;
248
249  if (MatchAddress(N, AM))
250    return false;
251
252  EVT VT = N.getValueType();
253  if (AM.BaseType == MSP430ISelAddressMode::RegBase) {
254    if (!AM.Base.Reg.getNode())
255      AM.Base.Reg = CurDAG->getRegister(0, VT);
256  }
257
258  Base = (AM.BaseType == MSP430ISelAddressMode::FrameIndexBase)
259             ? CurDAG->getTargetFrameIndex(
260                   AM.Base.FrameIndex,
261                   getTargetLowering()->getPointerTy(CurDAG->getDataLayout()))
262             : AM.Base.Reg;
263
264  if (AM.GV)
265    Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(N),
266                                          MVT::i16, AM.Disp,
267                                          0/*AM.SymbolFlags*/);
268  else if (AM.CP)
269    Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i16,
270                                         AM.Align, AM.Disp, 0/*AM.SymbolFlags*/);
271  else if (AM.ES)
272    Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i16, 0/*AM.SymbolFlags*/);
273  else if (AM.JT != -1)
274    Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i16, 0/*AM.SymbolFlags*/);
275  else if (AM.BlockAddr)
276    Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, 0,
277                                         0/*AM.SymbolFlags*/);
278  else
279    Disp = CurDAG->getTargetConstant(AM.Disp, SDLoc(N), MVT::i16);
280
281  return true;
282}
283
284bool MSP430DAGToDAGISel::
285SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
286                             std::vector<SDValue> &OutOps) {
287  SDValue Op0, Op1;
288  switch (ConstraintID) {
289  default: return true;
290  case InlineAsm::Constraint_m: // memory
291    if (!SelectAddr(Op, Op0, Op1))
292      return true;
293    break;
294  }
295
296  OutOps.push_back(Op0);
297  OutOps.push_back(Op1);
298  return false;
299}
300
301static bool isValidIndexedLoad(const LoadSDNode *LD) {
302  ISD::MemIndexedMode AM = LD->getAddressingMode();
303  if (AM != ISD::POST_INC || LD->getExtensionType() != ISD::NON_EXTLOAD)
304    return false;
305
306  EVT VT = LD->getMemoryVT();
307
308  switch (VT.getSimpleVT().SimpleTy) {
309  case MVT::i8:
310    // Sanity check
311    if (cast<ConstantSDNode>(LD->getOffset())->getZExtValue() != 1)
312      return false;
313
314    break;
315  case MVT::i16:
316    // Sanity check
317    if (cast<ConstantSDNode>(LD->getOffset())->getZExtValue() != 2)
318      return false;
319
320    break;
321  default:
322    return false;
323  }
324
325  return true;
326}
327
328bool MSP430DAGToDAGISel::tryIndexedLoad(SDNode *N) {
329  LoadSDNode *LD = cast<LoadSDNode>(N);
330  if (!isValidIndexedLoad(LD))
331    return false;
332
333  MVT VT = LD->getMemoryVT().getSimpleVT();
334
335  unsigned Opcode = 0;
336  switch (VT.SimpleTy) {
337  case MVT::i8:
338    Opcode = MSP430::MOV8rm_POST;
339    break;
340  case MVT::i16:
341    Opcode = MSP430::MOV16rm_POST;
342    break;
343  default:
344    return false;
345  }
346
347  ReplaceNode(N,
348              CurDAG->getMachineNode(Opcode, SDLoc(N), VT, MVT::i16, MVT::Other,
349                                     LD->getBasePtr(), LD->getChain()));
350  return true;
351}
352
353bool MSP430DAGToDAGISel::tryIndexedBinOp(SDNode *Op, SDValue N1, SDValue N2,
354                                         unsigned Opc8, unsigned Opc16) {
355  if (N1.getOpcode() == ISD::LOAD &&
356      N1.hasOneUse() &&
357      IsLegalToFold(N1, Op, Op, OptLevel)) {
358    LoadSDNode *LD = cast<LoadSDNode>(N1);
359    if (!isValidIndexedLoad(LD))
360      return false;
361
362    MVT VT = LD->getMemoryVT().getSimpleVT();
363    unsigned Opc = (VT == MVT::i16 ? Opc16 : Opc8);
364    MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
365    MemRefs0[0] = cast<MemSDNode>(N1)->getMemOperand();
366    SDValue Ops0[] = { N2, LD->getBasePtr(), LD->getChain() };
367    SDNode *ResNode =
368      CurDAG->SelectNodeTo(Op, Opc, VT, MVT::i16, MVT::Other, Ops0);
369    cast<MachineSDNode>(ResNode)->setMemRefs(MemRefs0, MemRefs0 + 1);
370    // Transfer chain.
371    ReplaceUses(SDValue(N1.getNode(), 2), SDValue(ResNode, 2));
372    // Transfer writeback.
373    ReplaceUses(SDValue(N1.getNode(), 1), SDValue(ResNode, 1));
374    return true;
375  }
376
377  return false;
378}
379
380
381void MSP430DAGToDAGISel::Select(SDNode *Node) {
382  SDLoc dl(Node);
383
384  // Dump information about the Node being selected
385  DEBUG(errs() << "Selecting: ");
386  DEBUG(Node->dump(CurDAG));
387  DEBUG(errs() << "\n");
388
389  // If we have a custom node, we already have selected!
390  if (Node->isMachineOpcode()) {
391    DEBUG(errs() << "== ";
392          Node->dump(CurDAG);
393          errs() << "\n");
394    Node->setNodeId(-1);
395    return;
396  }
397
398  // Few custom selection stuff.
399  switch (Node->getOpcode()) {
400  default: break;
401  case ISD::FrameIndex: {
402    assert(Node->getValueType(0) == MVT::i16);
403    int FI = cast<FrameIndexSDNode>(Node)->getIndex();
404    SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i16);
405    if (Node->hasOneUse()) {
406      CurDAG->SelectNodeTo(Node, MSP430::ADDframe, MVT::i16, TFI,
407                           CurDAG->getTargetConstant(0, dl, MVT::i16));
408      return;
409    }
410    ReplaceNode(Node, CurDAG->getMachineNode(
411                          MSP430::ADDframe, dl, MVT::i16, TFI,
412                          CurDAG->getTargetConstant(0, dl, MVT::i16)));
413    return;
414  }
415  case ISD::LOAD:
416    if (tryIndexedLoad(Node))
417      return;
418    // Other cases are autogenerated.
419    break;
420  case ISD::ADD:
421    if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
422                        MSP430::ADD8rm_POST, MSP430::ADD16rm_POST))
423      return;
424    else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
425                             MSP430::ADD8rm_POST, MSP430::ADD16rm_POST))
426      return;
427
428    // Other cases are autogenerated.
429    break;
430  case ISD::SUB:
431    if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
432                        MSP430::SUB8rm_POST, MSP430::SUB16rm_POST))
433      return;
434
435    // Other cases are autogenerated.
436    break;
437  case ISD::AND:
438    if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
439                        MSP430::AND8rm_POST, MSP430::AND16rm_POST))
440      return;
441    else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
442                             MSP430::AND8rm_POST, MSP430::AND16rm_POST))
443      return;
444
445    // Other cases are autogenerated.
446    break;
447  case ISD::OR:
448    if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
449                        MSP430::OR8rm_POST, MSP430::OR16rm_POST))
450      return;
451    else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
452                             MSP430::OR8rm_POST, MSP430::OR16rm_POST))
453      return;
454
455    // Other cases are autogenerated.
456    break;
457  case ISD::XOR:
458    if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
459                        MSP430::XOR8rm_POST, MSP430::XOR16rm_POST))
460      return;
461    else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
462                             MSP430::XOR8rm_POST, MSP430::XOR16rm_POST))
463      return;
464
465    // Other cases are autogenerated.
466    break;
467  }
468
469  // Select the default instruction
470  SelectCode(Node);
471}
472