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