blob: 189c80d5f22d26851befcaa480442d44ef00f252 [file] [log] [blame]
Nick Lewycky3c2f0a12011-06-14 03:23:52 +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"
Bill Wendling6a6b8c32011-07-07 00:54:13 +000026#include "llvm/MC/MCSymbol.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetOptions.h"
29#include "llvm/Support/CommandLine.h"
Evan Cheng7158e082011-01-03 22:53:22 +000030#include "llvm/ADT/SmallSet.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000031
32using namespace llvm;
33
34// FIXME: completely move here.
35extern cl::opt<bool> ForceStackAlign;
36
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000037bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000038 return !MF.getFrameInfo()->hasVarSizedObjects();
39}
40
41/// hasFP - Return true if the specified function should have a dedicated frame
42/// pointer register. This is true if the function has variable sized allocas
43/// or if frame pointer elimination is disabled.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000044bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000045 const MachineFrameInfo *MFI = MF.getFrameInfo();
46 const MachineModuleInfo &MMI = MF.getMMI();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000047 const TargetRegisterInfo *RI = TM.getRegisterInfo();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000048
49 return (DisableFramePointerElim(MF) ||
50 RI->needsStackRealignment(MF) ||
51 MFI->hasVarSizedObjects() ||
52 MFI->isFrameAddressTaken() ||
53 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
54 MMI.callsUnwindInit());
55}
56
Anton Korobeynikov33464912010-11-15 00:06:54 +000057static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
58 if (is64Bit) {
59 if (isInt<8>(Imm))
60 return X86::SUB64ri8;
61 return X86::SUB64ri32;
62 } else {
63 if (isInt<8>(Imm))
64 return X86::SUB32ri8;
65 return X86::SUB32ri;
66 }
67}
68
69static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
70 if (is64Bit) {
71 if (isInt<8>(Imm))
72 return X86::ADD64ri8;
73 return X86::ADD64ri32;
74 } else {
75 if (isInt<8>(Imm))
76 return X86::ADD32ri8;
77 return X86::ADD32ri;
78 }
79}
80
Evan Cheng7158e082011-01-03 22:53:22 +000081/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
82/// when it reaches the "return" instruction. We can then pop a stack object
83/// to this register without worry about clobbering it.
84static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
85 MachineBasicBlock::iterator &MBBI,
86 const TargetRegisterInfo &TRI,
87 bool Is64Bit) {
88 const MachineFunction *MF = MBB.getParent();
89 const Function *F = MF->getFunction();
90 if (!F || MF->getMMI().callsEHReturn())
91 return 0;
92
93 static const unsigned CallerSavedRegs32Bit[] = {
94 X86::EAX, X86::EDX, X86::ECX
95 };
96
97 static const unsigned CallerSavedRegs64Bit[] = {
98 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
99 X86::R8, X86::R9, X86::R10, X86::R11
100 };
101
102 unsigned Opc = MBBI->getOpcode();
103 switch (Opc) {
104 default: return 0;
105 case X86::RET:
106 case X86::RETI:
107 case X86::TCRETURNdi:
108 case X86::TCRETURNri:
109 case X86::TCRETURNmi:
110 case X86::TCRETURNdi64:
111 case X86::TCRETURNri64:
112 case X86::TCRETURNmi64:
113 case X86::EH_RETURN:
114 case X86::EH_RETURN64: {
115 SmallSet<unsigned, 8> Uses;
116 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
117 MachineOperand &MO = MBBI->getOperand(i);
118 if (!MO.isReg() || MO.isDef())
119 continue;
120 unsigned Reg = MO.getReg();
121 if (!Reg)
122 continue;
123 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
124 Uses.insert(*AsI);
125 }
126
127 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
128 for (; *CS; ++CS)
129 if (!Uses.count(*CS))
130 return *CS;
131 }
132 }
133
134 return 0;
135}
136
137
Anton Korobeynikov33464912010-11-15 00:06:54 +0000138/// emitSPUpdate - Emit a series of instructions to increment / decrement the
139/// stack pointer by a constant value.
140static
141void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng7158e082011-01-03 22:53:22 +0000142 unsigned StackPtr, int64_t NumBytes,
143 bool Is64Bit, const TargetInstrInfo &TII,
144 const TargetRegisterInfo &TRI) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000145 bool isSub = NumBytes < 0;
146 uint64_t Offset = isSub ? -NumBytes : NumBytes;
147 unsigned Opc = isSub ?
148 getSUBriOpcode(Is64Bit, Offset) :
149 getADDriOpcode(Is64Bit, Offset);
150 uint64_t Chunk = (1LL << 31) - 1;
151 DebugLoc DL = MBB.findDebugLoc(MBBI);
152
153 while (Offset) {
154 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng7158e082011-01-03 22:53:22 +0000155 if (ThisVal == (Is64Bit ? 8 : 4)) {
156 // Use push / pop instead.
157 unsigned Reg = isSub
Dale Johannesen1e08cd12011-01-04 19:31:24 +0000158 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng7158e082011-01-03 22:53:22 +0000159 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
160 if (Reg) {
161 Opc = isSub
162 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
163 : (Is64Bit ? X86::POP64r : X86::POP32r);
Charles Davisaff232a2011-06-12 01:45:54 +0000164 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
Evan Cheng7158e082011-01-03 22:53:22 +0000165 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
Charles Davisaff232a2011-06-12 01:45:54 +0000166 if (isSub)
167 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng7158e082011-01-03 22:53:22 +0000168 Offset -= ThisVal;
169 continue;
170 }
171 }
172
Anton Korobeynikov33464912010-11-15 00:06:54 +0000173 MachineInstr *MI =
174 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Evan Cheng7158e082011-01-03 22:53:22 +0000175 .addReg(StackPtr)
176 .addImm(ThisVal);
Charles Davisaff232a2011-06-12 01:45:54 +0000177 if (isSub)
178 MI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000179 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
180 Offset -= ThisVal;
181 }
182}
183
184/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
185static
186void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
187 unsigned StackPtr, uint64_t *NumBytes = NULL) {
188 if (MBBI == MBB.begin()) return;
189
190 MachineBasicBlock::iterator PI = prior(MBBI);
191 unsigned Opc = PI->getOpcode();
192 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
193 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
194 PI->getOperand(0).getReg() == StackPtr) {
195 if (NumBytes)
196 *NumBytes += PI->getOperand(2).getImm();
197 MBB.erase(PI);
198 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
199 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
200 PI->getOperand(0).getReg() == StackPtr) {
201 if (NumBytes)
202 *NumBytes -= PI->getOperand(2).getImm();
203 MBB.erase(PI);
204 }
205}
206
207/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
208static
209void mergeSPUpdatesDown(MachineBasicBlock &MBB,
210 MachineBasicBlock::iterator &MBBI,
211 unsigned StackPtr, uint64_t *NumBytes = NULL) {
212 // FIXME: THIS ISN'T RUN!!!
213 return;
214
215 if (MBBI == MBB.end()) return;
216
217 MachineBasicBlock::iterator NI = llvm::next(MBBI);
218 if (NI == MBB.end()) return;
219
220 unsigned Opc = NI->getOpcode();
221 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
222 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
223 NI->getOperand(0).getReg() == StackPtr) {
224 if (NumBytes)
225 *NumBytes -= NI->getOperand(2).getImm();
226 MBB.erase(NI);
227 MBBI = NI;
228 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
229 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
230 NI->getOperand(0).getReg() == StackPtr) {
231 if (NumBytes)
232 *NumBytes += NI->getOperand(2).getImm();
233 MBB.erase(NI);
234 MBBI = NI;
235 }
236}
237
238/// mergeSPUpdates - Checks the instruction before/after the passed
239/// instruction. If it is an ADD/SUB instruction it is deleted argument and the
240/// stack adjustment is returned as a positive value for ADD and a negative for
241/// SUB.
242static int mergeSPUpdates(MachineBasicBlock &MBB,
243 MachineBasicBlock::iterator &MBBI,
244 unsigned StackPtr,
245 bool doMergeWithPrevious) {
246 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
247 (!doMergeWithPrevious && MBBI == MBB.end()))
248 return 0;
249
250 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
251 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
252 unsigned Opc = PI->getOpcode();
253 int Offset = 0;
254
255 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
256 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
257 PI->getOperand(0).getReg() == StackPtr){
258 Offset += PI->getOperand(2).getImm();
259 MBB.erase(PI);
260 if (!doMergeWithPrevious) MBBI = NI;
261 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
262 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
263 PI->getOperand(0).getReg() == StackPtr) {
264 Offset -= PI->getOperand(2).getImm();
265 MBB.erase(PI);
266 if (!doMergeWithPrevious) MBBI = NI;
267 }
268
269 return Offset;
270}
271
272static bool isEAXLiveIn(MachineFunction &MF) {
273 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
274 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
275 unsigned Reg = II->first;
276
277 if (Reg == X86::EAX || Reg == X86::AX ||
278 Reg == X86::AH || Reg == X86::AL)
279 return true;
280 }
281
282 return false;
283}
284
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000285void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
Bill Wendling09b02c82011-07-25 18:00:28 +0000286 MCSymbol *Label,
287 unsigned FramePtr) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000288 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000289 MachineModuleInfo &MMI = MF.getMMI();
290
291 // Add callee saved registers to move list.
292 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
293 if (CSI.empty()) return;
294
295 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000296 const TargetData *TD = TM.getTargetData();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000297 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000298
299 // Calculate amount of bytes used for return address storing.
Anton Korobeynikove7499112011-01-14 21:57:58 +0000300 int stackGrowth = -TD->getPointerSize();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000301
302 // FIXME: This is dirty hack. The code itself is pretty mess right now.
303 // It should be rewritten from scratch and generalized sometimes.
304
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000305 // Determine maximum offset (minimum due to stack growth).
Anton Korobeynikov33464912010-11-15 00:06:54 +0000306 int64_t MaxOffset = 0;
307 for (std::vector<CalleeSavedInfo>::const_iterator
308 I = CSI.begin(), E = CSI.end(); I != E; ++I)
309 MaxOffset = std::min(MaxOffset,
310 MFI->getObjectOffset(I->getFrameIdx()));
311
312 // Calculate offsets.
313 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
314 for (std::vector<CalleeSavedInfo>::const_iterator
315 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
316 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
317 unsigned Reg = I->getReg();
318 Offset = MaxOffset - Offset + saveAreaOffset;
319
320 // Don't output a new machine move if we're re-saving the frame
321 // pointer. This happens when the PrologEpilogInserter has inserted an extra
322 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
323 // generates one when frame pointers are used. If we generate a "machine
324 // move" for this extra "PUSH", the linker will lose track of the fact that
325 // the frame pointer should have the value of the first "PUSH" when it's
326 // trying to unwind.
NAKAMURA Takumi27635382011-02-05 15:10:54 +0000327 //
Anton Korobeynikov33464912010-11-15 00:06:54 +0000328 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
329 // another bug. I.e., one where we generate a prolog like this:
330 //
331 // pushl %ebp
332 // movl %esp, %ebp
333 // pushl %ebp
334 // pushl %esi
335 // ...
336 //
337 // The immediate re-push of EBP is unnecessary. At the least, it's an
338 // optimization bug. EBP can be used as a scratch register in certain
339 // cases, but probably not when we have a frame pointer.
340 if (HasFP && FramePtr == Reg)
341 continue;
342
343 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
344 MachineLocation CSSrc(Reg);
345 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
346 }
347}
348
Bill Wendling09b02c82011-07-25 18:00:28 +0000349/// getCompactUnwindRegNum - Get the compact unwind number for a given
350/// register. The number corresponds to the enum lists in
351/// compact_unwind_encoding.h.
352static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
353 int Idx = 1;
354 for (; *CURegs; ++CURegs, ++Idx)
355 if (*CURegs == Reg)
356 return Idx;
357
358 return -1;
359}
360
361/// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
362/// used with frameless stacks. It is passed the number of registers to be saved
363/// and an array of the registers saved.
364static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[6],
365 unsigned RegCount,
366 bool Is64Bit) {
367 // The saved registers are numbered from 1 to 6. In order to encode the order
368 // in which they were saved, we re-number them according to their place in the
369 // register order. The re-numbering is relative to the last re-numbered
370 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
371 //
372 // Orig Re-Num
373 // ---- ------
374 // 6 6
375 // 2 2
376 // 4 3
377 // 5 3
378 //
379 static const unsigned CU32BitRegs[] = {
380 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
381 };
382 static const unsigned CU64BitRegs[] = {
383 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
384 };
385 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
386
387 uint32_t RenumRegs[6];
388 for (unsigned i = 6 - RegCount; i < 6; ++i) {
389 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
390 if (CUReg == -1) return ~0U;
391 SavedRegs[i] = CUReg;
392
393 unsigned Countless = 0;
394 for (unsigned j = 6 - RegCount; j < i; ++j)
395 if (SavedRegs[j] < SavedRegs[i])
396 ++Countless;
397
398 RenumRegs[i] = SavedRegs[i] - Countless - 1;
399 }
400
401 // Take the renumbered values and encode them into a 10-bit number.
402 uint32_t permutationEncoding = 0;
403 switch (RegCount) {
404 case 6:
405 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
406 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
407 + RenumRegs[4];
408 break;
409 case 5:
410 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
411 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
412 + RenumRegs[5];
413 break;
414 case 4:
415 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
416 + 3 * RenumRegs[4] + RenumRegs[5];
417 break;
418 case 3:
419 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
420 + RenumRegs[5];
421 break;
422 case 2:
423 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
424 break;
425 case 1:
426 permutationEncoding |= RenumRegs[5];
427 break;
428 }
429
430 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
431 "Invalid compact register encoding!");
432 return permutationEncoding;
433}
434
435/// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
436/// compact encoding with a frame pointer.
437static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6],
438 bool Is64Bit) {
439 static const unsigned CU32BitRegs[] = {
440 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
441 };
442 static const unsigned CU64BitRegs[] = {
443 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
444 };
445 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
446
447 // Encode the registers in the order they were saved, 3-bits per register. The
448 // registers are numbered from 1 to 6.
449 uint32_t RegEnc = 0;
450 for (int I = 5; I >= 0; --I) {
451 unsigned Reg = SavedRegs[I];
452 if (Reg == 0) break;
453 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
454 if (CURegNum == -1)
455 return ~0U;
456 RegEnc |= (CURegNum & 0x7) << (5 - I);
457 }
458
459 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
460 return RegEnc;
461}
462
463uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
464 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
465 unsigned FramePtr = RegInfo->getFrameRegister(MF);
466 unsigned StackPtr = RegInfo->getStackRegister();
467
468 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
469 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
470
471 bool Is64Bit = STI.is64Bit();
472 bool HasFP = hasFP(MF);
473
474 unsigned SavedRegs[6] = { 0, 0, 0, 0, 0, 0 };
475 int SavedRegIdx = 6;
476
477 unsigned OffsetSize = (Is64Bit ? 8 : 4);
478
479 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
480 unsigned PushInstrSize = 1;
481 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
482 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
483 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
484 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
485
486 unsigned InstrOffset = 0;
487 unsigned CFAOffset = 0;
488 unsigned StackAdjust = 0;
489
490 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
491 bool ExpectEnd = false;
492 for (MachineBasicBlock::iterator
493 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
494 MachineInstr &MI = *MBBI;
495 unsigned Opc = MI.getOpcode();
496 if (Opc == X86::PROLOG_LABEL) continue;
497 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
498
499 // We don't exect any more prolog instructions.
500 if (ExpectEnd) return 0;
501
502 if (Opc == PushInstr) {
503 // If there are too many saved registers, we cannot use compact encoding.
504 if (--SavedRegIdx < 0) return 0;
505
506 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
507 CFAOffset += OffsetSize;
508 InstrOffset += PushInstrSize;
509 } else if (Opc == MoveInstr) {
510 unsigned SrcReg = MI.getOperand(1).getReg();
511 unsigned DstReg = MI.getOperand(0).getReg();
512
513 if (DstReg != FramePtr || SrcReg != StackPtr)
514 return 0;
515
516 CFAOffset = 0;
517 memset(SavedRegs, 0, sizeof(SavedRegs));
518 InstrOffset += MoveInstrSize;
519 } else if (Opc == SubtractInstr) {
520 if (StackAdjust)
521 // We all ready have a stack pointer adjustment.
522 return 0;
523
524 if (!MI.getOperand(0).isReg() ||
525 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
526 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
527 // We need this to be a stack adjustment pointer. Something like:
528 //
529 // %RSP<def> = SUB64ri8 %RSP, 48
530 return 0;
531
532 StackAdjust = MI.getOperand(2).getImm() / 4;
533 SubtractInstrIdx += InstrOffset;
534 ExpectEnd = true;
535 }
536 }
537
538 // Encode that we are using EBP/RBP as the frame pointer.
539 uint32_t CompactUnwindEncoding = 0;
540 CFAOffset /= 4;
541 if (HasFP) {
542 if ((CFAOffset & 0xFF) != CFAOffset)
543 // Offset was too big for compact encoding.
544 return 0;
545
546 // Get the encoding of the saved registers when we have a frame pointer.
547 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
548 if (RegEnc == ~0U)
549 return 0;
550
551 CompactUnwindEncoding |= 0x01000000;
552 CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
553 CompactUnwindEncoding |= RegEnc & 0x7FFF;
554 } else {
555 unsigned FullOffset = CFAOffset + StackAdjust;
556 if ((FullOffset & 0xFF) == FullOffset) {
557 // Frameless stack.
558 CompactUnwindEncoding |= 0x02000000;
559 CompactUnwindEncoding |= (FullOffset & 0xFF) << 16;
560 } else {
561 if ((CFAOffset & 0x7) != CFAOffset)
562 // The extra stack adjustments are too big for us to handle.
563 return 0;
564
565 // Frameless stack with an offset too large for us to encode compactly.
566 CompactUnwindEncoding |= 0x03000000;
567
568 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
569 // instruction.
570 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
571
572 // Encode any extra stack stack changes (done via push instructions).
573 CompactUnwindEncoding |= (CFAOffset & 0x7) << 13;
574 }
575
576 // Get the encoding of the saved registers when we don't have a frame
577 // pointer.
578 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
579 6 - SavedRegIdx,
580 Is64Bit);
581 if (RegEnc == ~0U) return 0;
582 CompactUnwindEncoding |= RegEnc & 0x3FF;
583 }
584
585 return CompactUnwindEncoding;
586}
587
Anton Korobeynikov33464912010-11-15 00:06:54 +0000588/// emitPrologue - Push callee-saved registers onto the stack, which
589/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
590/// space for local variables. Also emit labels used by the exception handler to
591/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000592void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000593 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
594 MachineBasicBlock::iterator MBBI = MBB.begin();
595 MachineFrameInfo *MFI = MF.getFrameInfo();
596 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000597 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
598 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000599 MachineModuleInfo &MMI = MF.getMMI();
600 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
601 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000602 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000603 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
604 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000605 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000606 bool Is64Bit = STI.is64Bit();
607 bool IsWin64 = STI.isTargetWin64();
608 unsigned StackAlign = getStackAlignment();
609 unsigned SlotSize = RegInfo->getSlotSize();
610 unsigned FramePtr = RegInfo->getFrameRegister(MF);
611 unsigned StackPtr = RegInfo->getStackRegister();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000612 DebugLoc DL;
613
614 // If we're forcing a stack realignment we can't rely on just the frame
615 // info, we need to know the ABI stack alignment as well in case we
616 // have a call out. Otherwise just make sure we have some alignment - we'll
617 // go with the minimum SlotSize.
618 if (ForceStackAlign) {
619 if (MFI->hasCalls())
620 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
621 else if (MaxAlign < SlotSize)
622 MaxAlign = SlotSize;
623 }
624
625 // Add RETADDR move area to callee saved frame size.
626 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
627 if (TailCallReturnAddrDelta < 0)
628 X86FI->setCalleeSavedFrameSize(
629 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
630
631 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
632 // function, and use up to 128 bytes of stack space, don't have a frame
633 // pointer, calls, or dynamic alloca then we do not need to adjust the
634 // stack pointer (we fit in the Red Zone).
635 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
636 !RegInfo->needsStackRealignment(MF) &&
637 !MFI->hasVarSizedObjects() && // No dynamic alloca.
638 !MFI->adjustsStack() && // No calls.
639 !IsWin64) { // Win64 has no Red Zone
640 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
641 if (HasFP) MinSize += SlotSize;
642 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
643 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000644 }
645
646 // Insert stack pointer adjustment for later moving of return addr. Only
647 // applies to tail call optimized functions where the callee argument stack
648 // size is bigger than the callers.
649 if (TailCallReturnAddrDelta < 0) {
650 MachineInstr *MI =
651 BuildMI(MBB, MBBI, DL,
652 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
653 StackPtr)
654 .addReg(StackPtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000655 .addImm(-TailCallReturnAddrDelta)
656 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000657 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
658 }
659
660 // Mapping for machine moves:
661 //
662 // DST: VirtualFP AND
663 // SRC: VirtualFP => DW_CFA_def_cfa_offset
664 // ELSE => DW_CFA_def_cfa
665 //
666 // SRC: VirtualFP AND
667 // DST: Register => DW_CFA_def_cfa_register
668 //
669 // ELSE
670 // OFFSET < 0 => DW_CFA_offset_extended_sf
671 // REG < 64 => DW_CFA_offset + Reg
672 // ELSE => DW_CFA_offset_extended
673
674 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
675 const TargetData *TD = MF.getTarget().getTargetData();
676 uint64_t NumBytes = 0;
677 int stackGrowth = -TD->getPointerSize();
678
679 if (HasFP) {
680 // Calculate required stack adjustment.
681 uint64_t FrameSize = StackSize - SlotSize;
682 if (RegInfo->needsStackRealignment(MF))
683 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
684
685 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
686
687 // Get the offset of the stack slot for the EBP register, which is
688 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
689 // Update the frame offset adjustment.
690 MFI->setOffsetAdjustment(-NumBytes);
691
692 // Save EBP/RBP into the appropriate stack slot.
693 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davisaff232a2011-06-12 01:45:54 +0000694 .addReg(FramePtr, RegState::Kill)
695 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000696
697 if (needsFrameMoves) {
698 // Mark the place where EBP/RBP was saved.
699 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000700 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
701 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000702
703 // Define the current CFA rule to use the provided offset.
704 if (StackSize) {
705 MachineLocation SPDst(MachineLocation::VirtualFP);
706 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
707 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
708 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000709 MachineLocation SPDst(StackPtr);
710 MachineLocation SPSrc(StackPtr, stackGrowth);
711 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
712 }
713
714 // Change the rule for the FramePtr to be an "offset" rule.
715 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
716 MachineLocation FPSrc(FramePtr);
717 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
718 }
719
Bill Wendling09b02c82011-07-25 18:00:28 +0000720 // Update EBP with the new base value.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000721 BuildMI(MBB, MBBI, DL,
722 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000723 .addReg(StackPtr)
724 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000725
726 if (needsFrameMoves) {
727 // Mark effective beginning of when frame pointer becomes valid.
728 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000729 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
730 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000731
732 // Define the current CFA to use the EBP/RBP register.
733 MachineLocation FPDst(FramePtr);
734 MachineLocation FPSrc(MachineLocation::VirtualFP);
735 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
736 }
737
738 // Mark the FramePtr as live-in in every block except the entry.
739 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
740 I != E; ++I)
741 I->addLiveIn(FramePtr);
742
743 // Realign stack
744 if (RegInfo->needsStackRealignment(MF)) {
745 MachineInstr *MI =
746 BuildMI(MBB, MBBI, DL,
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000747 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
748 .addReg(StackPtr)
749 .addImm(-MaxAlign)
750 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000751
752 // The EFLAGS implicit def is dead.
753 MI->getOperand(3).setIsDead();
754 }
755 } else {
756 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
757 }
758
759 // Skip the callee-saved push instructions.
760 bool PushedRegs = false;
761 int StackOffset = 2 * stackGrowth;
762
763 while (MBBI != MBB.end() &&
764 (MBBI->getOpcode() == X86::PUSH32r ||
765 MBBI->getOpcode() == X86::PUSH64r)) {
766 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000767 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000768 ++MBBI;
769
770 if (!HasFP && needsFrameMoves) {
771 // Mark callee-saved push instruction.
772 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
773 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
774
775 // Define the current CFA rule to use the provided offset.
Bill Wendling09b02c82011-07-25 18:00:28 +0000776 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000777 MachineLocation SPDst(Ptr);
778 MachineLocation SPSrc(Ptr, StackOffset);
779 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
780 StackOffset += stackGrowth;
781 }
782 }
783
784 DL = MBB.findDebugLoc(MBBI);
785
786 // If there is an SUB32ri of ESP immediately before this instruction, merge
787 // the two. This can be the case when tail call elimination is enabled and
788 // the callee has more arguments then the caller.
789 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
790
791 // If there is an ADD32ri or SUB32ri of ESP immediately after this
792 // instruction, merge the two instructions.
793 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
794
795 // Adjust stack pointer: ESP -= numbytes.
796
797 // Windows and cygwin/mingw require a prologue helper routine when allocating
798 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
799 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
800 // stack and adjust the stack pointer in one go. The 64-bit version of
801 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
802 // responsible for adjusting the stack pointer. Touching the stack at 4K
803 // increments is necessary to ensure that the guard pages used by the OS
804 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000805 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
806 const char *StackProbeSymbol;
807 bool isSPUpdateNeeded = false;
808
809 if (Is64Bit) {
810 if (STI.isTargetCygMing())
811 StackProbeSymbol = "___chkstk";
812 else {
813 StackProbeSymbol = "__chkstk";
814 isSPUpdateNeeded = true;
815 }
816 } else if (STI.isTargetCygMing())
817 StackProbeSymbol = "_alloca";
818 else
819 StackProbeSymbol = "_chkstk";
820
Anton Korobeynikov33464912010-11-15 00:06:54 +0000821 // Check whether EAX is livein for this function.
822 bool isEAXAlive = isEAXLiveIn(MF);
823
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000824 if (isEAXAlive) {
825 // Sanity check that EAX is not livein for this function.
826 // It should not be, so throw an assert.
827 assert(!Is64Bit && "EAX is livein in x64 case!");
828
Anton Korobeynikov33464912010-11-15 00:06:54 +0000829 // Save EAX
830 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000831 .addReg(X86::EAX, RegState::Kill)
832 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000833 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000834
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000835 if (Is64Bit) {
836 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
837 // Function prologue is responsible for adjusting the stack pointer.
838 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000839 .addImm(NumBytes)
840 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000841 } else {
842 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
843 // We'll also use 4 already allocated bytes for EAX.
844 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000845 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
846 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000847 }
848
849 BuildMI(MBB, MBBI, DL,
850 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
851 .addExternalSymbol(StackProbeSymbol)
852 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000853 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
854 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000855
856 // MSVC x64's __chkstk needs to adjust %rsp.
857 // FIXME: %rax preserves the offset and should be available.
858 if (isSPUpdateNeeded)
859 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
860 TII, *RegInfo);
861
862 if (isEAXAlive) {
863 // Restore EAX
864 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
865 X86::EAX),
866 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000867 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000868 MBB.insert(MBBI, MI);
869 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000870 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000871 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
872 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000873
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000874 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000875 // Mark end of stack pointer adjustment.
876 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000877 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
878 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000879
880 if (!HasFP && NumBytes) {
881 // Define the current CFA rule to use the provided offset.
882 if (StackSize) {
883 MachineLocation SPDst(MachineLocation::VirtualFP);
884 MachineLocation SPSrc(MachineLocation::VirtualFP,
885 -StackSize + stackGrowth);
886 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
887 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000888 MachineLocation SPDst(StackPtr);
889 MachineLocation SPSrc(StackPtr, stackGrowth);
890 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
891 }
892 }
893
894 // Emit DWARF info specifying the offsets of the callee-saved registers.
895 if (PushedRegs)
896 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
897 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000898
899 // Darwin 10.7 and greater has support for compact unwind encoding.
900 if (false && // FIXME: Enable once linker support is available.
901 STI.isTargetDarwin() && !STI.getTargetTriple().isMacOSXVersionLT(10, 6))
902 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
Anton Korobeynikov33464912010-11-15 00:06:54 +0000903}
904
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000905void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000906 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000907 const MachineFrameInfo *MFI = MF.getFrameInfo();
908 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000909 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
910 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000911 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
912 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000913 unsigned RetOpcode = MBBI->getOpcode();
914 DebugLoc DL = MBBI->getDebugLoc();
915 bool Is64Bit = STI.is64Bit();
916 unsigned StackAlign = getStackAlignment();
917 unsigned SlotSize = RegInfo->getSlotSize();
918 unsigned FramePtr = RegInfo->getFrameRegister(MF);
919 unsigned StackPtr = RegInfo->getStackRegister();
920
921 switch (RetOpcode) {
922 default:
923 llvm_unreachable("Can only insert epilog into returning blocks");
924 case X86::RET:
925 case X86::RETI:
926 case X86::TCRETURNdi:
927 case X86::TCRETURNri:
928 case X86::TCRETURNmi:
929 case X86::TCRETURNdi64:
930 case X86::TCRETURNri64:
931 case X86::TCRETURNmi64:
932 case X86::EH_RETURN:
933 case X86::EH_RETURN64:
934 break; // These are ok
935 }
936
937 // Get the number of bytes to allocate from the FrameInfo.
938 uint64_t StackSize = MFI->getStackSize();
939 uint64_t MaxAlign = MFI->getMaxAlignment();
940 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
941 uint64_t NumBytes = 0;
942
943 // If we're forcing a stack realignment we can't rely on just the frame
944 // info, we need to know the ABI stack alignment as well in case we
945 // have a call out. Otherwise just make sure we have some alignment - we'll
946 // go with the minimum.
947 if (ForceStackAlign) {
948 if (MFI->hasCalls())
949 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
950 else
951 MaxAlign = MaxAlign ? MaxAlign : 4;
952 }
953
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000954 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000955 // Calculate required stack adjustment.
956 uint64_t FrameSize = StackSize - SlotSize;
957 if (RegInfo->needsStackRealignment(MF))
958 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
959
960 NumBytes = FrameSize - CSSize;
961
962 // Pop EBP.
963 BuildMI(MBB, MBBI, DL,
964 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
965 } else {
966 NumBytes = StackSize - CSSize;
967 }
968
969 // Skip the callee-saved pop instructions.
970 MachineBasicBlock::iterator LastCSPop = MBBI;
971 while (MBBI != MBB.begin()) {
972 MachineBasicBlock::iterator PI = prior(MBBI);
973 unsigned Opc = PI->getOpcode();
974
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000975 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000976 !PI->getDesc().isTerminator())
977 break;
978
979 --MBBI;
980 }
981
982 DL = MBBI->getDebugLoc();
983
984 // If there is an ADD32ri or SUB32ri of ESP immediately before this
985 // instruction, merge the two instructions.
986 if (NumBytes || MFI->hasVarSizedObjects())
987 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
988
989 // If dynamic alloca is used, then reset esp to point to the last callee-saved
990 // slot before popping them off! Same applies for the case, when stack was
991 // realigned.
992 if (RegInfo->needsStackRealignment(MF)) {
993 // We cannot use LEA here, because stack pointer was realigned. We need to
994 // deallocate local frame back.
995 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +0000996 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000997 MBBI = prior(LastCSPop);
998 }
999
1000 BuildMI(MBB, MBBI, DL,
1001 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1002 StackPtr).addReg(FramePtr);
1003 } else if (MFI->hasVarSizedObjects()) {
1004 if (CSSize) {
1005 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1006 MachineInstr *MI =
1007 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1008 FramePtr, false, -CSSize);
1009 MBB.insert(MBBI, MI);
1010 } else {
1011 BuildMI(MBB, MBBI, DL,
1012 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1013 .addReg(FramePtr);
1014 }
1015 } else if (NumBytes) {
1016 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +00001017 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001018 }
1019
1020 // We're returning from function via eh_return.
1021 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001022 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001023 MachineOperand &DestAddr = MBBI->getOperand(0);
1024 assert(DestAddr.isReg() && "Offset should be in register!");
1025 BuildMI(MBB, MBBI, DL,
1026 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1027 StackPtr).addReg(DestAddr.getReg());
1028 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1029 RetOpcode == X86::TCRETURNmi ||
1030 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1031 RetOpcode == X86::TCRETURNmi64) {
1032 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1033 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +00001034 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001035 MachineOperand &JumpTarget = MBBI->getOperand(0);
1036 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1037 assert(StackAdjust.isImm() && "Expecting immediate value.");
1038
1039 // Adjust stack pointer.
1040 int StackAdj = StackAdjust.getImm();
1041 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1042 int Offset = 0;
1043 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1044
1045 // Incoporate the retaddr area.
1046 Offset = StackAdj-MaxTCDelta;
1047 assert(Offset >= 0 && "Offset should never be negative");
1048
1049 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001050 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001051 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001052 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001053 }
1054
1055 // Jump to label or value in register.
1056 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +00001057 MachineInstrBuilder MIB =
1058 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1059 ? X86::TAILJMPd : X86::TAILJMPd64));
1060 if (JumpTarget.isGlobal())
1061 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1062 JumpTarget.getTargetFlags());
1063 else {
1064 assert(JumpTarget.isSymbol());
1065 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1066 JumpTarget.getTargetFlags());
1067 }
Anton Korobeynikov33464912010-11-15 00:06:54 +00001068 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1069 MachineInstrBuilder MIB =
1070 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1071 ? X86::TAILJMPm : X86::TAILJMPm64));
1072 for (unsigned i = 0; i != 5; ++i)
1073 MIB.addOperand(MBBI->getOperand(i));
1074 } else if (RetOpcode == X86::TCRETURNri64) {
1075 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1076 addReg(JumpTarget.getReg(), RegState::Kill);
1077 } else {
1078 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1079 addReg(JumpTarget.getReg(), RegState::Kill);
1080 }
1081
1082 MachineInstr *NewMI = prior(MBBI);
1083 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1084 NewMI->addOperand(MBBI->getOperand(i));
1085
1086 // Delete the pseudo instruction TCRETURN.
1087 MBB.erase(MBBI);
1088 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1089 (X86FI->getTCReturnAddrDelta() < 0)) {
1090 // Add the return addr area delta back since we are not tail calling.
1091 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001092 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001093
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001094 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001095 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001096 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001097 }
1098}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +00001099
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001100int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001101 const X86RegisterInfo *RI =
1102 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1103 const MachineFrameInfo *MFI = MF.getFrameInfo();
1104 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1105 uint64_t StackSize = MFI->getStackSize();
1106
1107 if (RI->needsStackRealignment(MF)) {
1108 if (FI < 0) {
1109 // Skip the saved EBP.
1110 Offset += RI->getSlotSize();
1111 } else {
1112 unsigned Align = MFI->getObjectAlignment(FI);
1113 assert((-(Offset + StackSize)) % Align == 0);
1114 Align = 0;
1115 return Offset + StackSize;
1116 }
1117 // FIXME: Support tail calls
1118 } else {
1119 if (!hasFP(MF))
1120 return Offset + StackSize;
1121
1122 // Skip the saved EBP.
1123 Offset += RI->getSlotSize();
1124
1125 // Skip the RETADDR move area
1126 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1127 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1128 if (TailCallReturnAddrDelta < 0)
1129 Offset -= TailCallReturnAddrDelta;
1130 }
1131
1132 return Offset;
1133}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001134
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001135bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001136 MachineBasicBlock::iterator MI,
1137 const std::vector<CalleeSavedInfo> &CSI,
1138 const TargetRegisterInfo *TRI) const {
1139 if (CSI.empty())
1140 return false;
1141
1142 DebugLoc DL = MBB.findDebugLoc(MI);
1143
1144 MachineFunction &MF = *MBB.getParent();
1145
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001146 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1147 unsigned FPReg = TRI->getFrameRegister(MF);
1148 unsigned CalleeFrameSize = 0;
1149
1150 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1151 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1152
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001153 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001154 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1155 for (unsigned i = CSI.size(); i != 0; --i) {
1156 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001157 if (!X86::GR64RegClass.contains(Reg) &&
1158 !X86::GR32RegClass.contains(Reg))
1159 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001160 // Add the callee-saved register as live-in. It's killed at the spill.
1161 MBB.addLiveIn(Reg);
1162 if (Reg == FPReg)
1163 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1164 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001165 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +00001166 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1167 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001168 }
1169
1170 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001171
1172 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1173 // It can be done by spilling XMMs to stack frame.
1174 // Note that only Win64 ABI might spill XMMs.
1175 for (unsigned i = CSI.size(); i != 0; --i) {
1176 unsigned Reg = CSI[i-1].getReg();
1177 if (X86::GR64RegClass.contains(Reg) ||
1178 X86::GR32RegClass.contains(Reg))
1179 continue;
1180 // Add the callee-saved register as live-in. It's killed at the spill.
1181 MBB.addLiveIn(Reg);
1182 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1183 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1184 RC, TRI);
1185 }
1186
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001187 return true;
1188}
1189
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001190bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001191 MachineBasicBlock::iterator MI,
1192 const std::vector<CalleeSavedInfo> &CSI,
1193 const TargetRegisterInfo *TRI) const {
1194 if (CSI.empty())
1195 return false;
1196
1197 DebugLoc DL = MBB.findDebugLoc(MI);
1198
1199 MachineFunction &MF = *MBB.getParent();
1200 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001201
1202 // Reload XMMs from stack frame.
1203 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1204 unsigned Reg = CSI[i].getReg();
1205 if (X86::GR64RegClass.contains(Reg) ||
1206 X86::GR32RegClass.contains(Reg))
1207 continue;
1208 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1209 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1210 RC, TRI);
1211 }
1212
1213 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001214 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001215 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1216 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1217 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001218 if (!X86::GR64RegClass.contains(Reg) &&
1219 !X86::GR32RegClass.contains(Reg))
1220 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001221 if (Reg == FPReg)
1222 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1223 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001224 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001225 }
1226 return true;
1227}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001228
1229void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001230X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001231 RegScavenger *RS) const {
1232 MachineFrameInfo *MFI = MF.getFrameInfo();
1233 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1234 unsigned SlotSize = RegInfo->getSlotSize();
1235
1236 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1237 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1238
1239 if (TailCallReturnAddrDelta < 0) {
1240 // create RETURNADDR area
1241 // arg
1242 // arg
1243 // RETADDR
1244 // { ...
1245 // RETADDR area
1246 // ...
1247 // }
1248 // [EBP]
1249 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1250 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1251 }
1252
1253 if (hasFP(MF)) {
1254 assert((TailCallReturnAddrDelta <= 0) &&
1255 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001256 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001257
1258 // Create a frame entry for the EBP register that must be saved.
1259 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1260 -(int)SlotSize +
1261 TFI.getOffsetOfLocalArea() +
1262 TailCallReturnAddrDelta,
1263 true);
1264 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1265 "Slot for EBP register must be last in order to be found!");
1266 FrameIdx = 0;
1267 }
1268}