8771c68e593145a1a944fa4b148f7a03d564a122
[oota-llvm.git] / lib / Target / ARM / Thumb1FrameLowering.cpp
1 //===-- Thumb1FrameLowering.cpp - Thumb1 Frame Information ----------------===//
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 contains the Thumb1 implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Thumb1FrameLowering.h"
15 #include "ARMMachineFunctionInfo.h"
16 #include "llvm/CodeGen/LivePhysRegs.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22
23 using namespace llvm;
24
25 Thumb1FrameLowering::Thumb1FrameLowering(const ARMSubtarget &sti)
26     : ARMFrameLowering(sti) {}
27
28 bool Thumb1FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const{
29   const MachineFrameInfo *FFI = MF.getFrameInfo();
30   unsigned CFSize = FFI->getMaxCallFrameSize();
31   // It's not always a good idea to include the call frame as part of the
32   // stack frame. ARM (especially Thumb) has small immediate offset to
33   // address the stack frame. So a large call frame can cause poor codegen
34   // and may even makes it impossible to scavenge a register.
35   if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
36     return false;
37
38   return !MF.getFrameInfo()->hasVarSizedObjects();
39 }
40
41 static void
42 emitSPUpdate(MachineBasicBlock &MBB,
43              MachineBasicBlock::iterator &MBBI,
44              const TargetInstrInfo &TII, DebugLoc dl,
45              const ThumbRegisterInfo &MRI,
46              int NumBytes, unsigned MIFlags = MachineInstr::NoFlags)  {
47   emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
48                             MRI, MIFlags);
49 }
50
51
52 void Thumb1FrameLowering::
53 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
54                               MachineBasicBlock::iterator I) const {
55   const Thumb1InstrInfo &TII =
56       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
57   const ThumbRegisterInfo *RegInfo =
58       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
59   if (!hasReservedCallFrame(MF)) {
60     // If we have alloca, convert as follows:
61     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
62     // ADJCALLSTACKUP   -> add, sp, sp, amount
63     MachineInstr *Old = I;
64     DebugLoc dl = Old->getDebugLoc();
65     unsigned Amount = Old->getOperand(0).getImm();
66     if (Amount != 0) {
67       // We need to keep the stack aligned properly.  To do this, we round the
68       // amount of space needed for the outgoing arguments up to the next
69       // alignment boundary.
70       unsigned Align = getStackAlignment();
71       Amount = (Amount+Align-1)/Align*Align;
72
73       // Replace the pseudo instruction with a new instruction...
74       unsigned Opc = Old->getOpcode();
75       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
76         emitSPUpdate(MBB, I, TII, dl, *RegInfo, -Amount);
77       } else {
78         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
79         emitSPUpdate(MBB, I, TII, dl, *RegInfo, Amount);
80       }
81     }
82   }
83   MBB.erase(I);
84 }
85
86 void Thumb1FrameLowering::emitPrologue(MachineFunction &MF,
87                                        MachineBasicBlock &MBB) const {
88   MachineBasicBlock::iterator MBBI = MBB.begin();
89   MachineFrameInfo  *MFI = MF.getFrameInfo();
90   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
91   MachineModuleInfo &MMI = MF.getMMI();
92   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
93   const ThumbRegisterInfo *RegInfo =
94       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
95   const Thumb1InstrInfo &TII =
96       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
97
98   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
99   unsigned NumBytes = MFI->getStackSize();
100   assert(NumBytes >= ArgRegsSaveSize &&
101          "ArgRegsSaveSize is included in NumBytes");
102   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
103
104   // Debug location must be unknown since the first debug location is used
105   // to determine the end of the prologue.
106   DebugLoc dl;
107   
108   unsigned FramePtr = RegInfo->getFrameRegister(MF);
109   unsigned BasePtr = RegInfo->getBaseRegister();
110   int CFAOffset = 0;
111
112   // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
113   NumBytes = (NumBytes + 3) & ~3;
114   MFI->setStackSize(NumBytes);
115
116   // Determine the sizes of each callee-save spill areas and record which frame
117   // belongs to which callee-save spill areas.
118   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
119   int FramePtrSpillFI = 0;
120
121   if (ArgRegsSaveSize) {
122     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -ArgRegsSaveSize,
123                  MachineInstr::FrameSetup);
124     CFAOffset -= ArgRegsSaveSize;
125     unsigned CFIIndex = MMI.addFrameInst(
126         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
127     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
128         .addCFIIndex(CFIIndex)
129         .setMIFlags(MachineInstr::FrameSetup);
130   }
131
132   if (!AFI->hasStackFrame()) {
133     if (NumBytes - ArgRegsSaveSize != 0) {
134       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -(NumBytes - ArgRegsSaveSize),
135                    MachineInstr::FrameSetup);
136       CFAOffset -= NumBytes - ArgRegsSaveSize;
137       unsigned CFIIndex = MMI.addFrameInst(
138           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
139       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
140           .addCFIIndex(CFIIndex)
141           .setMIFlags(MachineInstr::FrameSetup);
142     }
143     return;
144   }
145
146   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
147     unsigned Reg = CSI[i].getReg();
148     int FI = CSI[i].getFrameIdx();
149     switch (Reg) {
150     case ARM::R8:
151     case ARM::R9:
152     case ARM::R10:
153     case ARM::R11:
154       if (STI.isTargetMachO()) {
155         GPRCS2Size += 4;
156         break;
157       }
158       // fallthrough
159     case ARM::R4:
160     case ARM::R5:
161     case ARM::R6:
162     case ARM::R7:
163     case ARM::LR:
164       if (Reg == FramePtr)
165         FramePtrSpillFI = FI;
166       GPRCS1Size += 4;
167       break;
168     default:
169       DPRCSSize += 8;
170     }
171   }
172
173   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
174     ++MBBI;
175   }
176
177   // Determine starting offsets of spill areas.
178   unsigned DPRCSOffset  = NumBytes - ArgRegsSaveSize - (GPRCS1Size + GPRCS2Size + DPRCSSize);
179   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
180   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
181   bool HasFP = hasFP(MF);
182   if (HasFP)
183     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
184                                 NumBytes);
185   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
186   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
187   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
188   NumBytes = DPRCSOffset;
189
190   int FramePtrOffsetInBlock = 0;
191   unsigned adjustedGPRCS1Size = GPRCS1Size;
192   if (tryFoldSPUpdateIntoPushPop(STI, MF, std::prev(MBBI), NumBytes)) {
193     FramePtrOffsetInBlock = NumBytes;
194     adjustedGPRCS1Size += NumBytes;
195     NumBytes = 0;
196   }
197
198   if (adjustedGPRCS1Size) {
199     CFAOffset -= adjustedGPRCS1Size;
200     unsigned CFIIndex = MMI.addFrameInst(
201         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
202     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
203         .addCFIIndex(CFIIndex)
204         .setMIFlags(MachineInstr::FrameSetup);
205   }
206   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
207          E = CSI.end(); I != E; ++I) {
208     unsigned Reg = I->getReg();
209     int FI = I->getFrameIdx();
210     switch (Reg) {
211     case ARM::R8:
212     case ARM::R9:
213     case ARM::R10:
214     case ARM::R11:
215     case ARM::R12:
216       if (STI.isTargetMachO())
217         break;
218       // fallthough
219     case ARM::R0:
220     case ARM::R1:
221     case ARM::R2:
222     case ARM::R3:
223     case ARM::R4:
224     case ARM::R5:
225     case ARM::R6:
226     case ARM::R7:
227     case ARM::LR:
228       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
229           nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
230       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
231           .addCFIIndex(CFIIndex)
232           .setMIFlags(MachineInstr::FrameSetup);
233       break;
234     }
235   }
236
237   // Adjust FP so it point to the stack slot that contains the previous FP.
238   if (HasFP) {
239     FramePtrOffsetInBlock +=
240         MFI->getObjectOffset(FramePtrSpillFI) + GPRCS1Size + ArgRegsSaveSize;
241     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
242       .addReg(ARM::SP).addImm(FramePtrOffsetInBlock / 4)
243       .setMIFlags(MachineInstr::FrameSetup));
244     if(FramePtrOffsetInBlock) {
245       CFAOffset += FramePtrOffsetInBlock;
246       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
247           nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
248       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
249           .addCFIIndex(CFIIndex)
250           .setMIFlags(MachineInstr::FrameSetup);
251     } else {
252       unsigned CFIIndex =
253           MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
254               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
255       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
256           .addCFIIndex(CFIIndex)
257           .setMIFlags(MachineInstr::FrameSetup);
258     }
259     if (NumBytes > 508)
260       // If offset is > 508 then sp cannot be adjusted in a single instruction,
261       // try restoring from fp instead.
262       AFI->setShouldRestoreSPFromFP(true);
263   }
264
265   if (NumBytes) {
266     // Insert it after all the callee-save spills.
267     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
268                  MachineInstr::FrameSetup);
269     if (!HasFP) {
270       CFAOffset -= NumBytes;
271       unsigned CFIIndex = MMI.addFrameInst(
272           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
273       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
274           .addCFIIndex(CFIIndex)
275           .setMIFlags(MachineInstr::FrameSetup);
276     }
277   }
278
279   if (STI.isTargetELF() && HasFP)
280     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
281                              AFI->getFramePtrSpillOffset());
282
283   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
284   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
285   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
286
287   // Thumb1 does not currently support dynamic stack realignment.  Report a
288   // fatal error rather then silently generate bad code.
289   if (RegInfo->needsStackRealignment(MF))
290       report_fatal_error("Dynamic stack realignment not supported for thumb1.");
291
292   // If we need a base pointer, set it up here. It's whatever the value
293   // of the stack pointer is at this point. Any variable size objects
294   // will be allocated after this, so we can still use the base pointer
295   // to reference locals.
296   if (RegInfo->hasBasePointer(MF))
297     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
298                    .addReg(ARM::SP));
299
300   // If the frame has variable sized objects then the epilogue must restore
301   // the sp from fp. We can assume there's an FP here since hasFP already
302   // checks for hasVarSizedObjects.
303   if (MFI->hasVarSizedObjects())
304     AFI->setShouldRestoreSPFromFP(true);
305 }
306
307 static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
308   if (MI->getOpcode() == ARM::tLDRspi &&
309       MI->getOperand(1).isFI() &&
310       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs))
311     return true;
312   else if (MI->getOpcode() == ARM::tPOP) {
313     // The first two operands are predicates. The last two are
314     // imp-def and imp-use of SP. Check everything in between.
315     for (int i = 2, e = MI->getNumOperands() - 2; i != e; ++i)
316       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
317         return false;
318     return true;
319   }
320   return false;
321 }
322
323 void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
324                                    MachineBasicBlock &MBB) const {
325   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
326   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
327   MachineFrameInfo *MFI = MF.getFrameInfo();
328   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
329   const ThumbRegisterInfo *RegInfo =
330       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
331   const Thumb1InstrInfo &TII =
332       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
333
334   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
335   int NumBytes = (int)MFI->getStackSize();
336   assert((unsigned)NumBytes >= ArgRegsSaveSize &&
337          "ArgRegsSaveSize is included in NumBytes");
338   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
339   unsigned FramePtr = RegInfo->getFrameRegister(MF);
340
341   if (!AFI->hasStackFrame()) {
342     if (NumBytes - ArgRegsSaveSize != 0)
343       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes - ArgRegsSaveSize);
344   } else {
345     // Unwind MBBI to point to first LDR / VLDRD.
346     if (MBBI != MBB.begin()) {
347       do
348         --MBBI;
349       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
350       if (!isCSRestore(MBBI, CSRegs))
351         ++MBBI;
352     }
353
354     // Move SP to start of FP callee save spill area.
355     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
356                  AFI->getGPRCalleeSavedArea2Size() +
357                  AFI->getDPRCalleeSavedAreaSize() +
358                  ArgRegsSaveSize);
359
360     if (AFI->shouldRestoreSPFromFP()) {
361       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
362       // Reset SP based on frame pointer only if the stack frame extends beyond
363       // frame pointer stack slot, the target is ELF and the function has FP, or
364       // the target uses var sized objects.
365       if (NumBytes) {
366         assert(!MFI->getPristineRegs(MF).test(ARM::R4) &&
367                "No scratch register to restore SP from FP!");
368         emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
369                                   TII, *RegInfo);
370         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
371                                ARM::SP)
372           .addReg(ARM::R4));
373       } else
374         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
375                                ARM::SP)
376           .addReg(FramePtr));
377     } else {
378       if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET &&
379           &MBB.front() != MBBI && std::prev(MBBI)->getOpcode() == ARM::tPOP) {
380         MachineBasicBlock::iterator PMBBI = std::prev(MBBI);
381         if (!tryFoldSPUpdateIntoPushPop(STI, MF, PMBBI, NumBytes))
382           emitSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes);
383       } else if (!tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
384         emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
385     }
386   }
387
388   if (needPopSpecialFixUp(MF)) {
389     bool Done = emitPopSpecialFixUp(MBB, /* DoIt */ true);
390     (void)Done;
391     assert(Done && "Emission of the special fixup failed!?");
392   }
393 }
394
395 bool Thumb1FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
396   if (!needPopSpecialFixUp(*MBB.getParent()))
397     return true;
398
399   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
400   return emitPopSpecialFixUp(*TmpMBB, /* DoIt */ false);
401 }
402
403 bool Thumb1FrameLowering::needPopSpecialFixUp(const MachineFunction &MF) const {
404   ARMFunctionInfo *AFI =
405       const_cast<MachineFunction *>(&MF)->getInfo<ARMFunctionInfo>();
406   if (AFI->getArgRegsSaveSize())
407     return true;
408
409   // LR cannot be encoded with Thumb1, i.e., it requires a special fix-up.
410   for (const CalleeSavedInfo &CSI : MF.getFrameInfo()->getCalleeSavedInfo())
411     if (CSI.getReg() == ARM::LR)
412       return true;
413
414   return false;
415 }
416
417 bool Thumb1FrameLowering::emitPopSpecialFixUp(MachineBasicBlock &MBB,
418                                               bool DoIt) const {
419   MachineFunction &MF = *MBB.getParent();
420   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
421   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
422   const TargetInstrInfo &TII = *STI.getInstrInfo();
423   const ThumbRegisterInfo *RegInfo =
424       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
425
426   // If MBBI is a return instruction, or is a tPOP followed by a return
427   // instruction in the successor BB, we may be able to directly restore
428   // LR in the PC.
429   // This is only possible with v5T ops (v4T can't change the Thumb bit via
430   // a POP PC instruction), and only if we do not need to emit any SP update.
431   // Otherwise, we need a temporary register to pop the value
432   // and copy that value into LR.
433   auto MBBI = MBB.getFirstTerminator();
434   bool CanRestoreDirectly = STI.hasV5TOps() && !ArgRegsSaveSize;
435   if (CanRestoreDirectly) {
436     if (MBBI != MBB.end())
437       CanRestoreDirectly = (MBBI->getOpcode() == ARM::tBX_RET ||
438                             MBBI->getOpcode() == ARM::tPOP_RET);
439     else {
440       assert(MBB.back().getOpcode() == ARM::tPOP);
441       assert(MBB.succ_size() == 1);
442       if ((*MBB.succ_begin())->begin()->getOpcode() == ARM::tBX_RET)
443         MBBI--; // Replace the final tPOP with a tPOP_RET.
444       else
445         CanRestoreDirectly = false;
446     }
447   }
448
449   if (CanRestoreDirectly) {
450     if (!DoIt || MBBI->getOpcode() == ARM::tPOP_RET)
451       return true;
452     MachineInstrBuilder MIB =
453         AddDefaultPred(
454             BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET)));
455     // Copy implicit ops and popped registers, if any.
456     for (auto MO: MBBI->operands())
457       if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
458           MO.getReg() != ARM::LR)
459         MIB.addOperand(MO);
460     MIB.addReg(ARM::PC, RegState::Define);
461     // Erase the old instruction (tBX_RET or tPOP).
462     MBB.erase(MBBI);
463     return true;
464   }
465
466   // Look for a temporary register to use.
467   // First, compute the liveness information.
468   LivePhysRegs UsedRegs(STI.getRegisterInfo());
469   UsedRegs.addLiveOuts(&MBB, /*AddPristines*/ true);
470   // The semantic of pristines changed recently and now,
471   // the callee-saved registers that are touched in the function
472   // are not part of the pristines set anymore.
473   // Add those callee-saved now.
474   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
475   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
476   for (unsigned i = 0; CSRegs[i]; ++i)
477     UsedRegs.addReg(CSRegs[i]);
478
479   DebugLoc dl = DebugLoc();
480   if (MBBI != MBB.end()) {
481     dl = MBBI->getDebugLoc();
482     auto InstUpToMBBI = MBB.end();
483     while (InstUpToMBBI != MBBI)
484       // The pre-decrement is on purpose here.
485       // We want to have the liveness right before MBBI.
486       UsedRegs.stepBackward(*--InstUpToMBBI);
487   }
488
489   // Look for a register that can be directly use in the POP.
490   unsigned PopReg = 0;
491   // And some temporary register, just in case.
492   unsigned TemporaryReg = 0;
493   BitVector PopFriendly =
494       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::tGPRRegClassID));
495   assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
496   // Rebuild the GPRs from the high registers because they are removed
497   // form the GPR reg class for thumb1.
498   BitVector GPRsNoLRSP =
499       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::hGPRRegClassID));
500   GPRsNoLRSP |= PopFriendly;
501   GPRsNoLRSP.reset(ARM::LR);
502   GPRsNoLRSP.reset(ARM::SP);
503   GPRsNoLRSP.reset(ARM::PC);
504   for (int Register = GPRsNoLRSP.find_first(); Register != -1;
505        Register = GPRsNoLRSP.find_next(Register)) {
506     if (!UsedRegs.contains(Register)) {
507       // Remember the first pop-friendly register and exit.
508       if (PopFriendly.test(Register)) {
509         PopReg = Register;
510         TemporaryReg = 0;
511         break;
512       }
513       // Otherwise, remember that the register will be available to
514       // save a pop-friendly register.
515       TemporaryReg = Register;
516     }
517   }
518
519   if (!DoIt && !PopReg && !TemporaryReg)
520     return false;
521
522   assert((PopReg || TemporaryReg) && "Cannot get LR");
523
524   if (TemporaryReg) {
525     assert(!PopReg && "Unnecessary MOV is about to be inserted");
526     PopReg = PopFriendly.find_first();
527     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
528                        .addReg(TemporaryReg, RegState::Define)
529                        .addReg(PopReg, RegState::Kill));
530   }
531
532   bool AddBx = false;
533   if (MBBI == MBB.end()) {
534     MachineInstr& Pop = MBB.back();
535     assert(Pop.getOpcode() == ARM::tPOP);
536     Pop.RemoveOperand(Pop.findRegisterDefOperandIdx(ARM::LR));
537   } else if (MBBI->getOpcode() == ARM::tPOP_RET) {
538     // We couldn't use the direct restoration above, so
539     // perform the opposite conversion: tPOP_RET to tPOP.
540     MachineInstrBuilder MIB =
541         AddDefaultPred(
542             BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP)));
543     unsigned Popped = 0;
544     for (auto MO: MBBI->operands())
545       if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
546           MO.getReg() != ARM::PC) {
547         MIB.addOperand(MO);
548         if (!MO.isImplicit())
549           Popped++;
550       }
551     // Is there anything left to pop?
552     if (!Popped)
553       MBB.erase(MIB.getInstr());
554     // Erase the old instruction.
555     MBB.erase(MBBI);
556     MBBI = MBB.end();
557     AddBx = true;
558   }
559
560   assert(PopReg && "Do not know how to get LR");
561   AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
562       .addReg(PopReg, RegState::Define);
563
564   emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize);
565
566   if (!TemporaryReg && MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET) {
567     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX))
568                                   .addReg(PopReg, RegState::Kill);
569     AddDefaultPred(MIB);
570     MIB.copyImplicitOps(&*MBBI);
571     // erase the old tBX_RET instruction
572     MBB.erase(MBBI);
573     return true;
574   }
575
576   if (AddBx && !TemporaryReg) {
577     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX))
578                        .addReg(PopReg, RegState::Kill));
579   } else {
580     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
581                        .addReg(ARM::LR, RegState::Define)
582                        .addReg(PopReg, RegState::Kill));
583   }
584   if (TemporaryReg) {
585     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
586                        .addReg(PopReg, RegState::Define)
587                        .addReg(TemporaryReg, RegState::Kill));
588     if (AddBx)
589       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX_RET)));
590   }
591
592   return true;
593 }
594
595 bool Thumb1FrameLowering::
596 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
597                           MachineBasicBlock::iterator MI,
598                           const std::vector<CalleeSavedInfo> &CSI,
599                           const TargetRegisterInfo *TRI) const {
600   if (CSI.empty())
601     return false;
602
603   DebugLoc DL;
604   const TargetInstrInfo &TII = *STI.getInstrInfo();
605
606   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH));
607   AddDefaultPred(MIB);
608   for (unsigned i = CSI.size(); i != 0; --i) {
609     unsigned Reg = CSI[i-1].getReg();
610     bool isKill = true;
611
612     // Add the callee-saved register as live-in unless it's LR and
613     // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
614     // then it's already added to the function and entry block live-in sets.
615     if (Reg == ARM::LR) {
616       MachineFunction &MF = *MBB.getParent();
617       if (MF.getFrameInfo()->isReturnAddressTaken() &&
618           MF.getRegInfo().isLiveIn(Reg))
619         isKill = false;
620     }
621
622     if (isKill)
623       MBB.addLiveIn(Reg);
624
625     MIB.addReg(Reg, getKillRegState(isKill));
626   }
627   MIB.setMIFlags(MachineInstr::FrameSetup);
628   return true;
629 }
630
631 bool Thumb1FrameLowering::
632 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
633                             MachineBasicBlock::iterator MI,
634                             const std::vector<CalleeSavedInfo> &CSI,
635                             const TargetRegisterInfo *TRI) const {
636   if (CSI.empty())
637     return false;
638
639   MachineFunction &MF = *MBB.getParent();
640   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
641   const TargetInstrInfo &TII = *STI.getInstrInfo();
642
643   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
644   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
645   MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP));
646   AddDefaultPred(MIB);
647
648   bool NumRegs = false;
649   for (unsigned i = CSI.size(); i != 0; --i) {
650     unsigned Reg = CSI[i-1].getReg();
651     if (Reg == ARM::LR && MBB.succ_empty()) {
652       // Special epilogue for vararg functions. See emitEpilogue
653       if (isVarArg)
654         continue;
655       // ARMv4T requires BX, see emitEpilogue
656       if (!STI.hasV5TOps())
657         continue;
658       Reg = ARM::PC;
659       (*MIB).setDesc(TII.get(ARM::tPOP_RET));
660       if (MI != MBB.end())
661         MIB.copyImplicitOps(&*MI);
662       MI = MBB.erase(MI);
663     }
664     MIB.addReg(Reg, getDefRegState(true));
665     NumRegs = true;
666   }
667
668   // It's illegal to emit pop instruction without operands.
669   if (NumRegs)
670     MBB.insert(MI, &*MIB);
671   else
672     MF.DeleteMachineInstr(MIB);
673
674   return true;
675 }