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