blob: 2e95300160d819b6cb2ec85213415a61de6bdcaa [file] [log] [blame]
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001//=======- X86FrameLowering.cpp - X86 Frame Information ------------*- C++ -*-====//
Anton Korobeynikov33464912010-11-15 00:06:54 +00002//
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//
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000010// This file contains the X86 implementation of TargetFrameLowering class.
Anton Korobeynikov33464912010-11-15 00:06:54 +000011//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000014#include "X86FrameLowering.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000015#include "X86InstrBuilder.h"
16#include "X86InstrInfo.h"
17#include "X86MachineFunctionInfo.h"
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000018#include "X86TargetMachine.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000019#include "llvm/Function.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
Rafael Espindolaf0adba92011-04-15 15:11:06 +000025#include "llvm/MC/MCAsmInfo.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetOptions.h"
28#include "llvm/Support/CommandLine.h"
Evan Cheng7158e082011-01-03 22:53:22 +000029#include "llvm/ADT/SmallSet.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000030
31using namespace llvm;
32
33// FIXME: completely move here.
34extern cl::opt<bool> ForceStackAlign;
35
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000036bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000037 return !MF.getFrameInfo()->hasVarSizedObjects();
38}
39
40/// hasFP - Return true if the specified function should have a dedicated frame
41/// pointer register. This is true if the function has variable sized allocas
42/// or if frame pointer elimination is disabled.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000043bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000044 const MachineFrameInfo *MFI = MF.getFrameInfo();
45 const MachineModuleInfo &MMI = MF.getMMI();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000046 const TargetRegisterInfo *RI = TM.getRegisterInfo();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000047
48 return (DisableFramePointerElim(MF) ||
49 RI->needsStackRealignment(MF) ||
50 MFI->hasVarSizedObjects() ||
51 MFI->isFrameAddressTaken() ||
52 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
53 MMI.callsUnwindInit());
54}
55
Anton Korobeynikov33464912010-11-15 00:06:54 +000056static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
57 if (is64Bit) {
58 if (isInt<8>(Imm))
59 return X86::SUB64ri8;
60 return X86::SUB64ri32;
61 } else {
62 if (isInt<8>(Imm))
63 return X86::SUB32ri8;
64 return X86::SUB32ri;
65 }
66}
67
68static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
69 if (is64Bit) {
70 if (isInt<8>(Imm))
71 return X86::ADD64ri8;
72 return X86::ADD64ri32;
73 } else {
74 if (isInt<8>(Imm))
75 return X86::ADD32ri8;
76 return X86::ADD32ri;
77 }
78}
79
Evan Cheng7158e082011-01-03 22:53:22 +000080/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
81/// when it reaches the "return" instruction. We can then pop a stack object
82/// to this register without worry about clobbering it.
83static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
84 MachineBasicBlock::iterator &MBBI,
85 const TargetRegisterInfo &TRI,
86 bool Is64Bit) {
87 const MachineFunction *MF = MBB.getParent();
88 const Function *F = MF->getFunction();
89 if (!F || MF->getMMI().callsEHReturn())
90 return 0;
91
92 static const unsigned CallerSavedRegs32Bit[] = {
93 X86::EAX, X86::EDX, X86::ECX
94 };
95
96 static const unsigned CallerSavedRegs64Bit[] = {
97 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
98 X86::R8, X86::R9, X86::R10, X86::R11
99 };
100
101 unsigned Opc = MBBI->getOpcode();
102 switch (Opc) {
103 default: return 0;
104 case X86::RET:
105 case X86::RETI:
106 case X86::TCRETURNdi:
107 case X86::TCRETURNri:
108 case X86::TCRETURNmi:
109 case X86::TCRETURNdi64:
110 case X86::TCRETURNri64:
111 case X86::TCRETURNmi64:
112 case X86::EH_RETURN:
113 case X86::EH_RETURN64: {
114 SmallSet<unsigned, 8> Uses;
115 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
116 MachineOperand &MO = MBBI->getOperand(i);
117 if (!MO.isReg() || MO.isDef())
118 continue;
119 unsigned Reg = MO.getReg();
120 if (!Reg)
121 continue;
122 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
123 Uses.insert(*AsI);
124 }
125
126 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
127 for (; *CS; ++CS)
128 if (!Uses.count(*CS))
129 return *CS;
130 }
131 }
132
133 return 0;
134}
135
136
Anton Korobeynikov33464912010-11-15 00:06:54 +0000137/// emitSPUpdate - Emit a series of instructions to increment / decrement the
138/// stack pointer by a constant value.
139static
140void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng7158e082011-01-03 22:53:22 +0000141 unsigned StackPtr, int64_t NumBytes,
142 bool Is64Bit, const TargetInstrInfo &TII,
143 const TargetRegisterInfo &TRI) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000144 bool isSub = NumBytes < 0;
145 uint64_t Offset = isSub ? -NumBytes : NumBytes;
146 unsigned Opc = isSub ?
147 getSUBriOpcode(Is64Bit, Offset) :
148 getADDriOpcode(Is64Bit, Offset);
149 uint64_t Chunk = (1LL << 31) - 1;
150 DebugLoc DL = MBB.findDebugLoc(MBBI);
151
152 while (Offset) {
153 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng7158e082011-01-03 22:53:22 +0000154 if (ThisVal == (Is64Bit ? 8 : 4)) {
155 // Use push / pop instead.
156 unsigned Reg = isSub
Dale Johannesen1e08cd12011-01-04 19:31:24 +0000157 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng7158e082011-01-03 22:53:22 +0000158 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
159 if (Reg) {
160 Opc = isSub
161 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
162 : (Is64Bit ? X86::POP64r : X86::POP32r);
163 BuildMI(MBB, MBBI, DL, TII.get(Opc))
164 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
165 Offset -= ThisVal;
166 continue;
167 }
168 }
169
Anton Korobeynikov33464912010-11-15 00:06:54 +0000170 MachineInstr *MI =
171 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Evan Cheng7158e082011-01-03 22:53:22 +0000172 .addReg(StackPtr)
173 .addImm(ThisVal);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000174 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
175 Offset -= ThisVal;
176 }
177}
178
179/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
180static
181void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
182 unsigned StackPtr, uint64_t *NumBytes = NULL) {
183 if (MBBI == MBB.begin()) return;
184
185 MachineBasicBlock::iterator PI = prior(MBBI);
186 unsigned Opc = PI->getOpcode();
187 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
188 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
189 PI->getOperand(0).getReg() == StackPtr) {
190 if (NumBytes)
191 *NumBytes += PI->getOperand(2).getImm();
192 MBB.erase(PI);
193 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
194 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
195 PI->getOperand(0).getReg() == StackPtr) {
196 if (NumBytes)
197 *NumBytes -= PI->getOperand(2).getImm();
198 MBB.erase(PI);
199 }
200}
201
202/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
203static
204void mergeSPUpdatesDown(MachineBasicBlock &MBB,
205 MachineBasicBlock::iterator &MBBI,
206 unsigned StackPtr, uint64_t *NumBytes = NULL) {
207 // FIXME: THIS ISN'T RUN!!!
208 return;
209
210 if (MBBI == MBB.end()) return;
211
212 MachineBasicBlock::iterator NI = llvm::next(MBBI);
213 if (NI == MBB.end()) return;
214
215 unsigned Opc = NI->getOpcode();
216 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
217 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
218 NI->getOperand(0).getReg() == StackPtr) {
219 if (NumBytes)
220 *NumBytes -= NI->getOperand(2).getImm();
221 MBB.erase(NI);
222 MBBI = NI;
223 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
224 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
225 NI->getOperand(0).getReg() == StackPtr) {
226 if (NumBytes)
227 *NumBytes += NI->getOperand(2).getImm();
228 MBB.erase(NI);
229 MBBI = NI;
230 }
231}
232
233/// mergeSPUpdates - Checks the instruction before/after the passed
234/// instruction. If it is an ADD/SUB instruction it is deleted argument and the
235/// stack adjustment is returned as a positive value for ADD and a negative for
236/// SUB.
237static int mergeSPUpdates(MachineBasicBlock &MBB,
238 MachineBasicBlock::iterator &MBBI,
239 unsigned StackPtr,
240 bool doMergeWithPrevious) {
241 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
242 (!doMergeWithPrevious && MBBI == MBB.end()))
243 return 0;
244
245 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
246 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
247 unsigned Opc = PI->getOpcode();
248 int Offset = 0;
249
250 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
251 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
252 PI->getOperand(0).getReg() == StackPtr){
253 Offset += PI->getOperand(2).getImm();
254 MBB.erase(PI);
255 if (!doMergeWithPrevious) MBBI = NI;
256 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
257 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
258 PI->getOperand(0).getReg() == StackPtr) {
259 Offset -= PI->getOperand(2).getImm();
260 MBB.erase(PI);
261 if (!doMergeWithPrevious) MBBI = NI;
262 }
263
264 return Offset;
265}
266
267static bool isEAXLiveIn(MachineFunction &MF) {
268 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
269 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
270 unsigned Reg = II->first;
271
272 if (Reg == X86::EAX || Reg == X86::AX ||
273 Reg == X86::AH || Reg == X86::AL)
274 return true;
275 }
276
277 return false;
278}
279
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000280void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
Anton Korobeynikov33464912010-11-15 00:06:54 +0000281 MCSymbol *Label,
282 unsigned FramePtr) const {
283 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000284 MachineModuleInfo &MMI = MF.getMMI();
285
286 // Add callee saved registers to move list.
287 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
288 if (CSI.empty()) return;
289
290 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000291 const TargetData *TD = TM.getTargetData();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000292 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000293
294 // Calculate amount of bytes used for return address storing.
Anton Korobeynikove7499112011-01-14 21:57:58 +0000295 int stackGrowth = -TD->getPointerSize();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000296
297 // FIXME: This is dirty hack. The code itself is pretty mess right now.
298 // It should be rewritten from scratch and generalized sometimes.
299
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000300 // Determine maximum offset (minimum due to stack growth).
Anton Korobeynikov33464912010-11-15 00:06:54 +0000301 int64_t MaxOffset = 0;
302 for (std::vector<CalleeSavedInfo>::const_iterator
303 I = CSI.begin(), E = CSI.end(); I != E; ++I)
304 MaxOffset = std::min(MaxOffset,
305 MFI->getObjectOffset(I->getFrameIdx()));
306
307 // Calculate offsets.
308 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
309 for (std::vector<CalleeSavedInfo>::const_iterator
310 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
311 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
312 unsigned Reg = I->getReg();
313 Offset = MaxOffset - Offset + saveAreaOffset;
314
315 // Don't output a new machine move if we're re-saving the frame
316 // pointer. This happens when the PrologEpilogInserter has inserted an extra
317 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
318 // generates one when frame pointers are used. If we generate a "machine
319 // move" for this extra "PUSH", the linker will lose track of the fact that
320 // the frame pointer should have the value of the first "PUSH" when it's
321 // trying to unwind.
NAKAMURA Takumi27635382011-02-05 15:10:54 +0000322 //
Anton Korobeynikov33464912010-11-15 00:06:54 +0000323 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
324 // another bug. I.e., one where we generate a prolog like this:
325 //
326 // pushl %ebp
327 // movl %esp, %ebp
328 // pushl %ebp
329 // pushl %esi
330 // ...
331 //
332 // The immediate re-push of EBP is unnecessary. At the least, it's an
333 // optimization bug. EBP can be used as a scratch register in certain
334 // cases, but probably not when we have a frame pointer.
335 if (HasFP && FramePtr == Reg)
336 continue;
337
338 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
339 MachineLocation CSSrc(Reg);
340 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
341 }
342}
343
344/// emitPrologue - Push callee-saved registers onto the stack, which
345/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
346/// space for local variables. Also emit labels used by the exception handler to
347/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000348void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000349 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
350 MachineBasicBlock::iterator MBBI = MBB.begin();
351 MachineFrameInfo *MFI = MF.getFrameInfo();
352 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000353 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
354 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000355 MachineModuleInfo &MMI = MF.getMMI();
356 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
357 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000358 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000359 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
360 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000361 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000362 bool Is64Bit = STI.is64Bit();
363 bool IsWin64 = STI.isTargetWin64();
364 unsigned StackAlign = getStackAlignment();
365 unsigned SlotSize = RegInfo->getSlotSize();
366 unsigned FramePtr = RegInfo->getFrameRegister(MF);
367 unsigned StackPtr = RegInfo->getStackRegister();
368
369 DebugLoc DL;
370
371 // If we're forcing a stack realignment we can't rely on just the frame
372 // info, we need to know the ABI stack alignment as well in case we
373 // have a call out. Otherwise just make sure we have some alignment - we'll
374 // go with the minimum SlotSize.
375 if (ForceStackAlign) {
376 if (MFI->hasCalls())
377 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
378 else if (MaxAlign < SlotSize)
379 MaxAlign = SlotSize;
380 }
381
382 // Add RETADDR move area to callee saved frame size.
383 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
384 if (TailCallReturnAddrDelta < 0)
385 X86FI->setCalleeSavedFrameSize(
386 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
387
388 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
389 // function, and use up to 128 bytes of stack space, don't have a frame
390 // pointer, calls, or dynamic alloca then we do not need to adjust the
391 // stack pointer (we fit in the Red Zone).
392 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
393 !RegInfo->needsStackRealignment(MF) &&
394 !MFI->hasVarSizedObjects() && // No dynamic alloca.
395 !MFI->adjustsStack() && // No calls.
396 !IsWin64) { // Win64 has no Red Zone
397 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
398 if (HasFP) MinSize += SlotSize;
399 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
400 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000401 }
402
403 // Insert stack pointer adjustment for later moving of return addr. Only
404 // applies to tail call optimized functions where the callee argument stack
405 // size is bigger than the callers.
406 if (TailCallReturnAddrDelta < 0) {
407 MachineInstr *MI =
408 BuildMI(MBB, MBBI, DL,
409 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
410 StackPtr)
411 .addReg(StackPtr)
412 .addImm(-TailCallReturnAddrDelta);
413 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
414 }
415
416 // Mapping for machine moves:
417 //
418 // DST: VirtualFP AND
419 // SRC: VirtualFP => DW_CFA_def_cfa_offset
420 // ELSE => DW_CFA_def_cfa
421 //
422 // SRC: VirtualFP AND
423 // DST: Register => DW_CFA_def_cfa_register
424 //
425 // ELSE
426 // OFFSET < 0 => DW_CFA_offset_extended_sf
427 // REG < 64 => DW_CFA_offset + Reg
428 // ELSE => DW_CFA_offset_extended
429
430 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
431 const TargetData *TD = MF.getTarget().getTargetData();
432 uint64_t NumBytes = 0;
433 int stackGrowth = -TD->getPointerSize();
434
435 if (HasFP) {
436 // Calculate required stack adjustment.
437 uint64_t FrameSize = StackSize - SlotSize;
438 if (RegInfo->needsStackRealignment(MF))
439 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
440
441 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
442
443 // Get the offset of the stack slot for the EBP register, which is
444 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
445 // Update the frame offset adjustment.
446 MFI->setOffsetAdjustment(-NumBytes);
447
448 // Save EBP/RBP into the appropriate stack slot.
449 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
450 .addReg(FramePtr, RegState::Kill);
451
452 if (needsFrameMoves) {
453 // Mark the place where EBP/RBP was saved.
454 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
455 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
456
457 // Define the current CFA rule to use the provided offset.
458 if (StackSize) {
459 MachineLocation SPDst(MachineLocation::VirtualFP);
460 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
461 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
462 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000463 MachineLocation SPDst(StackPtr);
464 MachineLocation SPSrc(StackPtr, stackGrowth);
465 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
466 }
467
468 // Change the rule for the FramePtr to be an "offset" rule.
469 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
470 MachineLocation FPSrc(FramePtr);
471 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
472 }
473
474 // Update EBP with the new base value...
475 BuildMI(MBB, MBBI, DL,
476 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
477 .addReg(StackPtr);
478
479 if (needsFrameMoves) {
480 // Mark effective beginning of when frame pointer becomes valid.
481 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
482 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
483
484 // Define the current CFA to use the EBP/RBP register.
485 MachineLocation FPDst(FramePtr);
486 MachineLocation FPSrc(MachineLocation::VirtualFP);
487 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
488 }
489
490 // Mark the FramePtr as live-in in every block except the entry.
491 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
492 I != E; ++I)
493 I->addLiveIn(FramePtr);
494
495 // Realign stack
496 if (RegInfo->needsStackRealignment(MF)) {
497 MachineInstr *MI =
498 BuildMI(MBB, MBBI, DL,
499 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
500 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
501
502 // The EFLAGS implicit def is dead.
503 MI->getOperand(3).setIsDead();
504 }
505 } else {
506 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
507 }
508
509 // Skip the callee-saved push instructions.
510 bool PushedRegs = false;
511 int StackOffset = 2 * stackGrowth;
512
513 while (MBBI != MBB.end() &&
514 (MBBI->getOpcode() == X86::PUSH32r ||
515 MBBI->getOpcode() == X86::PUSH64r)) {
516 PushedRegs = true;
517 ++MBBI;
518
519 if (!HasFP && needsFrameMoves) {
520 // Mark callee-saved push instruction.
521 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
522 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
523
524 // Define the current CFA rule to use the provided offset.
525 unsigned Ptr = StackSize ?
526 MachineLocation::VirtualFP : StackPtr;
527 MachineLocation SPDst(Ptr);
528 MachineLocation SPSrc(Ptr, StackOffset);
529 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
530 StackOffset += stackGrowth;
531 }
532 }
533
534 DL = MBB.findDebugLoc(MBBI);
535
536 // If there is an SUB32ri of ESP immediately before this instruction, merge
537 // the two. This can be the case when tail call elimination is enabled and
538 // the callee has more arguments then the caller.
539 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
540
541 // If there is an ADD32ri or SUB32ri of ESP immediately after this
542 // instruction, merge the two instructions.
543 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
544
545 // Adjust stack pointer: ESP -= numbytes.
546
547 // Windows and cygwin/mingw require a prologue helper routine when allocating
548 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
549 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
550 // stack and adjust the stack pointer in one go. The 64-bit version of
551 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
552 // responsible for adjusting the stack pointer. Touching the stack at 4K
553 // increments is necessary to ensure that the guard pages used by the OS
554 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000555 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
556 const char *StackProbeSymbol;
557 bool isSPUpdateNeeded = false;
558
559 if (Is64Bit) {
560 if (STI.isTargetCygMing())
561 StackProbeSymbol = "___chkstk";
562 else {
563 StackProbeSymbol = "__chkstk";
564 isSPUpdateNeeded = true;
565 }
566 } else if (STI.isTargetCygMing())
567 StackProbeSymbol = "_alloca";
568 else
569 StackProbeSymbol = "_chkstk";
570
Anton Korobeynikov33464912010-11-15 00:06:54 +0000571 // Check whether EAX is livein for this function.
572 bool isEAXAlive = isEAXLiveIn(MF);
573
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000574 if (isEAXAlive) {
575 // Sanity check that EAX is not livein for this function.
576 // It should not be, so throw an assert.
577 assert(!Is64Bit && "EAX is livein in x64 case!");
578
Anton Korobeynikov33464912010-11-15 00:06:54 +0000579 // Save EAX
580 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
581 .addReg(X86::EAX, RegState::Kill);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000582 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000583
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000584 if (Is64Bit) {
585 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
586 // Function prologue is responsible for adjusting the stack pointer.
587 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
588 .addImm(NumBytes);
589 } else {
590 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
591 // We'll also use 4 already allocated bytes for EAX.
592 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
593 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes);
594 }
595
596 BuildMI(MBB, MBBI, DL,
597 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
598 .addExternalSymbol(StackProbeSymbol)
599 .addReg(StackPtr, RegState::Define | RegState::Implicit)
600 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
601
602 // MSVC x64's __chkstk needs to adjust %rsp.
603 // FIXME: %rax preserves the offset and should be available.
604 if (isSPUpdateNeeded)
605 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
606 TII, *RegInfo);
607
608 if (isEAXAlive) {
609 // Restore EAX
610 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
611 X86::EAX),
612 StackPtr, false, NumBytes - 4);
613 MBB.insert(MBBI, MI);
614 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000615 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000616 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
617 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000618
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000619 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000620 // Mark end of stack pointer adjustment.
621 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
622 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
623
624 if (!HasFP && NumBytes) {
625 // Define the current CFA rule to use the provided offset.
626 if (StackSize) {
627 MachineLocation SPDst(MachineLocation::VirtualFP);
628 MachineLocation SPSrc(MachineLocation::VirtualFP,
629 -StackSize + stackGrowth);
630 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
631 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000632 MachineLocation SPDst(StackPtr);
633 MachineLocation SPSrc(StackPtr, stackGrowth);
634 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
635 }
636 }
637
638 // Emit DWARF info specifying the offsets of the callee-saved registers.
639 if (PushedRegs)
640 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
641 }
642}
643
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000644void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Anton Korobeynikov33464912010-11-15 00:06:54 +0000645 MachineBasicBlock &MBB) const {
646 const MachineFrameInfo *MFI = MF.getFrameInfo();
647 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000648 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
649 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000650 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
651 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000652 unsigned RetOpcode = MBBI->getOpcode();
653 DebugLoc DL = MBBI->getDebugLoc();
654 bool Is64Bit = STI.is64Bit();
655 unsigned StackAlign = getStackAlignment();
656 unsigned SlotSize = RegInfo->getSlotSize();
657 unsigned FramePtr = RegInfo->getFrameRegister(MF);
658 unsigned StackPtr = RegInfo->getStackRegister();
659
660 switch (RetOpcode) {
661 default:
662 llvm_unreachable("Can only insert epilog into returning blocks");
663 case X86::RET:
664 case X86::RETI:
665 case X86::TCRETURNdi:
666 case X86::TCRETURNri:
667 case X86::TCRETURNmi:
668 case X86::TCRETURNdi64:
669 case X86::TCRETURNri64:
670 case X86::TCRETURNmi64:
671 case X86::EH_RETURN:
672 case X86::EH_RETURN64:
673 break; // These are ok
674 }
675
676 // Get the number of bytes to allocate from the FrameInfo.
677 uint64_t StackSize = MFI->getStackSize();
678 uint64_t MaxAlign = MFI->getMaxAlignment();
679 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
680 uint64_t NumBytes = 0;
681
682 // If we're forcing a stack realignment we can't rely on just the frame
683 // info, we need to know the ABI stack alignment as well in case we
684 // have a call out. Otherwise just make sure we have some alignment - we'll
685 // go with the minimum.
686 if (ForceStackAlign) {
687 if (MFI->hasCalls())
688 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
689 else
690 MaxAlign = MaxAlign ? MaxAlign : 4;
691 }
692
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000693 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000694 // Calculate required stack adjustment.
695 uint64_t FrameSize = StackSize - SlotSize;
696 if (RegInfo->needsStackRealignment(MF))
697 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
698
699 NumBytes = FrameSize - CSSize;
700
701 // Pop EBP.
702 BuildMI(MBB, MBBI, DL,
703 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
704 } else {
705 NumBytes = StackSize - CSSize;
706 }
707
708 // Skip the callee-saved pop instructions.
709 MachineBasicBlock::iterator LastCSPop = MBBI;
710 while (MBBI != MBB.begin()) {
711 MachineBasicBlock::iterator PI = prior(MBBI);
712 unsigned Opc = PI->getOpcode();
713
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000714 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000715 !PI->getDesc().isTerminator())
716 break;
717
718 --MBBI;
719 }
720
721 DL = MBBI->getDebugLoc();
722
723 // If there is an ADD32ri or SUB32ri of ESP immediately before this
724 // instruction, merge the two instructions.
725 if (NumBytes || MFI->hasVarSizedObjects())
726 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
727
728 // If dynamic alloca is used, then reset esp to point to the last callee-saved
729 // slot before popping them off! Same applies for the case, when stack was
730 // realigned.
731 if (RegInfo->needsStackRealignment(MF)) {
732 // We cannot use LEA here, because stack pointer was realigned. We need to
733 // deallocate local frame back.
734 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +0000735 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000736 MBBI = prior(LastCSPop);
737 }
738
739 BuildMI(MBB, MBBI, DL,
740 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
741 StackPtr).addReg(FramePtr);
742 } else if (MFI->hasVarSizedObjects()) {
743 if (CSSize) {
744 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
745 MachineInstr *MI =
746 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
747 FramePtr, false, -CSSize);
748 MBB.insert(MBBI, MI);
749 } else {
750 BuildMI(MBB, MBBI, DL,
751 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
752 .addReg(FramePtr);
753 }
754 } else if (NumBytes) {
755 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +0000756 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000757 }
758
759 // We're returning from function via eh_return.
760 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000761 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000762 MachineOperand &DestAddr = MBBI->getOperand(0);
763 assert(DestAddr.isReg() && "Offset should be in register!");
764 BuildMI(MBB, MBBI, DL,
765 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
766 StackPtr).addReg(DestAddr.getReg());
767 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
768 RetOpcode == X86::TCRETURNmi ||
769 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
770 RetOpcode == X86::TCRETURNmi64) {
771 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
772 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +0000773 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000774 MachineOperand &JumpTarget = MBBI->getOperand(0);
775 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
776 assert(StackAdjust.isImm() && "Expecting immediate value.");
777
778 // Adjust stack pointer.
779 int StackAdj = StackAdjust.getImm();
780 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
781 int Offset = 0;
782 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
783
784 // Incoporate the retaddr area.
785 Offset = StackAdj-MaxTCDelta;
786 assert(Offset >= 0 && "Offset should never be negative");
787
788 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000789 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000790 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +0000791 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000792 }
793
794 // Jump to label or value in register.
795 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +0000796 MachineInstrBuilder MIB =
797 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
798 ? X86::TAILJMPd : X86::TAILJMPd64));
799 if (JumpTarget.isGlobal())
800 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
801 JumpTarget.getTargetFlags());
802 else {
803 assert(JumpTarget.isSymbol());
804 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
805 JumpTarget.getTargetFlags());
806 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000807 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
808 MachineInstrBuilder MIB =
809 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
810 ? X86::TAILJMPm : X86::TAILJMPm64));
811 for (unsigned i = 0; i != 5; ++i)
812 MIB.addOperand(MBBI->getOperand(i));
813 } else if (RetOpcode == X86::TCRETURNri64) {
814 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
815 addReg(JumpTarget.getReg(), RegState::Kill);
816 } else {
817 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
818 addReg(JumpTarget.getReg(), RegState::Kill);
819 }
820
821 MachineInstr *NewMI = prior(MBBI);
822 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
823 NewMI->addOperand(MBBI->getOperand(i));
824
825 // Delete the pseudo instruction TCRETURN.
826 MBB.erase(MBBI);
827 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
828 (X86FI->getTCReturnAddrDelta() < 0)) {
829 // Add the return addr area delta back since we are not tail calling.
830 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000831 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000832
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000833 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000834 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +0000835 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000836 }
837}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000838
839void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000840X86FrameLowering::getInitialFrameState(std::vector<MachineMove> &Moves) const {
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000841 // Calculate amount of bytes used for return address storing
842 int stackGrowth = (STI.is64Bit() ? -8 : -4);
843 const X86RegisterInfo *RI = TM.getRegisterInfo();
844
845 // Initial state of the frame pointer is esp+stackGrowth.
846 MachineLocation Dst(MachineLocation::VirtualFP);
847 MachineLocation Src(RI->getStackRegister(), stackGrowth);
848 Moves.push_back(MachineMove(0, Dst, Src));
849
850 // Add return address to move list
851 MachineLocation CSDst(RI->getStackRegister(), stackGrowth);
852 MachineLocation CSSrc(RI->getRARegister());
853 Moves.push_back(MachineMove(0, CSDst, CSSrc));
854}
Anton Korobeynikov82f58742010-11-20 15:59:32 +0000855
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000856int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +0000857 const X86RegisterInfo *RI =
858 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
859 const MachineFrameInfo *MFI = MF.getFrameInfo();
860 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
861 uint64_t StackSize = MFI->getStackSize();
862
863 if (RI->needsStackRealignment(MF)) {
864 if (FI < 0) {
865 // Skip the saved EBP.
866 Offset += RI->getSlotSize();
867 } else {
868 unsigned Align = MFI->getObjectAlignment(FI);
869 assert((-(Offset + StackSize)) % Align == 0);
870 Align = 0;
871 return Offset + StackSize;
872 }
873 // FIXME: Support tail calls
874 } else {
875 if (!hasFP(MF))
876 return Offset + StackSize;
877
878 // Skip the saved EBP.
879 Offset += RI->getSlotSize();
880
881 // Skip the RETADDR move area
882 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
883 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
884 if (TailCallReturnAddrDelta < 0)
885 Offset -= TailCallReturnAddrDelta;
886 }
887
888 return Offset;
889}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000890
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000891bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000892 MachineBasicBlock::iterator MI,
893 const std::vector<CalleeSavedInfo> &CSI,
894 const TargetRegisterInfo *TRI) const {
895 if (CSI.empty())
896 return false;
897
898 DebugLoc DL = MBB.findDebugLoc(MI);
899
900 MachineFunction &MF = *MBB.getParent();
901
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000902 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
903 unsigned FPReg = TRI->getFrameRegister(MF);
904 unsigned CalleeFrameSize = 0;
905
906 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
907 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
908
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000909 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000910 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
911 for (unsigned i = CSI.size(); i != 0; --i) {
912 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000913 if (!X86::GR64RegClass.contains(Reg) &&
914 !X86::GR32RegClass.contains(Reg))
915 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000916 // Add the callee-saved register as live-in. It's killed at the spill.
917 MBB.addLiveIn(Reg);
918 if (Reg == FPReg)
919 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
920 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000921 CalleeFrameSize += SlotSize;
922 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000923 }
924
925 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000926
927 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
928 // It can be done by spilling XMMs to stack frame.
929 // Note that only Win64 ABI might spill XMMs.
930 for (unsigned i = CSI.size(); i != 0; --i) {
931 unsigned Reg = CSI[i-1].getReg();
932 if (X86::GR64RegClass.contains(Reg) ||
933 X86::GR32RegClass.contains(Reg))
934 continue;
935 // Add the callee-saved register as live-in. It's killed at the spill.
936 MBB.addLiveIn(Reg);
937 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
938 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
939 RC, TRI);
940 }
941
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000942 return true;
943}
944
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000945bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000946 MachineBasicBlock::iterator MI,
947 const std::vector<CalleeSavedInfo> &CSI,
948 const TargetRegisterInfo *TRI) const {
949 if (CSI.empty())
950 return false;
951
952 DebugLoc DL = MBB.findDebugLoc(MI);
953
954 MachineFunction &MF = *MBB.getParent();
955 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000956
957 // Reload XMMs from stack frame.
958 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
959 unsigned Reg = CSI[i].getReg();
960 if (X86::GR64RegClass.contains(Reg) ||
961 X86::GR32RegClass.contains(Reg))
962 continue;
963 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
964 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
965 RC, TRI);
966 }
967
968 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000969 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000970 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
971 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
972 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000973 if (!X86::GR64RegClass.contains(Reg) &&
974 !X86::GR32RegClass.contains(Reg))
975 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000976 if (Reg == FPReg)
977 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
978 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000979 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000980 }
981 return true;
982}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +0000983
984void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000985X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +0000986 RegScavenger *RS) const {
987 MachineFrameInfo *MFI = MF.getFrameInfo();
988 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
989 unsigned SlotSize = RegInfo->getSlotSize();
990
991 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
992 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
993
994 if (TailCallReturnAddrDelta < 0) {
995 // create RETURNADDR area
996 // arg
997 // arg
998 // RETADDR
999 // { ...
1000 // RETADDR area
1001 // ...
1002 // }
1003 // [EBP]
1004 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1005 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1006 }
1007
1008 if (hasFP(MF)) {
1009 assert((TailCallReturnAddrDelta <= 0) &&
1010 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001011 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001012
1013 // Create a frame entry for the EBP register that must be saved.
1014 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1015 -(int)SlotSize +
1016 TFI.getOffsetOfLocalArea() +
1017 TailCallReturnAddrDelta,
1018 true);
1019 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1020 "Slot for EBP register must be last in order to be found!");
1021 FrameIdx = 0;
1022 }
1023}