Cleanup comment wording
[oota-llvm.git] / lib / CodeGen / PrologEpilogInserter.cpp
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
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 pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation.  After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 // This pass provides an optional shrink wrapping variant of prolog/epilog
18 // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "PrologEpilogInserter.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetFrameInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/ADT/IndexedMap.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include <climits>
39
40 using namespace llvm;
41
42 char PEI::ID = 0;
43
44 INITIALIZE_PASS(PEI, "prologepilog",
45                 "Prologue/Epilogue Insertion", false, false);
46
47 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
48 /// prolog and epilog code, and eliminates abstract frame references.
49 ///
50 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
51
52 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
53 /// frame indexes with appropriate references.
54 ///
55 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
56   const Function* F = Fn.getFunction();
57   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
58   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
59   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
60   FrameConstantRegMap.clear();
61
62   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
63   // function's frame information. Also eliminates call frame pseudo
64   // instructions.
65   calculateCallsInformation(Fn);
66
67   // Allow the target machine to make some adjustments to the function
68   // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
69   TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
70
71   // Scan the function for modified callee saved registers and insert spill code
72   // for any callee saved registers that are modified.
73   calculateCalleeSavedRegisters(Fn);
74
75   // Determine placement of CSR spill/restore code:
76   //  - With shrink wrapping, place spills and restores to tightly
77   //    enclose regions in the Machine CFG of the function where
78   //    they are used.
79   //  - Without shink wrapping (default), place all spills in the
80   //    entry block, all restores in return blocks.
81   placeCSRSpillsAndRestores(Fn);
82
83   // Add the code to save and restore the callee saved registers
84   if (!F->hasFnAttr(Attribute::Naked))
85     insertCSRSpillsAndRestores(Fn);
86
87   // Allow the target machine to make final modifications to the function
88   // before the frame layout is finalized.
89   TRI->processFunctionBeforeFrameFinalized(Fn);
90
91   // Calculate actual frame offsets for all abstract stack objects...
92   calculateFrameObjectOffsets(Fn);
93
94   // Add prolog and epilog code to the function.  This function is required
95   // to align the stack frame as necessary for any stack variables or
96   // called functions.  Because of this, calculateCalleeSavedRegisters()
97   // must be called before this function in order to set the AdjustsStack
98   // and MaxCallFrameSize variables.
99   if (!F->hasFnAttr(Attribute::Naked))
100     insertPrologEpilogCode(Fn);
101
102   // Replace all MO_FrameIndex operands with physical register references
103   // and actual offsets.
104   //
105   replaceFrameIndices(Fn);
106
107   // If register scavenging is needed, as we've enabled doing it as a
108   // post-pass, scavenge the virtual registers that frame index elimiation
109   // inserted.
110   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
111     scavengeFrameVirtualRegs(Fn);
112
113   delete RS;
114   clearAllSets();
115   return true;
116 }
117
118 #if 0
119 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
120   AU.setPreservesCFG();
121   if (ShrinkWrapping || ShrinkWrapFunc != "") {
122     AU.addRequired<MachineLoopInfo>();
123     AU.addRequired<MachineDominatorTree>();
124   }
125   AU.addPreserved<MachineLoopInfo>();
126   AU.addPreserved<MachineDominatorTree>();
127   MachineFunctionPass::getAnalysisUsage(AU);
128 }
129 #endif
130
131 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
132 /// variables for the function's frame information and eliminate call frame
133 /// pseudo instructions.
134 void PEI::calculateCallsInformation(MachineFunction &Fn) {
135   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
136   MachineFrameInfo *MFI = Fn.getFrameInfo();
137
138   unsigned MaxCallFrameSize = 0;
139   bool AdjustsStack = MFI->adjustsStack();
140
141   // Get the function call frame set-up and tear-down instruction opcode
142   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
143   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
144
145   // Early exit for targets which have no call frame setup/destroy pseudo
146   // instructions.
147   if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
148     return;
149
150   std::vector<MachineBasicBlock::iterator> FrameSDOps;
151   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
152     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
153       if (I->getOpcode() == FrameSetupOpcode ||
154           I->getOpcode() == FrameDestroyOpcode) {
155         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
156                " instructions should have a single immediate argument!");
157         unsigned Size = I->getOperand(0).getImm();
158         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
159         AdjustsStack = true;
160         FrameSDOps.push_back(I);
161       } else if (I->isInlineAsm()) {
162         // Some inline asm's need a stack frame, as indicated by operand 1.
163         if (I->getOperand(1).getImm())
164           AdjustsStack = true;
165       }
166
167   MFI->setAdjustsStack(AdjustsStack);
168   MFI->setMaxCallFrameSize(MaxCallFrameSize);
169
170   for (std::vector<MachineBasicBlock::iterator>::iterator
171          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
172     MachineBasicBlock::iterator I = *i;
173
174     // If call frames are not being included as part of the stack frame, and
175     // the target doesn't indicate otherwise, remove the call frame pseudos
176     // here. The sub/add sp instruction pairs are still inserted, but we don't
177     // need to track the SP adjustment for frame index elimination.
178     if (RegInfo->canSimplifyCallFramePseudos(Fn))
179       RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
180   }
181 }
182
183
184 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
185 /// registers.
186 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
187   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
188   const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
189   MachineFrameInfo *MFI = Fn.getFrameInfo();
190
191   // Get the callee saved register list...
192   const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
193
194   // These are used to keep track the callee-save area. Initialize them.
195   MinCSFrameIndex = INT_MAX;
196   MaxCSFrameIndex = 0;
197
198   // Early exit for targets which have no callee saved registers.
199   if (CSRegs == 0 || CSRegs[0] == 0)
200     return;
201
202   // In Naked functions we aren't going to save any registers.
203   if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
204     return;
205
206   std::vector<CalleeSavedInfo> CSI;
207   for (unsigned i = 0; CSRegs[i]; ++i) {
208     unsigned Reg = CSRegs[i];
209     if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
210       // If the reg is modified, save it!
211       CSI.push_back(CalleeSavedInfo(Reg));
212     } else {
213       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
214            *AliasSet; ++AliasSet) {  // Check alias registers too.
215         if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
216           CSI.push_back(CalleeSavedInfo(Reg));
217           break;
218         }
219       }
220     }
221   }
222
223   if (CSI.empty())
224     return;   // Early exit if no callee saved registers are modified!
225
226   unsigned NumFixedSpillSlots;
227   const TargetFrameInfo::SpillSlot *FixedSpillSlots =
228     TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
229
230   // Now that we know which registers need to be saved and restored, allocate
231   // stack slots for them.
232   for (std::vector<CalleeSavedInfo>::iterator
233          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
234     unsigned Reg = I->getReg();
235     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
236
237     int FrameIdx;
238     if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
239       I->setFrameIdx(FrameIdx);
240       continue;
241     }
242
243     // Check to see if this physreg must be spilled to a particular stack slot
244     // on this target.
245     const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots;
246     while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
247            FixedSlot->Reg != Reg)
248       ++FixedSlot;
249
250     if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
251       // Nope, just spill it anywhere convenient.
252       unsigned Align = RC->getAlignment();
253       unsigned StackAlign = TFI->getStackAlignment();
254
255       // We may not be able to satisfy the desired alignment specification of
256       // the TargetRegisterClass if the stack alignment is smaller. Use the
257       // min.
258       Align = std::min(Align, StackAlign);
259       FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
260       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
261       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
262     } else {
263       // Spill it to the stack where we must.
264       FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
265     }
266
267     I->setFrameIdx(FrameIdx);
268   }
269
270   MFI->setCalleeSavedInfo(CSI);
271 }
272
273 /// insertCSRSpillsAndRestores - Insert spill and restore code for
274 /// callee saved registers used in the function, handling shrink wrapping.
275 ///
276 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
277   // Get callee saved register information.
278   MachineFrameInfo *MFI = Fn.getFrameInfo();
279   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
280
281   MFI->setCalleeSavedInfoValid(true);
282
283   // Early exit if no callee saved registers are modified!
284   if (CSI.empty())
285     return;
286
287   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
288   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
289   MachineBasicBlock::iterator I;
290
291   if (! ShrinkWrapThisFunction) {
292     // Spill using target interface.
293     I = EntryBlock->begin();
294     if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
295       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
296         // Add the callee-saved register as live-in.
297         // It's killed at the spill.
298         EntryBlock->addLiveIn(CSI[i].getReg());
299
300         // Insert the spill to the stack frame.
301         unsigned Reg = CSI[i].getReg();
302         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
303         TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
304                                 CSI[i].getFrameIdx(), RC, TRI);
305       }
306     }
307
308     // Restore using target interface.
309     for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
310       MachineBasicBlock* MBB = ReturnBlocks[ri];
311       I = MBB->end(); --I;
312
313       // Skip over all terminator instructions, which are part of the return
314       // sequence.
315       MachineBasicBlock::iterator I2 = I;
316       while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
317         I = I2;
318
319       bool AtStart = I == MBB->begin();
320       MachineBasicBlock::iterator BeforeI = I;
321       if (!AtStart)
322         --BeforeI;
323
324       // Restore all registers immediately before the return and any
325       // terminators that preceed it.
326       if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
327         for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
328           unsigned Reg = CSI[i].getReg();
329           const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
330           TII.loadRegFromStackSlot(*MBB, I, Reg,
331                                    CSI[i].getFrameIdx(),
332                                    RC, TRI);
333           assert(I != MBB->begin() &&
334                  "loadRegFromStackSlot didn't insert any code!");
335           // Insert in reverse order.  loadRegFromStackSlot can insert
336           // multiple instructions.
337           if (AtStart)
338             I = MBB->begin();
339           else {
340             I = BeforeI;
341             ++I;
342           }
343         }
344       }
345     }
346     return;
347   }
348
349   // Insert spills.
350   std::vector<CalleeSavedInfo> blockCSI;
351   for (CSRegBlockMap::iterator BI = CSRSave.begin(),
352          BE = CSRSave.end(); BI != BE; ++BI) {
353     MachineBasicBlock* MBB = BI->first;
354     CSRegSet save = BI->second;
355
356     if (save.empty())
357       continue;
358
359     blockCSI.clear();
360     for (CSRegSet::iterator RI = save.begin(),
361            RE = save.end(); RI != RE; ++RI) {
362       blockCSI.push_back(CSI[*RI]);
363     }
364     assert(blockCSI.size() > 0 &&
365            "Could not collect callee saved register info");
366
367     I = MBB->begin();
368
369     // When shrink wrapping, use stack slot stores/loads.
370     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
371       // Add the callee-saved register as live-in.
372       // It's killed at the spill.
373       MBB->addLiveIn(blockCSI[i].getReg());
374
375       // Insert the spill to the stack frame.
376       unsigned Reg = blockCSI[i].getReg();
377       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
378       TII.storeRegToStackSlot(*MBB, I, Reg,
379                               true,
380                               blockCSI[i].getFrameIdx(),
381                               RC, TRI);
382     }
383   }
384
385   for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
386          BE = CSRRestore.end(); BI != BE; ++BI) {
387     MachineBasicBlock* MBB = BI->first;
388     CSRegSet restore = BI->second;
389
390     if (restore.empty())
391       continue;
392
393     blockCSI.clear();
394     for (CSRegSet::iterator RI = restore.begin(),
395            RE = restore.end(); RI != RE; ++RI) {
396       blockCSI.push_back(CSI[*RI]);
397     }
398     assert(blockCSI.size() > 0 &&
399            "Could not find callee saved register info");
400
401     // If MBB is empty and needs restores, insert at the _beginning_.
402     if (MBB->empty()) {
403       I = MBB->begin();
404     } else {
405       I = MBB->end();
406       --I;
407
408       // Skip over all terminator instructions, which are part of the
409       // return sequence.
410       if (! I->getDesc().isTerminator()) {
411         ++I;
412       } else {
413         MachineBasicBlock::iterator I2 = I;
414         while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
415           I = I2;
416       }
417     }
418
419     bool AtStart = I == MBB->begin();
420     MachineBasicBlock::iterator BeforeI = I;
421     if (!AtStart)
422       --BeforeI;
423
424     // Restore all registers immediately before the return and any
425     // terminators that preceed it.
426     for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
427       unsigned Reg = blockCSI[i].getReg();
428       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
429       TII.loadRegFromStackSlot(*MBB, I, Reg,
430                                blockCSI[i].getFrameIdx(),
431                                RC, TRI);
432       assert(I != MBB->begin() &&
433              "loadRegFromStackSlot didn't insert any code!");
434       // Insert in reverse order.  loadRegFromStackSlot can insert
435       // multiple instructions.
436       if (AtStart)
437         I = MBB->begin();
438       else {
439         I = BeforeI;
440         ++I;
441       }
442     }
443   }
444 }
445
446 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
447 static inline void
448 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
449                   bool StackGrowsDown, int64_t &Offset,
450                   unsigned &MaxAlign) {
451   // If the stack grows down, add the object size to find the lowest address.
452   if (StackGrowsDown)
453     Offset += MFI->getObjectSize(FrameIdx);
454
455   unsigned Align = MFI->getObjectAlignment(FrameIdx);
456
457   // If the alignment of this object is greater than that of the stack, then
458   // increase the stack alignment to match.
459   MaxAlign = std::max(MaxAlign, Align);
460
461   // Adjust to alignment boundary.
462   Offset = (Offset + Align - 1) / Align * Align;
463
464   if (StackGrowsDown) {
465     MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
466   } else {
467     MFI->setObjectOffset(FrameIdx, Offset);
468     Offset += MFI->getObjectSize(FrameIdx);
469   }
470 }
471
472 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
473 /// abstract stack objects.
474 ///
475 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
476   const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
477
478   bool StackGrowsDown =
479     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
480
481   // Loop over all of the stack objects, assigning sequential addresses...
482   MachineFrameInfo *MFI = Fn.getFrameInfo();
483
484   // Start at the beginning of the local area.
485   // The Offset is the distance from the stack top in the direction
486   // of stack growth -- so it's always nonnegative.
487   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
488   if (StackGrowsDown)
489     LocalAreaOffset = -LocalAreaOffset;
490   assert(LocalAreaOffset >= 0
491          && "Local area offset should be in direction of stack growth");
492   int64_t Offset = LocalAreaOffset;
493
494   // If there are fixed sized objects that are preallocated in the local area,
495   // non-fixed objects can't be allocated right at the start of local area.
496   // We currently don't support filling in holes in between fixed sized
497   // objects, so we adjust 'Offset' to point to the end of last fixed sized
498   // preallocated object.
499   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
500     int64_t FixedOff;
501     if (StackGrowsDown) {
502       // The maximum distance from the stack pointer is at lower address of
503       // the object -- which is given by offset. For down growing stack
504       // the offset is negative, so we negate the offset to get the distance.
505       FixedOff = -MFI->getObjectOffset(i);
506     } else {
507       // The maximum distance from the start pointer is at the upper
508       // address of the object.
509       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
510     }
511     if (FixedOff > Offset) Offset = FixedOff;
512   }
513
514   // First assign frame offsets to stack objects that are used to spill
515   // callee saved registers.
516   if (StackGrowsDown) {
517     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
518       // If the stack grows down, we need to add the size to find the lowest
519       // address of the object.
520       Offset += MFI->getObjectSize(i);
521
522       unsigned Align = MFI->getObjectAlignment(i);
523       // Adjust to alignment boundary
524       Offset = (Offset+Align-1)/Align*Align;
525
526       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
527     }
528   } else {
529     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
530     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
531       unsigned Align = MFI->getObjectAlignment(i);
532       // Adjust to alignment boundary
533       Offset = (Offset+Align-1)/Align*Align;
534
535       MFI->setObjectOffset(i, Offset);
536       Offset += MFI->getObjectSize(i);
537     }
538   }
539
540   unsigned MaxAlign = MFI->getMaxAlignment();
541
542   // Make sure the special register scavenging spill slot is closest to the
543   // frame pointer if a frame pointer is required.
544   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
545   if (RS && RegInfo->hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
546     int SFI = RS->getScavengingFrameIndex();
547     if (SFI >= 0)
548       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
549   }
550
551   // Make sure that the stack protector comes before the local variables on the
552   // stack.
553   SmallSet<int, 16> LargeStackObjs;
554   if (MFI->getStackProtectorIndex() >= 0) {
555     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
556                       Offset, MaxAlign);
557
558     // Assign large stack objects first.
559     for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
560       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
561         continue;
562       if (RS && (int)i == RS->getScavengingFrameIndex())
563         continue;
564       if (MFI->isDeadObjectIndex(i))
565         continue;
566       if (MFI->getStackProtectorIndex() == (int)i)
567         continue;
568       if (!MFI->MayNeedStackProtector(i))
569         continue;
570
571       AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
572       LargeStackObjs.insert(i);
573     }
574   }
575
576   // Then assign frame offsets to stack objects that are not used to spill
577   // callee saved registers.
578   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
579     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
580       continue;
581     if (RS && (int)i == RS->getScavengingFrameIndex())
582       continue;
583     if (MFI->isDeadObjectIndex(i))
584       continue;
585     if (MFI->getStackProtectorIndex() == (int)i)
586       continue;
587     if (LargeStackObjs.count(i))
588       continue;
589
590     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
591   }
592
593   // Make sure the special register scavenging spill slot is closest to the
594   // stack pointer.
595   if (RS && (!RegInfo->hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
596     int SFI = RS->getScavengingFrameIndex();
597     if (SFI >= 0)
598       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
599   }
600
601   if (!RegInfo->targetHandlesStackFrameRounding()) {
602     // If we have reserved argument space for call sites in the function
603     // immediately on entry to the current function, count it as part of the
604     // overall stack size.
605     if (MFI->adjustsStack() && RegInfo->hasReservedCallFrame(Fn))
606       Offset += MFI->getMaxCallFrameSize();
607
608     // Round up the size to a multiple of the alignment.  If the function has
609     // any calls or alloca's, align to the target's StackAlignment value to
610     // ensure that the callee's frame or the alloca data is suitably aligned;
611     // otherwise, for leaf functions, align to the TransientStackAlignment
612     // value.
613     unsigned StackAlign;
614     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
615         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
616       StackAlign = TFI.getStackAlignment();
617     else
618       StackAlign = TFI.getTransientStackAlignment();
619
620     // If the frame pointer is eliminated, all frame offsets will be relative to
621     // SP not FP. Align to MaxAlign so this works.
622     StackAlign = std::max(StackAlign, MaxAlign);
623     unsigned AlignMask = StackAlign - 1;
624     Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
625   }
626
627   // Update frame info to pretend that this is part of the stack...
628   MFI->setStackSize(Offset - LocalAreaOffset);
629 }
630
631 /// insertPrologEpilogCode - Scan the function for modified callee saved
632 /// registers, insert spill code for these callee saved registers, then add
633 /// prolog and epilog code to the function.
634 ///
635 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
636   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
637
638   // Add prologue to the function...
639   TRI->emitPrologue(Fn);
640
641   // Add epilogue to restore the callee-save registers in each exiting block
642   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
643     // If last instruction is a return instruction, add an epilogue
644     if (!I->empty() && I->back().getDesc().isReturn())
645       TRI->emitEpilogue(Fn, *I);
646   }
647 }
648
649 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
650 /// register references and actual offsets.
651 ///
652 void PEI::replaceFrameIndices(MachineFunction &Fn) {
653   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
654
655   const TargetMachine &TM = Fn.getTarget();
656   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
657   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
658   const TargetFrameInfo *TFI = TM.getFrameInfo();
659   bool StackGrowsDown =
660     TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
661   int FrameSetupOpcode   = TRI.getCallFrameSetupOpcode();
662   int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
663
664   for (MachineFunction::iterator BB = Fn.begin(),
665          E = Fn.end(); BB != E; ++BB) {
666 #ifndef NDEBUG
667     int SPAdjCount = 0; // frame setup / destroy count.
668 #endif
669     int SPAdj = 0;  // SP offset due to call frame setup / destroy.
670     if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
671
672     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
673
674       if (I->getOpcode() == FrameSetupOpcode ||
675           I->getOpcode() == FrameDestroyOpcode) {
676 #ifndef NDEBUG
677         // Track whether we see even pairs of them
678         SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
679 #endif
680         // Remember how much SP has been adjusted to create the call
681         // frame.
682         int Size = I->getOperand(0).getImm();
683
684         if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
685             (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
686           Size = -Size;
687
688         SPAdj += Size;
689
690         MachineBasicBlock::iterator PrevI = BB->end();
691         if (I != BB->begin()) PrevI = prior(I);
692         TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
693
694         // Visit the instructions created by eliminateCallFramePseudoInstr().
695         if (PrevI == BB->end())
696           I = BB->begin();     // The replaced instr was the first in the block.
697         else
698           I = llvm::next(PrevI);
699         continue;
700       }
701
702       MachineInstr *MI = I;
703       bool DoIncr = true;
704       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
705         if (MI->getOperand(i).isFI()) {
706           // Some instructions (e.g. inline asm instructions) can have
707           // multiple frame indices and/or cause eliminateFrameIndex
708           // to insert more than one instruction. We need the register
709           // scavenger to go through all of these instructions so that
710           // it can update its register information. We keep the
711           // iterator at the point before insertion so that we can
712           // revisit them in full.
713           bool AtBeginning = (I == BB->begin());
714           if (!AtBeginning) --I;
715
716           // If this instruction has a FrameIndex operand, we need to
717           // use that target machine register info object to eliminate
718           // it.
719           TargetRegisterInfo::FrameIndexValue Value;
720           unsigned VReg =
721             TRI.eliminateFrameIndex(MI, SPAdj, &Value,
722                                     FrameIndexVirtualScavenging ?  NULL : RS);
723           if (VReg) {
724             assert (FrameIndexVirtualScavenging &&
725                     "Not scavenging, but virtual returned from "
726                     "eliminateFrameIndex()!");
727             FrameConstantRegMap[VReg] = FrameConstantEntry(Value, SPAdj);
728           }
729
730           // Reset the iterator if we were at the beginning of the BB.
731           if (AtBeginning) {
732             I = BB->begin();
733             DoIncr = false;
734           }
735
736           MI = 0;
737           break;
738         }
739
740       if (DoIncr && I != BB->end()) ++I;
741
742       // Update register states.
743       if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
744     }
745
746     // If we have evenly matched pairs of frame setup / destroy instructions,
747     // make sure the adjustments come out to zero. If we don't have matched
748     // pairs, we can't be sure the missing bit isn't in another basic block
749     // due to a custom inserter playing tricks, so just asserting SPAdj==0
750     // isn't sufficient. See tMOVCC on Thumb1, for example.
751     assert((SPAdjCount || SPAdj == 0) &&
752            "Unbalanced call frame setup / destroy pairs?");
753   }
754 }
755
756 /// findLastUseReg - find the killing use of the specified register within
757 /// the instruciton range. Return the operand number of the kill in Operand.
758 static MachineBasicBlock::iterator
759 findLastUseReg(MachineBasicBlock::iterator I, MachineBasicBlock::iterator ME,
760                unsigned Reg) {
761   // Scan forward to find the last use of this virtual register
762   for (++I; I != ME; ++I) {
763     MachineInstr *MI = I;
764     bool isDefInsn = false;
765     bool isKillInsn = false;
766     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
767       if (MI->getOperand(i).isReg()) {
768         unsigned OpReg = MI->getOperand(i).getReg();
769         if (OpReg == 0 || !TargetRegisterInfo::isVirtualRegister(OpReg))
770           continue;
771         assert (OpReg == Reg
772                 && "overlapping use of scavenged index register!");
773         // If this is the killing use, we have a candidate.
774         if (MI->getOperand(i).isKill())
775           isKillInsn = true;
776         else if (MI->getOperand(i).isDef())
777           isDefInsn = true;
778       }
779     if (isKillInsn && !isDefInsn)
780       return I;
781   }
782   // If we hit the end of the basic block, there was no kill of
783   // the virtual register, which is wrong.
784   assert (0 && "scavenged index register never killed!");
785   return ME;
786 }
787
788 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
789 /// with physical registers. Use the register scavenger to find an
790 /// appropriate register to use.
791 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
792   // Run through the instructions and find any virtual registers.
793   for (MachineFunction::iterator BB = Fn.begin(),
794        E = Fn.end(); BB != E; ++BB) {
795     RS->enterBasicBlock(BB);
796
797     // FIXME: The logic flow in this function is still too convoluted.
798     // It needs a cleanup refactoring. Do that in preparation for tracking
799     // more than one scratch register value and using ranges to find
800     // available scratch registers.
801     unsigned CurrentVirtReg = 0;
802     unsigned CurrentScratchReg = 0;
803     bool havePrevValue = false;
804     TargetRegisterInfo::FrameIndexValue PrevValue(0,0);
805     TargetRegisterInfo::FrameIndexValue Value(0,0);
806     MachineInstr *PrevLastUseMI = NULL;
807     unsigned PrevLastUseOp = 0;
808     bool trackingCurrentValue = false;
809     int SPAdj = 0;
810
811     // The instruction stream may change in the loop, so check BB->end()
812     // directly.
813     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
814       MachineInstr *MI = I;
815       bool isDefInsn = false;
816       bool isKillInsn = false;
817       bool clobbersScratchReg = false;
818       bool DoIncr = true;
819       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
820         if (MI->getOperand(i).isReg()) {
821           MachineOperand &MO = MI->getOperand(i);
822           unsigned Reg = MO.getReg();
823           if (Reg == 0)
824             continue;
825           if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
826             // If we have a previous scratch reg, check and see if anything
827             // here kills whatever value is in there.
828             if (Reg == CurrentScratchReg) {
829               if (MO.isUse()) {
830                 // Two-address operands implicitly kill
831                 if (MO.isKill() || MI->isRegTiedToDefOperand(i))
832                   clobbersScratchReg = true;
833               } else {
834                 assert (MO.isDef());
835                 clobbersScratchReg = true;
836               }
837             }
838             continue;
839           }
840           // If this is a def, remember that this insn defines the value.
841           // This lets us properly consider insns which re-use the scratch
842           // register, such as r2 = sub r2, #imm, in the middle of the
843           // scratch range.
844           if (MO.isDef())
845             isDefInsn = true;
846
847           // Have we already allocated a scratch register for this virtual?
848           if (Reg != CurrentVirtReg) {
849             // When we first encounter a new virtual register, it
850             // must be a definition.
851             assert(MI->getOperand(i).isDef() &&
852                    "frame index virtual missing def!");
853             // We can't have nested virtual register live ranges because
854             // there's only a guarantee of one scavenged register at a time.
855             assert (CurrentVirtReg == 0 &&
856                     "overlapping frame index virtual registers!");
857
858             // If the target gave us information about what's in the register,
859             // we can use that to re-use scratch regs.
860             DenseMap<unsigned, FrameConstantEntry>::iterator Entry =
861               FrameConstantRegMap.find(Reg);
862             trackingCurrentValue = Entry != FrameConstantRegMap.end();
863             if (trackingCurrentValue) {
864               SPAdj = (*Entry).second.second;
865               Value = (*Entry).second.first;
866             } else {
867               SPAdj = 0;
868               Value.first = 0;
869               Value.second = 0;
870             }
871
872             // If the scratch register from the last allocation is still
873             // available, see if the value matches. If it does, just re-use it.
874             if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
875               // FIXME: This assumes that the instructions in the live range
876               // for the virtual register are exclusively for the purpose
877               // of populating the value in the register. That's reasonable
878               // for these frame index registers, but it's still a very, very
879               // strong assumption. rdar://7322732. Better would be to
880               // explicitly check each instruction in the range for references
881               // to the virtual register. Only delete those insns that
882               // touch the virtual register.
883
884               // Find the last use of the new virtual register. Remove all
885               // instruction between here and there, and update the current
886               // instruction to reference the last use insn instead.
887               MachineBasicBlock::iterator LastUseMI =
888                 findLastUseReg(I, BB->end(), Reg);
889
890               // Remove all instructions up 'til the last use, since they're
891               // just calculating the value we already have.
892               BB->erase(I, LastUseMI);
893               I = LastUseMI;
894
895               // Extend the live range of the scratch register
896               PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
897               RS->setUsed(CurrentScratchReg);
898               CurrentVirtReg = Reg;
899
900               // We deleted the instruction we were scanning the operands of.
901               // Jump back to the instruction iterator loop. Don't increment
902               // past this instruction since we updated the iterator already.
903               DoIncr = false;
904               break;
905             }
906
907             // Scavenge a new scratch register
908             CurrentVirtReg = Reg;
909             const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
910             CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
911             PrevValue = Value;
912           }
913           // replace this reference to the virtual register with the
914           // scratch register.
915           assert (CurrentScratchReg && "Missing scratch register!");
916           MI->getOperand(i).setReg(CurrentScratchReg);
917
918           if (MI->getOperand(i).isKill()) {
919             isKillInsn = true;
920             PrevLastUseOp = i;
921             PrevLastUseMI = MI;
922           }
923         }
924       }
925       // If this is the last use of the scratch, stop tracking it. The
926       // last use will be a kill operand in an instruction that does
927       // not also define the scratch register.
928       if (isKillInsn && !isDefInsn) {
929         CurrentVirtReg = 0;
930         havePrevValue = trackingCurrentValue;
931       }
932       // Similarly, notice if instruction clobbered the value in the
933       // register we're tracking for possible later reuse. This is noted
934       // above, but enforced here since the value is still live while we
935       // process the rest of the operands of the instruction.
936       if (clobbersScratchReg) {
937         havePrevValue = false;
938         CurrentScratchReg = 0;
939       }
940       if (DoIncr) {
941         RS->forward(I);
942         ++I;
943       }
944     }
945   }
946 }