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