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