blob: 7933593e64944da4500371e81968be629d593058 [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;
Bill Wendling09b02c82011-07-25 18:00:28 +0000762 SmallVector<int, 8> SavedRegs;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000763
764 while (MBBI != MBB.end() &&
765 (MBBI->getOpcode() == X86::PUSH32r ||
766 MBBI->getOpcode() == X86::PUSH64r)) {
767 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000768 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000769 ++MBBI;
770
771 if (!HasFP && needsFrameMoves) {
772 // Mark callee-saved push instruction.
773 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
774 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
775
776 // Define the current CFA rule to use the provided offset.
Bill Wendling09b02c82011-07-25 18:00:28 +0000777 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000778 MachineLocation SPDst(Ptr);
779 MachineLocation SPSrc(Ptr, StackOffset);
780 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
781 StackOffset += stackGrowth;
782 }
783 }
784
785 DL = MBB.findDebugLoc(MBBI);
786
787 // If there is an SUB32ri of ESP immediately before this instruction, merge
788 // the two. This can be the case when tail call elimination is enabled and
789 // the callee has more arguments then the caller.
790 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
791
792 // If there is an ADD32ri or SUB32ri of ESP immediately after this
793 // instruction, merge the two instructions.
794 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
795
796 // Adjust stack pointer: ESP -= numbytes.
797
798 // Windows and cygwin/mingw require a prologue helper routine when allocating
799 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
800 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
801 // stack and adjust the stack pointer in one go. The 64-bit version of
802 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
803 // responsible for adjusting the stack pointer. Touching the stack at 4K
804 // increments is necessary to ensure that the guard pages used by the OS
805 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000806 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
807 const char *StackProbeSymbol;
808 bool isSPUpdateNeeded = false;
809
810 if (Is64Bit) {
811 if (STI.isTargetCygMing())
812 StackProbeSymbol = "___chkstk";
813 else {
814 StackProbeSymbol = "__chkstk";
815 isSPUpdateNeeded = true;
816 }
817 } else if (STI.isTargetCygMing())
818 StackProbeSymbol = "_alloca";
819 else
820 StackProbeSymbol = "_chkstk";
821
Anton Korobeynikov33464912010-11-15 00:06:54 +0000822 // Check whether EAX is livein for this function.
823 bool isEAXAlive = isEAXLiveIn(MF);
824
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000825 if (isEAXAlive) {
826 // Sanity check that EAX is not livein for this function.
827 // It should not be, so throw an assert.
828 assert(!Is64Bit && "EAX is livein in x64 case!");
829
Anton Korobeynikov33464912010-11-15 00:06:54 +0000830 // Save EAX
831 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000832 .addReg(X86::EAX, RegState::Kill)
833 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000834 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000835
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000836 if (Is64Bit) {
837 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
838 // Function prologue is responsible for adjusting the stack pointer.
839 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000840 .addImm(NumBytes)
841 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000842 } else {
843 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
844 // We'll also use 4 already allocated bytes for EAX.
845 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000846 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
847 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000848 }
849
850 BuildMI(MBB, MBBI, DL,
851 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
852 .addExternalSymbol(StackProbeSymbol)
853 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000854 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
855 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000856
857 // MSVC x64's __chkstk needs to adjust %rsp.
858 // FIXME: %rax preserves the offset and should be available.
859 if (isSPUpdateNeeded)
860 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
861 TII, *RegInfo);
862
863 if (isEAXAlive) {
864 // Restore EAX
865 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
866 X86::EAX),
867 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000868 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000869 MBB.insert(MBBI, MI);
870 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000871 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000872 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
873 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000874
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000875 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000876 // Mark end of stack pointer adjustment.
877 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000878 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
879 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000880
881 if (!HasFP && NumBytes) {
882 // Define the current CFA rule to use the provided offset.
883 if (StackSize) {
884 MachineLocation SPDst(MachineLocation::VirtualFP);
885 MachineLocation SPSrc(MachineLocation::VirtualFP,
886 -StackSize + stackGrowth);
887 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
888 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000889 MachineLocation SPDst(StackPtr);
890 MachineLocation SPSrc(StackPtr, stackGrowth);
891 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
892 }
893 }
894
895 // Emit DWARF info specifying the offsets of the callee-saved registers.
896 if (PushedRegs)
897 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
898 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000899
900 // Darwin 10.7 and greater has support for compact unwind encoding.
901 if (false && // FIXME: Enable once linker support is available.
902 STI.isTargetDarwin() && !STI.getTargetTriple().isMacOSXVersionLT(10, 6))
903 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
Anton Korobeynikov33464912010-11-15 00:06:54 +0000904}
905
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000906void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000907 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000908 const MachineFrameInfo *MFI = MF.getFrameInfo();
909 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000910 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
911 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000912 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
913 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000914 unsigned RetOpcode = MBBI->getOpcode();
915 DebugLoc DL = MBBI->getDebugLoc();
916 bool Is64Bit = STI.is64Bit();
917 unsigned StackAlign = getStackAlignment();
918 unsigned SlotSize = RegInfo->getSlotSize();
919 unsigned FramePtr = RegInfo->getFrameRegister(MF);
920 unsigned StackPtr = RegInfo->getStackRegister();
921
922 switch (RetOpcode) {
923 default:
924 llvm_unreachable("Can only insert epilog into returning blocks");
925 case X86::RET:
926 case X86::RETI:
927 case X86::TCRETURNdi:
928 case X86::TCRETURNri:
929 case X86::TCRETURNmi:
930 case X86::TCRETURNdi64:
931 case X86::TCRETURNri64:
932 case X86::TCRETURNmi64:
933 case X86::EH_RETURN:
934 case X86::EH_RETURN64:
935 break; // These are ok
936 }
937
938 // Get the number of bytes to allocate from the FrameInfo.
939 uint64_t StackSize = MFI->getStackSize();
940 uint64_t MaxAlign = MFI->getMaxAlignment();
941 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
942 uint64_t NumBytes = 0;
943
944 // If we're forcing a stack realignment we can't rely on just the frame
945 // info, we need to know the ABI stack alignment as well in case we
946 // have a call out. Otherwise just make sure we have some alignment - we'll
947 // go with the minimum.
948 if (ForceStackAlign) {
949 if (MFI->hasCalls())
950 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
951 else
952 MaxAlign = MaxAlign ? MaxAlign : 4;
953 }
954
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000955 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000956 // Calculate required stack adjustment.
957 uint64_t FrameSize = StackSize - SlotSize;
958 if (RegInfo->needsStackRealignment(MF))
959 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
960
961 NumBytes = FrameSize - CSSize;
962
963 // Pop EBP.
964 BuildMI(MBB, MBBI, DL,
965 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
966 } else {
967 NumBytes = StackSize - CSSize;
968 }
969
970 // Skip the callee-saved pop instructions.
971 MachineBasicBlock::iterator LastCSPop = MBBI;
972 while (MBBI != MBB.begin()) {
973 MachineBasicBlock::iterator PI = prior(MBBI);
974 unsigned Opc = PI->getOpcode();
975
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000976 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000977 !PI->getDesc().isTerminator())
978 break;
979
980 --MBBI;
981 }
982
983 DL = MBBI->getDebugLoc();
984
985 // If there is an ADD32ri or SUB32ri of ESP immediately before this
986 // instruction, merge the two instructions.
987 if (NumBytes || MFI->hasVarSizedObjects())
988 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
989
990 // If dynamic alloca is used, then reset esp to point to the last callee-saved
991 // slot before popping them off! Same applies for the case, when stack was
992 // realigned.
993 if (RegInfo->needsStackRealignment(MF)) {
994 // We cannot use LEA here, because stack pointer was realigned. We need to
995 // deallocate local frame back.
996 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +0000997 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000998 MBBI = prior(LastCSPop);
999 }
1000
1001 BuildMI(MBB, MBBI, DL,
1002 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1003 StackPtr).addReg(FramePtr);
1004 } else if (MFI->hasVarSizedObjects()) {
1005 if (CSSize) {
1006 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1007 MachineInstr *MI =
1008 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1009 FramePtr, false, -CSSize);
1010 MBB.insert(MBBI, MI);
1011 } else {
1012 BuildMI(MBB, MBBI, DL,
1013 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1014 .addReg(FramePtr);
1015 }
1016 } else if (NumBytes) {
1017 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +00001018 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001019 }
1020
1021 // We're returning from function via eh_return.
1022 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001023 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001024 MachineOperand &DestAddr = MBBI->getOperand(0);
1025 assert(DestAddr.isReg() && "Offset should be in register!");
1026 BuildMI(MBB, MBBI, DL,
1027 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1028 StackPtr).addReg(DestAddr.getReg());
1029 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1030 RetOpcode == X86::TCRETURNmi ||
1031 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1032 RetOpcode == X86::TCRETURNmi64) {
1033 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1034 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +00001035 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001036 MachineOperand &JumpTarget = MBBI->getOperand(0);
1037 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1038 assert(StackAdjust.isImm() && "Expecting immediate value.");
1039
1040 // Adjust stack pointer.
1041 int StackAdj = StackAdjust.getImm();
1042 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1043 int Offset = 0;
1044 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1045
1046 // Incoporate the retaddr area.
1047 Offset = StackAdj-MaxTCDelta;
1048 assert(Offset >= 0 && "Offset should never be negative");
1049
1050 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001051 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001052 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001053 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001054 }
1055
1056 // Jump to label or value in register.
1057 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +00001058 MachineInstrBuilder MIB =
1059 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1060 ? X86::TAILJMPd : X86::TAILJMPd64));
1061 if (JumpTarget.isGlobal())
1062 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1063 JumpTarget.getTargetFlags());
1064 else {
1065 assert(JumpTarget.isSymbol());
1066 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1067 JumpTarget.getTargetFlags());
1068 }
Anton Korobeynikov33464912010-11-15 00:06:54 +00001069 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1070 MachineInstrBuilder MIB =
1071 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1072 ? X86::TAILJMPm : X86::TAILJMPm64));
1073 for (unsigned i = 0; i != 5; ++i)
1074 MIB.addOperand(MBBI->getOperand(i));
1075 } else if (RetOpcode == X86::TCRETURNri64) {
1076 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1077 addReg(JumpTarget.getReg(), RegState::Kill);
1078 } else {
1079 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1080 addReg(JumpTarget.getReg(), RegState::Kill);
1081 }
1082
1083 MachineInstr *NewMI = prior(MBBI);
1084 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1085 NewMI->addOperand(MBBI->getOperand(i));
1086
1087 // Delete the pseudo instruction TCRETURN.
1088 MBB.erase(MBBI);
1089 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1090 (X86FI->getTCReturnAddrDelta() < 0)) {
1091 // Add the return addr area delta back since we are not tail calling.
1092 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001093 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001094
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001095 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001096 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001097 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001098 }
1099}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +00001100
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001101int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001102 const X86RegisterInfo *RI =
1103 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1104 const MachineFrameInfo *MFI = MF.getFrameInfo();
1105 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1106 uint64_t StackSize = MFI->getStackSize();
1107
1108 if (RI->needsStackRealignment(MF)) {
1109 if (FI < 0) {
1110 // Skip the saved EBP.
1111 Offset += RI->getSlotSize();
1112 } else {
1113 unsigned Align = MFI->getObjectAlignment(FI);
1114 assert((-(Offset + StackSize)) % Align == 0);
1115 Align = 0;
1116 return Offset + StackSize;
1117 }
1118 // FIXME: Support tail calls
1119 } else {
1120 if (!hasFP(MF))
1121 return Offset + StackSize;
1122
1123 // Skip the saved EBP.
1124 Offset += RI->getSlotSize();
1125
1126 // Skip the RETADDR move area
1127 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1128 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1129 if (TailCallReturnAddrDelta < 0)
1130 Offset -= TailCallReturnAddrDelta;
1131 }
1132
1133 return Offset;
1134}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001135
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001136bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001137 MachineBasicBlock::iterator MI,
1138 const std::vector<CalleeSavedInfo> &CSI,
1139 const TargetRegisterInfo *TRI) const {
1140 if (CSI.empty())
1141 return false;
1142
1143 DebugLoc DL = MBB.findDebugLoc(MI);
1144
1145 MachineFunction &MF = *MBB.getParent();
1146
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001147 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1148 unsigned FPReg = TRI->getFrameRegister(MF);
1149 unsigned CalleeFrameSize = 0;
1150
1151 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1152 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1153
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001154 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001155 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1156 for (unsigned i = CSI.size(); i != 0; --i) {
1157 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001158 if (!X86::GR64RegClass.contains(Reg) &&
1159 !X86::GR32RegClass.contains(Reg))
1160 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001161 // Add the callee-saved register as live-in. It's killed at the spill.
1162 MBB.addLiveIn(Reg);
1163 if (Reg == FPReg)
1164 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1165 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001166 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +00001167 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1168 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001169 }
1170
1171 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001172
1173 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1174 // It can be done by spilling XMMs to stack frame.
1175 // Note that only Win64 ABI might spill XMMs.
1176 for (unsigned i = CSI.size(); i != 0; --i) {
1177 unsigned Reg = CSI[i-1].getReg();
1178 if (X86::GR64RegClass.contains(Reg) ||
1179 X86::GR32RegClass.contains(Reg))
1180 continue;
1181 // Add the callee-saved register as live-in. It's killed at the spill.
1182 MBB.addLiveIn(Reg);
1183 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1184 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1185 RC, TRI);
1186 }
1187
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001188 return true;
1189}
1190
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001191bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001192 MachineBasicBlock::iterator MI,
1193 const std::vector<CalleeSavedInfo> &CSI,
1194 const TargetRegisterInfo *TRI) const {
1195 if (CSI.empty())
1196 return false;
1197
1198 DebugLoc DL = MBB.findDebugLoc(MI);
1199
1200 MachineFunction &MF = *MBB.getParent();
1201 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001202
1203 // Reload XMMs from stack frame.
1204 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1205 unsigned Reg = CSI[i].getReg();
1206 if (X86::GR64RegClass.contains(Reg) ||
1207 X86::GR32RegClass.contains(Reg))
1208 continue;
1209 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1210 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1211 RC, TRI);
1212 }
1213
1214 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001215 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001216 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1217 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1218 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001219 if (!X86::GR64RegClass.contains(Reg) &&
1220 !X86::GR32RegClass.contains(Reg))
1221 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001222 if (Reg == FPReg)
1223 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1224 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001225 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001226 }
1227 return true;
1228}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001229
1230void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001231X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001232 RegScavenger *RS) const {
1233 MachineFrameInfo *MFI = MF.getFrameInfo();
1234 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1235 unsigned SlotSize = RegInfo->getSlotSize();
1236
1237 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1238 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1239
1240 if (TailCallReturnAddrDelta < 0) {
1241 // create RETURNADDR area
1242 // arg
1243 // arg
1244 // RETADDR
1245 // { ...
1246 // RETADDR area
1247 // ...
1248 // }
1249 // [EBP]
1250 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1251 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1252 }
1253
1254 if (hasFP(MF)) {
1255 assert((TailCallReturnAddrDelta <= 0) &&
1256 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001257 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001258
1259 // Create a frame entry for the EBP register that must be saved.
1260 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1261 -(int)SlotSize +
1262 TFI.getOffsetOfLocalArea() +
1263 TailCallReturnAddrDelta,
1264 true);
1265 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1266 "Slot for EBP register must be last in order to be found!");
1267 FrameIdx = 0;
1268 }
1269}