xref: /llvm-project/llvm/lib/Target/AVR/AVRInstrInfo.cpp (revision f7d8336a2fb4fad4a6efe5af9b0a10ddd970f6d3)
1 //===-- AVRInstrInfo.cpp - AVR Instruction Information --------------------===//
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 contains the AVR implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AVRInstrInfo.h"
14 
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineMemOperand.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/Support/ErrorHandling.h"
20 
21 #include "AVR.h"
22 #include "AVRMachineFunctionInfo.h"
23 #include "AVRRegisterInfo.h"
24 #include "AVRTargetMachine.h"
25 #include "MCTargetDesc/AVRMCTargetDesc.h"
26 
27 #define GET_INSTRINFO_CTOR_DTOR
28 #include "AVRGenInstrInfo.inc"
29 
30 namespace llvm {
31 
32 AVRInstrInfo::AVRInstrInfo(AVRSubtarget &STI)
33     : AVRGenInstrInfo(AVR::ADJCALLSTACKDOWN, AVR::ADJCALLSTACKUP), RI(),
34       STI(STI) {}
35 
36 void AVRInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
37                                MachineBasicBlock::iterator MI,
38                                const DebugLoc &DL, MCRegister DestReg,
39                                MCRegister SrcReg, bool KillSrc,
40                                bool RenamableDest, bool RenamableSrc) const {
41   const AVRRegisterInfo &TRI = *STI.getRegisterInfo();
42   unsigned Opc;
43 
44   if (AVR::DREGSRegClass.contains(DestReg, SrcReg)) {
45     // If our AVR has `movw`, let's emit that; otherwise let's emit two separate
46     // `mov`s.
47     if (STI.hasMOVW() && AVR::DREGSMOVWRegClass.contains(DestReg, SrcReg)) {
48       BuildMI(MBB, MI, DL, get(AVR::MOVWRdRr), DestReg)
49           .addReg(SrcReg, getKillRegState(KillSrc));
50     } else {
51       Register DestLo, DestHi, SrcLo, SrcHi;
52 
53       TRI.splitReg(DestReg, DestLo, DestHi);
54       TRI.splitReg(SrcReg, SrcLo, SrcHi);
55 
56       // Emit the copies.
57       // The original instruction was for a register pair, of which only one
58       // register might have been live. Add 'undef' to satisfy the machine
59       // verifier, when subreg liveness is enabled.
60       // TODO: Eliminate these unnecessary copies.
61       if (DestLo == SrcHi) {
62         BuildMI(MBB, MI, DL, get(AVR::MOVRdRr), DestHi)
63             .addReg(SrcHi, getKillRegState(KillSrc) | RegState::Undef);
64         BuildMI(MBB, MI, DL, get(AVR::MOVRdRr), DestLo)
65             .addReg(SrcLo, getKillRegState(KillSrc) | RegState::Undef);
66       } else {
67         BuildMI(MBB, MI, DL, get(AVR::MOVRdRr), DestLo)
68             .addReg(SrcLo, getKillRegState(KillSrc) | RegState::Undef);
69         BuildMI(MBB, MI, DL, get(AVR::MOVRdRr), DestHi)
70             .addReg(SrcHi, getKillRegState(KillSrc) | RegState::Undef);
71       }
72     }
73   } else {
74     if (AVR::GPR8RegClass.contains(DestReg, SrcReg)) {
75       Opc = AVR::MOVRdRr;
76     } else if (SrcReg == AVR::SP && AVR::DREGSRegClass.contains(DestReg)) {
77       Opc = AVR::SPREAD;
78     } else if (DestReg == AVR::SP && AVR::DREGSRegClass.contains(SrcReg)) {
79       Opc = AVR::SPWRITE;
80     } else {
81       llvm_unreachable("Impossible reg-to-reg copy");
82     }
83 
84     BuildMI(MBB, MI, DL, get(Opc), DestReg)
85         .addReg(SrcReg, getKillRegState(KillSrc));
86   }
87 }
88 
89 Register AVRInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
90                                            int &FrameIndex) const {
91   switch (MI.getOpcode()) {
92   case AVR::LDDRdPtrQ:
93   case AVR::LDDWRdYQ: { //: FIXME: remove this once PR13375 gets fixed
94     if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
95         MI.getOperand(2).getImm() == 0) {
96       FrameIndex = MI.getOperand(1).getIndex();
97       return MI.getOperand(0).getReg();
98     }
99     break;
100   }
101   default:
102     break;
103   }
104 
105   return 0;
106 }
107 
108 Register AVRInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
109                                           int &FrameIndex) const {
110   switch (MI.getOpcode()) {
111   case AVR::STDPtrQRr:
112   case AVR::STDWPtrQRr: {
113     if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
114         MI.getOperand(1).getImm() == 0) {
115       FrameIndex = MI.getOperand(0).getIndex();
116       return MI.getOperand(2).getReg();
117     }
118     break;
119   }
120   default:
121     break;
122   }
123 
124   return 0;
125 }
126 
127 void AVRInstrInfo::storeRegToStackSlot(
128     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
129     bool isKill, int FrameIndex, const TargetRegisterClass *RC,
130     const TargetRegisterInfo *TRI, Register VReg,
131     MachineInstr::MIFlag Flags) const {
132   MachineFunction &MF = *MBB.getParent();
133   AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
134 
135   AFI->setHasSpills(true);
136 
137   const MachineFrameInfo &MFI = MF.getFrameInfo();
138 
139   MachineMemOperand *MMO = MF.getMachineMemOperand(
140       MachinePointerInfo::getFixedStack(MF, FrameIndex),
141       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIndex),
142       MFI.getObjectAlign(FrameIndex));
143 
144   unsigned Opcode = 0;
145   if (TRI->isTypeLegalForClass(*RC, MVT::i8)) {
146     Opcode = AVR::STDPtrQRr;
147   } else if (TRI->isTypeLegalForClass(*RC, MVT::i16)) {
148     Opcode = AVR::STDWPtrQRr;
149   } else {
150     llvm_unreachable("Cannot store this register into a stack slot!");
151   }
152 
153   BuildMI(MBB, MI, DebugLoc(), get(Opcode))
154       .addFrameIndex(FrameIndex)
155       .addImm(0)
156       .addReg(SrcReg, getKillRegState(isKill))
157       .addMemOperand(MMO);
158 }
159 
160 void AVRInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
161                                         MachineBasicBlock::iterator MI,
162                                         Register DestReg, int FrameIndex,
163                                         const TargetRegisterClass *RC,
164                                         const TargetRegisterInfo *TRI,
165                                         Register VReg,
166                                         MachineInstr::MIFlag Flags) const {
167   MachineFunction &MF = *MBB.getParent();
168   const MachineFrameInfo &MFI = MF.getFrameInfo();
169 
170   MachineMemOperand *MMO = MF.getMachineMemOperand(
171       MachinePointerInfo::getFixedStack(MF, FrameIndex),
172       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIndex),
173       MFI.getObjectAlign(FrameIndex));
174 
175   unsigned Opcode = 0;
176   if (TRI->isTypeLegalForClass(*RC, MVT::i8)) {
177     Opcode = AVR::LDDRdPtrQ;
178   } else if (TRI->isTypeLegalForClass(*RC, MVT::i16)) {
179     // Opcode = AVR::LDDWRdPtrQ;
180     //: FIXME: remove this once PR13375 gets fixed
181     Opcode = AVR::LDDWRdYQ;
182   } else {
183     llvm_unreachable("Cannot load this register from a stack slot!");
184   }
185 
186   BuildMI(MBB, MI, DebugLoc(), get(Opcode), DestReg)
187       .addFrameIndex(FrameIndex)
188       .addImm(0)
189       .addMemOperand(MMO);
190 }
191 
192 const MCInstrDesc &AVRInstrInfo::getBrCond(AVRCC::CondCodes CC) const {
193   switch (CC) {
194   default:
195     llvm_unreachable("Unknown condition code!");
196   case AVRCC::COND_EQ:
197     return get(AVR::BREQk);
198   case AVRCC::COND_NE:
199     return get(AVR::BRNEk);
200   case AVRCC::COND_GE:
201     return get(AVR::BRGEk);
202   case AVRCC::COND_LT:
203     return get(AVR::BRLTk);
204   case AVRCC::COND_SH:
205     return get(AVR::BRSHk);
206   case AVRCC::COND_LO:
207     return get(AVR::BRLOk);
208   case AVRCC::COND_MI:
209     return get(AVR::BRMIk);
210   case AVRCC::COND_PL:
211     return get(AVR::BRPLk);
212   }
213 }
214 
215 AVRCC::CondCodes AVRInstrInfo::getCondFromBranchOpc(unsigned Opc) const {
216   switch (Opc) {
217   default:
218     return AVRCC::COND_INVALID;
219   case AVR::BREQk:
220     return AVRCC::COND_EQ;
221   case AVR::BRNEk:
222     return AVRCC::COND_NE;
223   case AVR::BRSHk:
224     return AVRCC::COND_SH;
225   case AVR::BRLOk:
226     return AVRCC::COND_LO;
227   case AVR::BRMIk:
228     return AVRCC::COND_MI;
229   case AVR::BRPLk:
230     return AVRCC::COND_PL;
231   case AVR::BRGEk:
232     return AVRCC::COND_GE;
233   case AVR::BRLTk:
234     return AVRCC::COND_LT;
235   }
236 }
237 
238 AVRCC::CondCodes AVRInstrInfo::getOppositeCondition(AVRCC::CondCodes CC) const {
239   switch (CC) {
240   default:
241     llvm_unreachable("Invalid condition!");
242   case AVRCC::COND_EQ:
243     return AVRCC::COND_NE;
244   case AVRCC::COND_NE:
245     return AVRCC::COND_EQ;
246   case AVRCC::COND_SH:
247     return AVRCC::COND_LO;
248   case AVRCC::COND_LO:
249     return AVRCC::COND_SH;
250   case AVRCC::COND_GE:
251     return AVRCC::COND_LT;
252   case AVRCC::COND_LT:
253     return AVRCC::COND_GE;
254   case AVRCC::COND_MI:
255     return AVRCC::COND_PL;
256   case AVRCC::COND_PL:
257     return AVRCC::COND_MI;
258   }
259 }
260 
261 bool AVRInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
262                                  MachineBasicBlock *&TBB,
263                                  MachineBasicBlock *&FBB,
264                                  SmallVectorImpl<MachineOperand> &Cond,
265                                  bool AllowModify) const {
266   // Start from the bottom of the block and work up, examining the
267   // terminator instructions.
268   MachineBasicBlock::iterator I = MBB.end();
269   MachineBasicBlock::iterator UnCondBrIter = MBB.end();
270 
271   while (I != MBB.begin()) {
272     --I;
273     if (I->isDebugInstr()) {
274       continue;
275     }
276 
277     // Working from the bottom, when we see a non-terminator
278     // instruction, we're done.
279     if (!isUnpredicatedTerminator(*I)) {
280       break;
281     }
282 
283     // A terminator that isn't a branch can't easily be handled
284     // by this analysis.
285     if (!I->getDesc().isBranch()) {
286       return true;
287     }
288 
289     // Handle unconditional branches.
290     //: TODO: add here jmp
291     if (I->getOpcode() == AVR::RJMPk) {
292       UnCondBrIter = I;
293 
294       if (!AllowModify) {
295         TBB = I->getOperand(0).getMBB();
296         continue;
297       }
298 
299       // If the block has any instructions after a JMP, delete them.
300       MBB.erase(std::next(I), MBB.end());
301 
302       Cond.clear();
303       FBB = nullptr;
304 
305       // Delete the JMP if it's equivalent to a fall-through.
306       if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
307         TBB = nullptr;
308         I->eraseFromParent();
309         I = MBB.end();
310         UnCondBrIter = MBB.end();
311         continue;
312       }
313 
314       // TBB is used to indicate the unconditinal destination.
315       TBB = I->getOperand(0).getMBB();
316       continue;
317     }
318 
319     // Handle conditional branches.
320     AVRCC::CondCodes BranchCode = getCondFromBranchOpc(I->getOpcode());
321     if (BranchCode == AVRCC::COND_INVALID) {
322       return true; // Can't handle indirect branch.
323     }
324 
325     // Working from the bottom, handle the first conditional branch.
326     if (Cond.empty()) {
327       MachineBasicBlock *TargetBB = I->getOperand(0).getMBB();
328       if (AllowModify && UnCondBrIter != MBB.end() &&
329           MBB.isLayoutSuccessor(TargetBB)) {
330         // If we can modify the code and it ends in something like:
331         //
332         //     jCC L1
333         //     jmp L2
334         //   L1:
335         //     ...
336         //   L2:
337         //
338         // Then we can change this to:
339         //
340         //     jnCC L2
341         //   L1:
342         //     ...
343         //   L2:
344         //
345         // Which is a bit more efficient.
346         // We conditionally jump to the fall-through block.
347         BranchCode = getOppositeCondition(BranchCode);
348         unsigned JNCC = getBrCond(BranchCode).getOpcode();
349         MachineBasicBlock::iterator OldInst = I;
350 
351         BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(JNCC))
352             .addMBB(UnCondBrIter->getOperand(0).getMBB());
353         BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(AVR::RJMPk))
354             .addMBB(TargetBB);
355 
356         OldInst->eraseFromParent();
357         UnCondBrIter->eraseFromParent();
358 
359         // Restart the analysis.
360         UnCondBrIter = MBB.end();
361         I = MBB.end();
362         continue;
363       }
364 
365       FBB = TBB;
366       TBB = I->getOperand(0).getMBB();
367       Cond.push_back(MachineOperand::CreateImm(BranchCode));
368       continue;
369     }
370 
371     // Handle subsequent conditional branches. Only handle the case where all
372     // conditional branches branch to the same destination.
373     assert(Cond.size() == 1);
374     assert(TBB);
375 
376     // Only handle the case where all conditional branches branch to
377     // the same destination.
378     if (TBB != I->getOperand(0).getMBB()) {
379       return true;
380     }
381 
382     AVRCC::CondCodes OldBranchCode = (AVRCC::CondCodes)Cond[0].getImm();
383     // If the conditions are the same, we can leave them alone.
384     if (OldBranchCode == BranchCode) {
385       continue;
386     }
387 
388     return true;
389   }
390 
391   return false;
392 }
393 
394 unsigned AVRInstrInfo::insertBranch(MachineBasicBlock &MBB,
395                                     MachineBasicBlock *TBB,
396                                     MachineBasicBlock *FBB,
397                                     ArrayRef<MachineOperand> Cond,
398                                     const DebugLoc &DL, int *BytesAdded) const {
399   if (BytesAdded)
400     *BytesAdded = 0;
401 
402   // Shouldn't be a fall through.
403   assert(TBB && "insertBranch must not be told to insert a fallthrough");
404   assert((Cond.size() == 1 || Cond.size() == 0) &&
405          "AVR branch conditions have one component!");
406 
407   if (Cond.empty()) {
408     assert(!FBB && "Unconditional branch with multiple successors!");
409     auto &MI = *BuildMI(&MBB, DL, get(AVR::RJMPk)).addMBB(TBB);
410     if (BytesAdded)
411       *BytesAdded += getInstSizeInBytes(MI);
412     return 1;
413   }
414 
415   // Conditional branch.
416   unsigned Count = 0;
417   AVRCC::CondCodes CC = (AVRCC::CondCodes)Cond[0].getImm();
418   auto &CondMI = *BuildMI(&MBB, DL, getBrCond(CC)).addMBB(TBB);
419 
420   if (BytesAdded)
421     *BytesAdded += getInstSizeInBytes(CondMI);
422   ++Count;
423 
424   if (FBB) {
425     // Two-way Conditional branch. Insert the second branch.
426     auto &MI = *BuildMI(&MBB, DL, get(AVR::RJMPk)).addMBB(FBB);
427     if (BytesAdded)
428       *BytesAdded += getInstSizeInBytes(MI);
429     ++Count;
430   }
431 
432   return Count;
433 }
434 
435 unsigned AVRInstrInfo::removeBranch(MachineBasicBlock &MBB,
436                                     int *BytesRemoved) const {
437   if (BytesRemoved)
438     *BytesRemoved = 0;
439 
440   MachineBasicBlock::iterator I = MBB.end();
441   unsigned Count = 0;
442 
443   while (I != MBB.begin()) {
444     --I;
445     if (I->isDebugInstr()) {
446       continue;
447     }
448     //: TODO: add here the missing jmp instructions once they are implemented
449     // like jmp, {e}ijmp, and other cond branches, ...
450     if (I->getOpcode() != AVR::RJMPk &&
451         getCondFromBranchOpc(I->getOpcode()) == AVRCC::COND_INVALID) {
452       break;
453     }
454 
455     // Remove the branch.
456     if (BytesRemoved)
457       *BytesRemoved += getInstSizeInBytes(*I);
458     I->eraseFromParent();
459     I = MBB.end();
460     ++Count;
461   }
462 
463   return Count;
464 }
465 
466 bool AVRInstrInfo::reverseBranchCondition(
467     SmallVectorImpl<MachineOperand> &Cond) const {
468   assert(Cond.size() == 1 && "Invalid AVR branch condition!");
469 
470   AVRCC::CondCodes CC = static_cast<AVRCC::CondCodes>(Cond[0].getImm());
471   Cond[0].setImm(getOppositeCondition(CC));
472 
473   return false;
474 }
475 
476 unsigned AVRInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
477   unsigned Opcode = MI.getOpcode();
478 
479   switch (Opcode) {
480   // A regular instruction
481   default: {
482     const MCInstrDesc &Desc = get(Opcode);
483     return Desc.getSize();
484   }
485   case TargetOpcode::EH_LABEL:
486   case TargetOpcode::IMPLICIT_DEF:
487   case TargetOpcode::KILL:
488   case TargetOpcode::DBG_VALUE:
489     return 0;
490   case TargetOpcode::INLINEASM:
491   case TargetOpcode::INLINEASM_BR: {
492     const MachineFunction &MF = *MI.getParent()->getParent();
493     const AVRTargetMachine &TM =
494         static_cast<const AVRTargetMachine &>(MF.getTarget());
495     const TargetInstrInfo &TII = *STI.getInstrInfo();
496     return TII.getInlineAsmLength(MI.getOperand(0).getSymbolName(),
497                                   *TM.getMCAsmInfo());
498   }
499   }
500 }
501 
502 MachineBasicBlock *
503 AVRInstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
504   switch (MI.getOpcode()) {
505   default:
506     llvm_unreachable("unexpected opcode!");
507   case AVR::JMPk:
508   case AVR::CALLk:
509   case AVR::RCALLk:
510   case AVR::RJMPk:
511   case AVR::BREQk:
512   case AVR::BRNEk:
513   case AVR::BRSHk:
514   case AVR::BRLOk:
515   case AVR::BRMIk:
516   case AVR::BRPLk:
517   case AVR::BRGEk:
518   case AVR::BRLTk:
519     return MI.getOperand(0).getMBB();
520   case AVR::BRBSsk:
521   case AVR::BRBCsk:
522     return MI.getOperand(1).getMBB();
523   case AVR::SBRCRrB:
524   case AVR::SBRSRrB:
525   case AVR::SBICAb:
526   case AVR::SBISAb:
527     llvm_unreachable("unimplemented branch instructions");
528   }
529 }
530 
531 bool AVRInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
532                                          int64_t BrOffset) const {
533 
534   switch (BranchOp) {
535   default:
536     llvm_unreachable("unexpected opcode!");
537   case AVR::JMPk:
538   case AVR::CALLk:
539     return STI.hasJMPCALL();
540   case AVR::RCALLk:
541   case AVR::RJMPk:
542     return isIntN(13, BrOffset);
543   case AVR::BRBSsk:
544   case AVR::BRBCsk:
545   case AVR::BREQk:
546   case AVR::BRNEk:
547   case AVR::BRSHk:
548   case AVR::BRLOk:
549   case AVR::BRMIk:
550   case AVR::BRPLk:
551   case AVR::BRGEk:
552   case AVR::BRLTk:
553     return isIntN(7, BrOffset);
554   }
555 }
556 
557 void AVRInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
558                                         MachineBasicBlock &NewDestBB,
559                                         MachineBasicBlock &RestoreBB,
560                                         const DebugLoc &DL, int64_t BrOffset,
561                                         RegScavenger *RS) const {
562   // This method inserts a *direct* branch (JMP), despite its name.
563   // LLVM calls this method to fixup unconditional branches; it never calls
564   // insertBranch or some hypothetical "insertDirectBranch".
565   // See lib/CodeGen/RegisterRelaxation.cpp for details.
566   // We end up here when a jump is too long for a RJMP instruction.
567   if (STI.hasJMPCALL())
568     BuildMI(&MBB, DL, get(AVR::JMPk)).addMBB(&NewDestBB);
569   else
570     // The RJMP may jump to a far place beyond its legal range. We let the
571     // linker to report 'out of range' rather than crash, or silently emit
572     // incorrect assembly code.
573     BuildMI(&MBB, DL, get(AVR::RJMPk)).addMBB(&NewDestBB);
574 }
575 
576 } // end of namespace llvm
577