064cff6f570407ffca6c4a2db1140aa9d645913a
[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   bool IsV4PopReturn = false;
410   for (const CalleeSavedInfo &CSI : MF.getFrameInfo()->getCalleeSavedInfo())
411     if (CSI.getReg() == ARM::LR)
412       IsV4PopReturn = true;
413   return IsV4PopReturn && STI.hasV4TOps() && !STI.hasV5TOps();
414 }
415
416 bool Thumb1FrameLowering::emitPopSpecialFixUp(MachineBasicBlock &MBB,
417                                               bool DoIt) const {
418   MachineFunction &MF = *MBB.getParent();
419   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
420   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
421   const TargetInstrInfo &TII = *STI.getInstrInfo();
422   const ThumbRegisterInfo *RegInfo =
423       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
424
425   // When we need a special fix up for POP, this means that
426   // we either cannot use PC in POP or we have to update
427   // SP after poping the return address.
428   // In other words, we cannot use a pop {pc} like construction
429   // here, no matter what.
430   auto MBBI = MBB.getFirstTerminator();
431
432   // Look for a temporary register to use.
433   // First, compute the liveness information.
434   LivePhysRegs UsedRegs(STI.getRegisterInfo());
435   UsedRegs.addLiveOuts(&MBB, /*AddPristines*/ true);
436   // The semantic of pristines changed recently and now,
437   // the callee-saved registers that are touched in the function
438   // are not part of the pristines set anymore.
439   // Add those callee-saved now.
440   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
441   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
442   for (unsigned i = 0; CSRegs[i]; ++i)
443     UsedRegs.addReg(CSRegs[i]);
444
445   DebugLoc dl = DebugLoc();
446   if (MBBI != MBB.end()) {
447     dl = MBBI->getDebugLoc();
448     auto InstUpToMBBI = MBB.end();
449     // The post-decrement is on purpose here.
450     // We want to have the liveness right before MBBI.
451     while (InstUpToMBBI-- != MBBI)
452       UsedRegs.stepBackward(*InstUpToMBBI);
453   }
454
455   // Look for a register that can be directly use in the POP.
456   unsigned PopReg = 0;
457   // And some temporary register, just in case.
458   unsigned TemporaryReg = 0;
459   BitVector PopFriendly =
460       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::tGPRRegClassID));
461   assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
462   // Rebuild the GPRs from the high registers because they are removed
463   // form the GPR reg class for thumb1.
464   BitVector GPRsNoLRSP =
465       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::hGPRRegClassID));
466   GPRsNoLRSP |= PopFriendly;
467   GPRsNoLRSP.reset(ARM::LR);
468   GPRsNoLRSP.reset(ARM::SP);
469   GPRsNoLRSP.reset(ARM::PC);
470   for (int Register = GPRsNoLRSP.find_first(); Register != -1;
471        Register = GPRsNoLRSP.find_next(Register)) {
472     if (!UsedRegs.contains(Register)) {
473       // Remember the first pop-friendly register and exit.
474       if (PopFriendly.test(Register)) {
475         PopReg = Register;
476         TemporaryReg = 0;
477         break;
478       }
479       // Otherwise, remember that the register will be available to
480       // save a pop-friendly register.
481       TemporaryReg = Register;
482     }
483   }
484
485   if (!DoIt && !PopReg && !TemporaryReg)
486     return false;
487
488   assert((PopReg || TemporaryReg) && "Cannot get LR");
489
490   if (TemporaryReg) {
491     assert(!PopReg && "Unnecessary MOV is about to be inserted");
492     PopReg = PopFriendly.find_first();
493     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
494                        .addReg(TemporaryReg, RegState::Define)
495                        .addReg(PopReg, RegState::Kill));
496   }
497
498   assert(PopReg && "Do not know how to get LR");
499   AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
500       .addReg(PopReg, RegState::Define);
501
502   emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize);
503
504   if (!TemporaryReg && MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET) {
505     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX))
506                                   .addReg(PopReg, RegState::Kill);
507     AddDefaultPred(MIB);
508     MIB.copyImplicitOps(&*MBBI);
509     // erase the old tBX_RET instruction
510     MBB.erase(MBBI);
511     return true;
512   }
513
514   AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
515                      .addReg(ARM::LR, RegState::Define)
516                      .addReg(PopReg, RegState::Kill));
517
518   if (TemporaryReg) {
519     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
520                        .addReg(PopReg, RegState::Define)
521                        .addReg(TemporaryReg, RegState::Kill));
522   }
523
524   return true;
525 }
526
527 bool Thumb1FrameLowering::
528 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
529                           MachineBasicBlock::iterator MI,
530                           const std::vector<CalleeSavedInfo> &CSI,
531                           const TargetRegisterInfo *TRI) const {
532   if (CSI.empty())
533     return false;
534
535   DebugLoc DL;
536   const TargetInstrInfo &TII = *STI.getInstrInfo();
537
538   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH));
539   AddDefaultPred(MIB);
540   for (unsigned i = CSI.size(); i != 0; --i) {
541     unsigned Reg = CSI[i-1].getReg();
542     bool isKill = true;
543
544     // Add the callee-saved register as live-in unless it's LR and
545     // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
546     // then it's already added to the function and entry block live-in sets.
547     if (Reg == ARM::LR) {
548       MachineFunction &MF = *MBB.getParent();
549       if (MF.getFrameInfo()->isReturnAddressTaken() &&
550           MF.getRegInfo().isLiveIn(Reg))
551         isKill = false;
552     }
553
554     if (isKill)
555       MBB.addLiveIn(Reg);
556
557     MIB.addReg(Reg, getKillRegState(isKill));
558   }
559   MIB.setMIFlags(MachineInstr::FrameSetup);
560   return true;
561 }
562
563 bool Thumb1FrameLowering::
564 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
565                             MachineBasicBlock::iterator MI,
566                             const std::vector<CalleeSavedInfo> &CSI,
567                             const TargetRegisterInfo *TRI) const {
568   if (CSI.empty())
569     return false;
570
571   MachineFunction &MF = *MBB.getParent();
572   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
573   const TargetInstrInfo &TII = *STI.getInstrInfo();
574
575   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
576   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
577   MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP));
578   AddDefaultPred(MIB);
579
580   bool NumRegs = false;
581   for (unsigned i = CSI.size(); i != 0; --i) {
582     unsigned Reg = CSI[i-1].getReg();
583     if (Reg == ARM::LR && MBB.succ_empty()) {
584       // Special epilogue for vararg functions. See emitEpilogue
585       if (isVarArg)
586         continue;
587       // ARMv4T requires BX, see emitEpilogue
588       if (STI.hasV4TOps() && !STI.hasV5TOps())
589         continue;
590       Reg = ARM::PC;
591       (*MIB).setDesc(TII.get(ARM::tPOP_RET));
592       if (MI != MBB.end())
593         MIB.copyImplicitOps(&*MI);
594       MI = MBB.erase(MI);
595     }
596     MIB.addReg(Reg, getDefRegState(true));
597     NumRegs = true;
598   }
599
600   // It's illegal to emit pop instruction without operands.
601   if (NumRegs)
602     MBB.insert(MI, &*MIB);
603   else
604     MF.DeleteMachineInstr(MIB);
605
606   return true;
607 }