Delete trailing whitespace; NFC
[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() && MBBI->getOpcode() != ARM::tB)
437       CanRestoreDirectly = (MBBI->getOpcode() == ARM::tBX_RET ||
438                             MBBI->getOpcode() == ARM::tPOP_RET);
439     else {
440       auto MBBI_prev = MBBI;
441       MBBI_prev--;
442       assert(MBBI_prev->getOpcode() == ARM::tPOP);
443       assert(MBB.succ_size() == 1);
444       if ((*MBB.succ_begin())->begin()->getOpcode() == ARM::tBX_RET)
445         MBBI = MBBI_prev; // Replace the final tPOP with a tPOP_RET.
446       else
447         CanRestoreDirectly = false;
448     }
449   }
450
451   if (CanRestoreDirectly) {
452     if (!DoIt || MBBI->getOpcode() == ARM::tPOP_RET)
453       return true;
454     MachineInstrBuilder MIB =
455         AddDefaultPred(
456             BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET)));
457     // Copy implicit ops and popped registers, if any.
458     for (auto MO: MBBI->operands())
459       if (MO.isReg() && (MO.isImplicit() || MO.isDef()))
460         MIB.addOperand(MO);
461     MIB.addReg(ARM::PC, RegState::Define);
462     // Erase the old instruction (tBX_RET or tPOP).
463     MBB.erase(MBBI);
464     return true;
465   }
466
467   // Look for a temporary register to use.
468   // First, compute the liveness information.
469   LivePhysRegs UsedRegs(STI.getRegisterInfo());
470   UsedRegs.addLiveOuts(&MBB, /*AddPristines*/ true);
471   // The semantic of pristines changed recently and now,
472   // the callee-saved registers that are touched in the function
473   // are not part of the pristines set anymore.
474   // Add those callee-saved now.
475   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
476   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
477   for (unsigned i = 0; CSRegs[i]; ++i)
478     UsedRegs.addReg(CSRegs[i]);
479
480   DebugLoc dl = DebugLoc();
481   if (MBBI != MBB.end()) {
482     dl = MBBI->getDebugLoc();
483     auto InstUpToMBBI = MBB.end();
484     while (InstUpToMBBI != MBBI)
485       // The pre-decrement is on purpose here.
486       // We want to have the liveness right before MBBI.
487       UsedRegs.stepBackward(*--InstUpToMBBI);
488   }
489
490   // Look for a register that can be directly use in the POP.
491   unsigned PopReg = 0;
492   // And some temporary register, just in case.
493   unsigned TemporaryReg = 0;
494   BitVector PopFriendly =
495       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::tGPRRegClassID));
496   assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
497   // Rebuild the GPRs from the high registers because they are removed
498   // form the GPR reg class for thumb1.
499   BitVector GPRsNoLRSP =
500       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::hGPRRegClassID));
501   GPRsNoLRSP |= PopFriendly;
502   GPRsNoLRSP.reset(ARM::LR);
503   GPRsNoLRSP.reset(ARM::SP);
504   GPRsNoLRSP.reset(ARM::PC);
505   for (int Register = GPRsNoLRSP.find_first(); Register != -1;
506        Register = GPRsNoLRSP.find_next(Register)) {
507     if (!UsedRegs.contains(Register)) {
508       // Remember the first pop-friendly register and exit.
509       if (PopFriendly.test(Register)) {
510         PopReg = Register;
511         TemporaryReg = 0;
512         break;
513       }
514       // Otherwise, remember that the register will be available to
515       // save a pop-friendly register.
516       TemporaryReg = Register;
517     }
518   }
519
520   if (!DoIt && !PopReg && !TemporaryReg)
521     return false;
522
523   assert((PopReg || TemporaryReg) && "Cannot get LR");
524
525   if (TemporaryReg) {
526     assert(!PopReg && "Unnecessary MOV is about to be inserted");
527     PopReg = PopFriendly.find_first();
528     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
529                        .addReg(TemporaryReg, RegState::Define)
530                        .addReg(PopReg, RegState::Kill));
531   }
532
533   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPOP_RET) {
534     // We couldn't use the direct restoration above, so
535     // perform the opposite conversion: tPOP_RET to tPOP.
536     MachineInstrBuilder MIB =
537         AddDefaultPred(
538             BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP)));
539     bool Popped = false;
540     for (auto MO: MBBI->operands())
541       if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
542           MO.getReg() != ARM::PC) {
543         MIB.addOperand(MO);
544         if (!MO.isImplicit())
545           Popped = true;
546       }
547     // Is there anything left to pop?
548     if (!Popped)
549       MBB.erase(MIB.getInstr());
550     // Erase the old instruction.
551     MBB.erase(MBBI);
552     MBBI = AddDefaultPred(BuildMI(MBB, MBB.end(), dl, TII.get(ARM::tBX_RET)));
553   }
554
555   assert(PopReg && "Do not know how to get LR");
556   AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
557       .addReg(PopReg, RegState::Define);
558
559   emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize);
560
561   AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
562                      .addReg(ARM::LR, RegState::Define)
563                      .addReg(PopReg, RegState::Kill));
564
565   if (TemporaryReg)
566     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
567                        .addReg(PopReg, RegState::Define)
568                        .addReg(TemporaryReg, RegState::Kill));
569
570   return true;
571 }
572
573 bool Thumb1FrameLowering::
574 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
575                           MachineBasicBlock::iterator MI,
576                           const std::vector<CalleeSavedInfo> &CSI,
577                           const TargetRegisterInfo *TRI) const {
578   if (CSI.empty())
579     return false;
580
581   DebugLoc DL;
582   const TargetInstrInfo &TII = *STI.getInstrInfo();
583
584   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH));
585   AddDefaultPred(MIB);
586   for (unsigned i = CSI.size(); i != 0; --i) {
587     unsigned Reg = CSI[i-1].getReg();
588     bool isKill = true;
589
590     // Add the callee-saved register as live-in unless it's LR and
591     // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
592     // then it's already added to the function and entry block live-in sets.
593     if (Reg == ARM::LR) {
594       MachineFunction &MF = *MBB.getParent();
595       if (MF.getFrameInfo()->isReturnAddressTaken() &&
596           MF.getRegInfo().isLiveIn(Reg))
597         isKill = false;
598     }
599
600     if (isKill)
601       MBB.addLiveIn(Reg);
602
603     MIB.addReg(Reg, getKillRegState(isKill));
604   }
605   MIB.setMIFlags(MachineInstr::FrameSetup);
606   return true;
607 }
608
609 bool Thumb1FrameLowering::
610 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
611                             MachineBasicBlock::iterator MI,
612                             const std::vector<CalleeSavedInfo> &CSI,
613                             const TargetRegisterInfo *TRI) const {
614   if (CSI.empty())
615     return false;
616
617   MachineFunction &MF = *MBB.getParent();
618   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
619   const TargetInstrInfo &TII = *STI.getInstrInfo();
620
621   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
622   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
623   MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP));
624   AddDefaultPred(MIB);
625
626   bool NeedsPop = false;
627   for (unsigned i = CSI.size(); i != 0; --i) {
628     unsigned Reg = CSI[i-1].getReg();
629     if (Reg == ARM::LR) {
630       if (MBB.succ_empty()) {
631         // Special epilogue for vararg functions. See emitEpilogue
632         if (isVarArg)
633           continue;
634         // ARMv4T requires BX, see emitEpilogue
635         if (!STI.hasV5TOps())
636           continue;
637         Reg = ARM::PC;
638         (*MIB).setDesc(TII.get(ARM::tPOP_RET));
639         if (MI != MBB.end())
640           MIB.copyImplicitOps(&*MI);
641         MI = MBB.erase(MI);
642       } else
643         // LR may only be popped into PC, as part of return sequence.
644         // If this isn't the return sequence, we'll need emitPopSpecialFixUp
645         // to restore LR the hard way.
646         continue;
647     }
648     MIB.addReg(Reg, getDefRegState(true));
649     NeedsPop = true;
650   }
651
652   // It's illegal to emit pop instruction without operands.
653   if (NeedsPop)
654     MBB.insert(MI, &*MIB);
655   else
656     MF.DeleteMachineInstr(MIB);
657
658   return true;
659 }