LLVM 24.0.0git
PPCFrameLowering.cpp
Go to the documentation of this file.
1//===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the PPC implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "PPCFrameLowering.h"
15#include "PPCInstrBuilder.h"
16#include "PPCInstrInfo.h"
18#include "PPCSubtarget.h"
19#include "PPCTargetMachine.h"
20#include "llvm/ADT/Statistic.h"
28#include "llvm/IR/Function.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "framelowering"
34STATISTIC(NumPESpillVSR, "Number of spills to vector in prologue");
35STATISTIC(NumPEReloadVSR, "Number of reloads from vector in epilogue");
36STATISTIC(NumPrologProbed, "Number of prologues probed");
37
38static cl::opt<bool>
39EnablePEVectorSpills("ppc-enable-pe-vector-spills",
40 cl::desc("Enable spills in prologue to vector registers."),
41 cl::init(false), cl::Hidden);
42
43static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
44 if (STI.isAIXABI())
45 return STI.isPPC64() ? 16 : 8;
46 // SVR4 ABI:
47 return STI.isPPC64() ? 16 : 4;
48}
49
50static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
51 if (STI.isAIXABI())
52 return STI.isPPC64() ? 40 : 20;
53 return STI.isELFv2ABI() ? 24 : 40;
54}
55
56static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
57 // First slot in the general register save area.
58 return STI.isPPC64() ? -8U : -4U;
59}
60
61static unsigned computeLinkageSize(const PPCSubtarget &STI) {
62 if (STI.isAIXABI() || STI.isPPC64())
63 return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
64
65 // 32-bit SVR4 ABI:
66 return 8;
67}
68
69static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {
70 // Third slot in the general purpose register save area.
72 return -12U;
73
74 // Second slot in the general purpose register save area.
75 return STI.isPPC64() ? -16U : -8U;
76}
77
78static unsigned computeCRSaveOffset(const PPCSubtarget &STI) {
79 return (STI.isAIXABI() && !STI.isPPC64()) ? 4 : 8;
80}
81
84 STI.getPlatformStackAlignment(), 0),
85 Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
86 TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
87 FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
88 LinkageSize(computeLinkageSize(Subtarget)),
89 BasePointerSaveOffset(computeBasePointerSaveOffset(Subtarget)),
90 CRSaveOffset(computeCRSaveOffset(Subtarget)) {}
91
92// With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
94 unsigned &NumEntries) const {
95
96// Floating-point register save area offsets.
97#define CALLEE_SAVED_FPRS \
98 {PPC::F31, -8}, \
99 {PPC::F30, -16}, \
100 {PPC::F29, -24}, \
101 {PPC::F28, -32}, \
102 {PPC::F27, -40}, \
103 {PPC::F26, -48}, \
104 {PPC::F25, -56}, \
105 {PPC::F24, -64}, \
106 {PPC::F23, -72}, \
107 {PPC::F22, -80}, \
108 {PPC::F21, -88}, \
109 {PPC::F20, -96}, \
110 {PPC::F19, -104}, \
111 {PPC::F18, -112}, \
112 {PPC::F17, -120}, \
113 {PPC::F16, -128}, \
114 {PPC::F15, -136}, \
115 {PPC::F14, -144}
116
117// 32-bit general purpose register save area offsets shared by ELF and
118// AIX. AIX has an extra CSR with r13.
119#define CALLEE_SAVED_GPRS32 \
120 {PPC::R31, -4}, \
121 {PPC::R30, -8}, \
122 {PPC::R29, -12}, \
123 {PPC::R28, -16}, \
124 {PPC::R27, -20}, \
125 {PPC::R26, -24}, \
126 {PPC::R25, -28}, \
127 {PPC::R24, -32}, \
128 {PPC::R23, -36}, \
129 {PPC::R22, -40}, \
130 {PPC::R21, -44}, \
131 {PPC::R20, -48}, \
132 {PPC::R19, -52}, \
133 {PPC::R18, -56}, \
134 {PPC::R17, -60}, \
135 {PPC::R16, -64}, \
136 {PPC::R15, -68}, \
137 {PPC::R14, -72}
138
139// 64-bit general purpose register save area offsets.
140#define CALLEE_SAVED_GPRS64 \
141 {PPC::X31, -8}, \
142 {PPC::X30, -16}, \
143 {PPC::X29, -24}, \
144 {PPC::X28, -32}, \
145 {PPC::X27, -40}, \
146 {PPC::X26, -48}, \
147 {PPC::X25, -56}, \
148 {PPC::X24, -64}, \
149 {PPC::X23, -72}, \
150 {PPC::X22, -80}, \
151 {PPC::X21, -88}, \
152 {PPC::X20, -96}, \
153 {PPC::X19, -104}, \
154 {PPC::X18, -112}, \
155 {PPC::X17, -120}, \
156 {PPC::X16, -128}, \
157 {PPC::X15, -136}, \
158 {PPC::X14, -144}
159
160// Vector register save area offsets.
161#define CALLEE_SAVED_VRS \
162 {PPC::V31, -16}, \
163 {PPC::V30, -32}, \
164 {PPC::V29, -48}, \
165 {PPC::V28, -64}, \
166 {PPC::V27, -80}, \
167 {PPC::V26, -96}, \
168 {PPC::V25, -112}, \
169 {PPC::V24, -128}, \
170 {PPC::V23, -144}, \
171 {PPC::V22, -160}, \
172 {PPC::V21, -176}, \
173 {PPC::V20, -192}
174
175 // Note that the offsets here overlap, but this is fixed up in
176 // processFunctionBeforeFrameFinalized.
177
178 static const SpillSlot ELFOffsets32[] = {
181
182 // CR save area offset. We map each of the nonvolatile CR fields
183 // to the slot for CR2, which is the first of the nonvolatile CR
184 // fields to be assigned, so that we only allocate one save slot.
185 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
186 {PPC::CR2, -4},
187
188 // VRSAVE save area offset.
189 {PPC::VRSAVE, -4},
190
192
193 // SPE register save area (overlaps Vector save area).
194 {PPC::S31, -8},
195 {PPC::S30, -16},
196 {PPC::S29, -24},
197 {PPC::S28, -32},
198 {PPC::S27, -40},
199 {PPC::S26, -48},
200 {PPC::S25, -56},
201 {PPC::S24, -64},
202 {PPC::S23, -72},
203 {PPC::S22, -80},
204 {PPC::S21, -88},
205 {PPC::S20, -96},
206 {PPC::S19, -104},
207 {PPC::S18, -112},
208 {PPC::S17, -120},
209 {PPC::S16, -128},
210 {PPC::S15, -136},
211 {PPC::S14, -144}};
212
213 static const SpillSlot ELFOffsets64[] = {
216
217 // VRSAVE save area offset.
218 {PPC::VRSAVE, -4},
220 };
221
222 static const SpillSlot AIXOffsets32[] = {CALLEE_SAVED_FPRS,
224 // Add AIX's extra CSR.
225 {PPC::R13, -76},
227
228 static const SpillSlot AIXOffsets64[] = {
230
231 if (Subtarget.is64BitELFABI()) {
232 NumEntries = std::size(ELFOffsets64);
233 return ELFOffsets64;
234 }
235
236 if (Subtarget.is32BitELFABI()) {
237 NumEntries = std::size(ELFOffsets32);
238 return ELFOffsets32;
239 }
240
241 assert(Subtarget.isAIXABI() && "Unexpected ABI.");
242
243 if (Subtarget.isPPC64()) {
244 NumEntries = std::size(AIXOffsets64);
245 return AIXOffsets64;
246 }
247
248 NumEntries = std::size(AIXOffsets32);
249 return AIXOffsets32;
250}
251
252static bool spillsCR(const MachineFunction &MF) {
253 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
254 return FuncInfo->isCRSpilled();
255}
256
257static bool hasSpills(const MachineFunction &MF) {
258 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
259 return FuncInfo->hasSpills();
260}
261
262static bool hasNonRISpills(const MachineFunction &MF) {
263 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
264 return FuncInfo->hasNonRISpills();
265}
266
267/// MustSaveLR - Return true if this function requires that we save the LR
268/// register onto the stack in the prolog and restore it in the epilog of the
269/// function.
270static bool MustSaveLR(const MachineFunction &MF, MCRegister LR) {
271 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
272
273 // We need a save/restore of LR if there is any def of LR (which is
274 // defined by calls, including the PIC setup sequence), or if there is
275 // some use of the LR stack slot (e.g. for builtin_return_address).
276 // (LR comes in 32 and 64 bit versions.)
278 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
279}
280
281/// determineFrameLayoutAndUpdate - Determine the size of the frame and maximum
282/// call frame size. Update the MachineFunction object with the stack size.
285 bool UseEstimate) const {
286 unsigned NewMaxCallFrameSize = 0;
287 uint64_t FrameSize = determineFrameLayout(MF, UseEstimate,
288 &NewMaxCallFrameSize);
289 MF.getFrameInfo().setStackSize(FrameSize);
290 MF.getFrameInfo().setMaxCallFrameSize(NewMaxCallFrameSize);
291 return FrameSize;
292}
293
294/// determineFrameLayout - Determine the size of the frame and maximum call
295/// frame size.
296uint64_t
298 bool UseEstimate,
299 unsigned *NewMaxCallFrameSize) const {
300 const MachineFrameInfo &MFI = MF.getFrameInfo();
301 const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
302
303 // Get the number of bytes to allocate from the FrameInfo
304 uint64_t FrameSize =
305 UseEstimate ? MFI.estimateStackSize(MF) : MFI.getStackSize();
306
307 // Get stack alignments. The frame must be aligned to the greatest of these:
308 Align TargetAlign = getStackAlign(); // alignment required per the ABI
309 Align MaxAlign = MFI.getMaxAlign(); // algmt required by data in frame
310 Align Alignment = std::max(TargetAlign, MaxAlign);
311
312 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
313
314 MCRegister LR = RegInfo->getRARegister();
315 bool DisableRedZone = MF.getFunction().hasFnAttribute(Attribute::NoRedZone);
316 bool CanUseRedZone = !MFI.hasVarSizedObjects() && // No dynamic alloca.
317 !MFI.adjustsStack() && // No calls.
318 !MustSaveLR(MF, LR) && // No need to save LR.
319 !FI->mustSaveTOC() && // No need to save TOC.
320 !RegInfo->hasBasePointer(MF) && // No special alignment.
321 !MFI.isFrameAddressTaken();
322
323 // Note: for PPC32 SVR4ABI, we can still generate stackless
324 // code if all local vars are reg-allocated.
325 bool FitsInRedZone = FrameSize <= Subtarget.getRedZoneSize();
326
327 // Check whether we can skip adjusting the stack pointer (by using red zone)
328 if (!DisableRedZone && CanUseRedZone && FitsInRedZone) {
329 // No need for frame
330 return 0;
331 }
332
333 // Get the maximum call frame size of all the calls.
334 unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
335
336 // Maximum call frame needs to be at least big enough for linkage area.
337 unsigned minCallFrameSize = getLinkageSize();
338 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
339
340 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
341 // that allocations will be aligned.
342 if (MFI.hasVarSizedObjects())
343 maxCallFrameSize = alignTo(maxCallFrameSize, Alignment);
344
345 // Update the new max call frame size if the caller passes in a valid pointer.
346 if (NewMaxCallFrameSize)
347 *NewMaxCallFrameSize = maxCallFrameSize;
348
349 // Include call frame size in total.
350 FrameSize += maxCallFrameSize;
351
352 // Make sure the frame is aligned.
353 FrameSize = alignTo(FrameSize, Alignment);
354
355 return FrameSize;
356}
357
358// hasFPImpl - Return true if the specified function actually has a dedicated
359// frame pointer register.
361 const MachineFrameInfo &MFI = MF.getFrameInfo();
362 // FIXME: This is pretty much broken by design: hasFP() might be called really
363 // early, before the stack layout was calculated and thus hasFP() might return
364 // true or false here depending on the time of call.
365 return (MFI.getStackSize()) && needsFP(MF);
366}
367
368// needsFP - Return true if the specified function should have a dedicated frame
369// pointer register. This is true if the function has variable sized allocas or
370// if frame pointer elimination is disabled.
372 const MachineFrameInfo &MFI = MF.getFrameInfo();
373
374 // Naked functions have no stack frame pushed, so we don't have a frame
375 // pointer.
376 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
377 return false;
378
379 return MF.disableFramePointerElim() || MFI.hasVarSizedObjects() ||
380 MFI.hasStackMap() || MFI.hasPatchPoint() || MF.exposesReturnsTwice() ||
381 (MF.getTarget().Options.GuaranteedTailCallOpt &&
383}
384
386 // When there is dynamic alloca in this function, we can not use the frame
387 // pointer X31/R31 for the frameaddress lowering. In this case, only X1/R1
388 // always points to the backchain.
389 bool is31 = needsFP(MF) && !MF.getFrameInfo().hasVarSizedObjects();
390 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
391 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
392
393 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
394 bool HasBP = RegInfo->hasBasePointer(MF);
395 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
396 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FP8Reg;
397
398 for (MachineBasicBlock &MBB : MF)
399 for (MachineBasicBlock::iterator MBBI = MBB.end(); MBBI != MBB.begin();) {
400 --MBBI;
401 for (MachineOperand &MO : MBBI->operands()) {
402 if (!MO.isReg())
403 continue;
404
405 switch (MO.getReg()) {
406 case PPC::FP:
407 MO.setReg(FPReg);
408 break;
409 case PPC::FP8:
410 MO.setReg(FP8Reg);
411 break;
412 case PPC::BP:
413 MO.setReg(BPReg);
414 break;
415 case PPC::BP8:
416 MO.setReg(BP8Reg);
417 break;
418
419 }
420 }
421 }
422}
423
424/* This function will do the following:
425 - If MBB is an entry or exit block, set SR1 and SR2 to R0 and R12
426 respectively (defaults recommended by the ABI) and return true
427 - If MBB is not an entry block, initialize the register scavenger and look
428 for available registers.
429 - If the defaults (R0/R12) are available, return true
430 - If TwoUniqueRegsRequired is set to true, it looks for two unique
431 registers. Otherwise, look for a single available register.
432 - If the required registers are found, set SR1 and SR2 and return true.
433 - If the required registers are not found, set SR2 or both SR1 and SR2 to
434 PPC::NoRegister and return false.
435
436 Note that if both SR1 and SR2 are valid parameters and TwoUniqueRegsRequired
437 is not set, this function will attempt to find two different registers, but
438 still return true if only one register is available (and set SR1 == SR2).
439*/
440bool
441PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,
442 bool UseAtEnd,
443 bool TwoUniqueRegsRequired,
444 Register *SR1,
445 Register *SR2) const {
446 RegScavenger RS;
447 Register R0 = Subtarget.isPPC64() ? PPC::X0 : PPC::R0;
448 Register R12 = Subtarget.isPPC64() ? PPC::X12 : PPC::R12;
449
450 // Set the defaults for the two scratch registers.
451 if (SR1)
452 *SR1 = R0;
453
454 if (SR2) {
455 assert (SR1 && "Asking for the second scratch register but not the first?");
456 *SR2 = R12;
457 }
458
459 // If MBB is an entry or exit block, use R0 and R12 as the scratch registers.
460 if ((UseAtEnd && MBB->isReturnBlock()) ||
461 (!UseAtEnd && (&MBB->getParent()->front() == MBB)))
462 return true;
463
464 if (UseAtEnd) {
465 // The scratch register will be used before the first terminator (or at the
466 // end of the block if there are no terminators).
467 MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();
468 if (MBBI == MBB->begin()) {
469 RS.enterBasicBlock(*MBB);
470 } else {
471 RS.enterBasicBlockEnd(*MBB);
472 RS.backward(MBBI);
473 }
474 } else {
475 // The scratch register will be used at the start of the block.
476 RS.enterBasicBlock(*MBB);
477 }
478
479 // If the two registers are available, we're all good.
480 // Note that we only return here if both R0 and R12 are available because
481 // although the function may not require two unique registers, it may benefit
482 // from having two so we should try to provide them.
483 if (!RS.isRegUsed(R0) && !RS.isRegUsed(R12))
484 return true;
485
486 // Get the list of callee-saved registers for the target.
487 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
488 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MBB->getParent());
489
490 // Get all the available registers in the block.
491 BitVector BV = RS.getRegsAvailable(Subtarget.isPPC64() ? &PPC::G8RCRegClass :
492 &PPC::GPRCRegClass);
493
494 // We shouldn't use callee-saved registers as scratch registers as they may be
495 // available when looking for a candidate block for shrink wrapping but not
496 // available when the actual prologue/epilogue is being emitted because they
497 // were added as live-in to the prologue block by PrologueEpilogueInserter.
498 for (int i = 0; CSRegs[i]; ++i)
499 BV.reset(CSRegs[i]);
500
501 // Set the first scratch register to the first available one.
502 if (SR1) {
503 int FirstScratchReg = BV.find_first();
504 *SR1 = FirstScratchReg == -1 ? (unsigned)PPC::NoRegister : FirstScratchReg;
505 }
506
507 // If there is another one available, set the second scratch register to that.
508 // Otherwise, set it to either PPC::NoRegister if this function requires two
509 // or to whatever SR1 is set to if this function doesn't require two.
510 if (SR2) {
511 int SecondScratchReg = BV.find_next(*SR1);
512 if (SecondScratchReg != -1)
513 *SR2 = SecondScratchReg;
514 else
515 *SR2 = TwoUniqueRegsRequired ? Register() : *SR1;
516 }
517
518 // Now that we've done our best to provide both registers, double check
519 // whether we were unable to provide enough.
520 if (BV.count() < (TwoUniqueRegsRequired ? 2U : 1U))
521 return false;
522
523 return true;
524}
525
526// We need a scratch register for spilling LR and for spilling CR. By default,
527// we use two scratch registers to hide latency. However, if only one scratch
528// register is available, we can adjust for that by not overlapping the spill
529// code. However, if we need to realign the stack (i.e. have a base pointer)
530// and the stack frame is large, we need two scratch registers.
531// Also, stack probe requires two scratch registers, one for old sp, one for
532// large frame and large probe size.
533bool
534PPCFrameLowering::twoUniqueScratchRegsRequired(MachineBasicBlock *MBB) const {
535 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
536 MachineFunction &MF = *(MBB->getParent());
537 bool HasBP = RegInfo->hasBasePointer(MF);
538 unsigned FrameSize = determineFrameLayout(MF);
539 int NegFrameSize = -FrameSize;
540 bool IsLargeFrame = !isInt<16>(NegFrameSize);
541 MachineFrameInfo &MFI = MF.getFrameInfo();
542 Align MaxAlign = MFI.getMaxAlign();
543 bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
544 const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
545
546 return ((IsLargeFrame || !HasRedZone) && HasBP && MaxAlign > 1) ||
547 TLI.hasInlineStackProbe(MF);
548}
549
551 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
552
553 return findScratchRegister(TmpMBB, false,
554 twoUniqueScratchRegsRequired(TmpMBB));
555}
556
558 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
559
560 return findScratchRegister(TmpMBB, true);
561}
562
563bool PPCFrameLowering::stackUpdateCanBeMoved(MachineFunction &MF) const {
564 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
566
567 // Abort if there is no register info or function info.
568 if (!RegInfo || !FI)
569 return false;
570
571 // Only move the stack update on ELFv2 ABI and PPC64.
572 if (!Subtarget.isELFv2ABI() || !Subtarget.isPPC64())
573 return false;
574
575 // Check the frame size first and return false if it does not fit the
576 // requirements.
577 // We need a non-zero frame size as well as a frame that will fit in the red
578 // zone. This is because by moving the stack pointer update we are now storing
579 // to the red zone until the stack pointer is updated. If we get an interrupt
580 // inside the prologue but before the stack update we now have a number of
581 // stores to the red zone and those stores must all fit.
582 MachineFrameInfo &MFI = MF.getFrameInfo();
583 unsigned FrameSize = MFI.getStackSize();
584 if (!FrameSize || FrameSize > Subtarget.getRedZoneSize())
585 return false;
586
587 // Frame pointers and base pointers complicate matters so don't do anything
588 // if we have them. For example having a frame pointer will sometimes require
589 // a copy of r1 into r31 and that makes keeping track of updates to r1 more
590 // difficult. Similar situation exists with setjmp.
591 if (hasFP(MF) || RegInfo->hasBasePointer(MF) || MF.exposesReturnsTwice())
592 return false;
593
594 // Calls to fast_cc functions use different rules for passing parameters on
595 // the stack from the ABI and using PIC base in the function imposes
596 // similar restrictions to using the base pointer. It is not generally safe
597 // to move the stack pointer update in these situations.
598 if (FI->hasFastCall() || FI->usesPICBase())
599 return false;
600
601 // Finally we can move the stack update if we do not require register
602 // scavenging. Register scavenging can introduce more spills and so
603 // may make the frame size larger than we have computed.
604 return !RegInfo->requiresFrameIndexScavenging(MF);
605}
606
608 MachineBasicBlock &MBB) const {
610 MachineFrameInfo &MFI = MF.getFrameInfo();
611 const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
612 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
613 const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
614
615 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
616 DebugLoc dl;
617 // AIX assembler does not support cfi directives.
618 const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();
619
620 const bool HasFastMFLR = Subtarget.hasFastMFLR();
621
622 // Get processor type.
623 bool isPPC64 = Subtarget.isPPC64();
624 // Get the ABI.
625 bool isSVR4ABI = Subtarget.isSVR4ABI();
626 bool isELFv2ABI = Subtarget.isELFv2ABI();
627 assert((isSVR4ABI || Subtarget.isAIXABI()) && "Unsupported PPC ABI.");
628
629 // Work out frame sizes.
630 uint64_t FrameSize = determineFrameLayoutAndUpdate(MF);
631 int64_t NegFrameSize = -FrameSize;
632 if (!isPPC64 && (!isInt<32>(FrameSize) || !isInt<32>(NegFrameSize)))
633 llvm_unreachable("Unhandled stack size!");
634
635 if (MFI.isFrameAddressTaken())
637
638 // Check if the link register (LR) must be saved.
640 bool MustSaveLR = FI->mustSaveLR();
641 bool MustSaveTOC = FI->mustSaveTOC();
642 const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
643 bool MustSaveCR = !MustSaveCRs.empty();
644 // Do we have a frame pointer and/or base pointer for this function?
645 bool HasFP = hasFP(MF);
646 bool HasBP = RegInfo->hasBasePointer(MF);
647 bool HasRedZone = isPPC64 || !isSVR4ABI;
648 const bool HasROPProtect = Subtarget.hasROPProtect();
649 bool HasPrivileged = Subtarget.hasPrivileged();
650
651 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
652 Register BPReg = RegInfo->getBaseRegister(MF);
653 Register FPReg = isPPC64 ? PPC::X31 : PPC::R31;
654 Register LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
655 Register TOCReg = isPPC64 ? PPC::X2 : PPC::R2;
656 Register ScratchReg;
657 Register TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
658 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
659 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
660 : PPC::MFLR );
661 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
662 : PPC::STW );
663 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
664 : PPC::STWU );
665 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
666 : PPC::STWUX);
667 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
668 : PPC::OR );
669 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
670 : PPC::SUBFC);
671 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
672 : PPC::SUBFIC);
673 const MCInstrDesc &MoveFromCondRegInst = TII.get(isPPC64 ? PPC::MFCR8
674 : PPC::MFCR);
675 const MCInstrDesc &StoreWordInst = TII.get(isPPC64 ? PPC::STW8 : PPC::STW);
676 const MCInstrDesc &HashST =
677 TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHSTP8 : PPC::HASHST8)
678 : (HasPrivileged ? PPC::HASHSTP : PPC::HASHST));
679
680 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
681 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
682 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
683 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
684 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
685 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
686
687 // Using the same bool variable as below to suppress compiler warnings.
688 bool SingleScratchReg = findScratchRegister(
689 &MBB, false, twoUniqueScratchRegsRequired(&MBB), &ScratchReg, &TempReg);
690 assert(SingleScratchReg &&
691 "Required number of registers not available in this block");
692
693 SingleScratchReg = ScratchReg == TempReg;
694
695 int64_t LROffset = getReturnSaveOffset();
696
697 int64_t FPOffset = 0;
698 if (HasFP) {
699 MachineFrameInfo &MFI = MF.getFrameInfo();
700 int FPIndex = FI->getFramePointerSaveIndex();
701 assert(FPIndex && "No Frame Pointer Save Slot!");
702 FPOffset = MFI.getObjectOffset(FPIndex);
703 }
704
705 int64_t BPOffset = 0;
706 if (HasBP) {
707 MachineFrameInfo &MFI = MF.getFrameInfo();
708 int BPIndex = FI->getBasePointerSaveIndex();
709 assert(BPIndex && "No Base Pointer Save Slot!");
710 BPOffset = MFI.getObjectOffset(BPIndex);
711 }
712
713 int64_t PBPOffset = 0;
714 if (FI->usesPICBase()) {
715 MachineFrameInfo &MFI = MF.getFrameInfo();
716 int PBPIndex = FI->getPICBasePointerSaveIndex();
717 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
718 PBPOffset = MFI.getObjectOffset(PBPIndex);
719 }
720
721 // Get stack alignments.
722 Align MaxAlign = MFI.getMaxAlign();
723 if (HasBP && MaxAlign > 1)
724 assert(Log2(MaxAlign) < 16 && "Invalid alignment!");
725
726 // Frames of 32KB & larger require special handling because they cannot be
727 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
728 bool isLargeFrame = !isInt<16>(NegFrameSize);
729
730 // Check if we can move the stack update instruction (stdu) down the prologue
731 // past the callee saves. Hopefully this will avoid the situation where the
732 // saves are waiting for the update on the store with update to complete.
733 MachineBasicBlock::iterator StackUpdateLoc = MBBI;
734 bool MovingStackUpdateDown = false;
735
736 // Check if we can move the stack update.
737 if (stackUpdateCanBeMoved(MF)) {
738 const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
739 for (CalleeSavedInfo CSI : Info) {
740 // If the callee saved register is spilled to a register instead of the
741 // stack then the spill no longer uses the stack pointer.
742 // This can lead to two consequences:
743 // 1) We no longer need to update the stack because the function does not
744 // spill any callee saved registers to stack.
745 // 2) We have a situation where we still have to update the stack pointer
746 // even though some registers are spilled to other registers. In
747 // this case the current code moves the stack update to an incorrect
748 // position.
749 // In either case we should abort moving the stack update operation.
750 if (CSI.isSpilledToReg()) {
751 StackUpdateLoc = MBBI;
752 MovingStackUpdateDown = false;
753 break;
754 }
755
756 int FrIdx = CSI.getFrameIdx();
757 // If the frame index is not negative the callee saved info belongs to a
758 // stack object that is not a fixed stack object. We ignore non-fixed
759 // stack objects because we won't move the stack update pointer past them.
760 if (FrIdx >= 0)
761 continue;
762
763 if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0) {
764 StackUpdateLoc++;
765 MovingStackUpdateDown = true;
766 } else {
767 // We need all of the Frame Indices to meet these conditions.
768 // If they do not, abort the whole operation.
769 StackUpdateLoc = MBBI;
770 MovingStackUpdateDown = false;
771 break;
772 }
773 }
774
775 // If the operation was not aborted then update the object offset.
776 if (MovingStackUpdateDown) {
777 for (CalleeSavedInfo CSI : Info) {
778 int FrIdx = CSI.getFrameIdx();
779 if (FrIdx < 0)
780 MFI.setObjectOffset(FrIdx, MFI.getObjectOffset(FrIdx) + NegFrameSize);
781 }
782 }
783 }
784
785 // Where in the prologue we move the CR fields depends on how many scratch
786 // registers we have, and if we need to save the link register or not. This
787 // lambda is to avoid duplicating the logic in 2 places.
788 auto BuildMoveFromCR = [&]() {
789 if (isELFv2ABI && MustSaveCRs.size() == 1) {
790 // In the ELFv2 ABI, we are not required to save all CR fields.
791 // If only one CR field is clobbered, it is more efficient to use
792 // mfocrf to selectively save just that field, because mfocrf has short
793 // latency compares to mfcr.
794 assert(isPPC64 && "V2 ABI is 64-bit only.");
796 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFOCRF8), TempReg);
797 MIB.addReg(MustSaveCRs[0], RegState::Kill);
798 } else {
800 BuildMI(MBB, MBBI, dl, MoveFromCondRegInst, TempReg);
801 for (unsigned CRfield : MustSaveCRs)
802 MIB.addReg(CRfield, RegState::ImplicitKill);
803 }
804 };
805
806 // If we need to spill the CR and the LR but we don't have two separate
807 // registers available, we must spill them one at a time
808 if (MustSaveCR && SingleScratchReg && MustSaveLR) {
809 BuildMoveFromCR();
810 BuildMI(MBB, MBBI, dl, StoreWordInst)
811 .addReg(TempReg, getKillRegState(true))
812 .addImm(CRSaveOffset)
813 .addReg(SPReg);
814 }
815
816 if (MustSaveLR)
817 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
818
819 if (MustSaveCR && !(SingleScratchReg && MustSaveLR))
820 BuildMoveFromCR();
821
822 if (HasRedZone) {
823 if (HasFP)
825 .addReg(FPReg)
826 .addImm(FPOffset)
827 .addReg(SPReg);
828 if (FI->usesPICBase())
830 .addReg(PPC::R30)
831 .addImm(PBPOffset)
832 .addReg(SPReg);
833 if (HasBP)
835 .addReg(BPReg)
836 .addImm(BPOffset)
837 .addReg(SPReg);
838 }
839
840 // Generate the instruction to store the LR. In the case where ROP protection
841 // is required the register holding the LR should not be killed as it will be
842 // used by the hash store instruction.
843 auto SaveLR = [&](int64_t Offset) {
844 assert(MustSaveLR && "LR is not required to be saved!");
845 BuildMI(MBB, StackUpdateLoc, dl, StoreInst)
846 .addReg(ScratchReg, getKillRegState(!HasROPProtect))
847 .addImm(Offset)
848 .addReg(SPReg);
849
850 // Add the ROP protection Hash Store instruction.
851 // NOTE: This is technically a violation of the ABI. The hash can be saved
852 // up to 512 bytes into the Protected Zone. This can be outside of the
853 // initial 288 byte volatile program storage region in the Protected Zone.
854 // However, this restriction will be removed in an upcoming revision of the
855 // ABI.
856 if (HasROPProtect) {
857 const int SaveIndex = FI->getROPProtectionHashSaveIndex();
858 const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);
859 assert((ImmOffset <= -8 && ImmOffset >= -512) &&
860 "ROP hash save offset out of range.");
861 assert(((ImmOffset & 0x7) == 0) &&
862 "ROP hash save offset must be 8 byte aligned.");
863 BuildMI(MBB, StackUpdateLoc, dl, HashST)
864 .addReg(ScratchReg, getKillRegState(true))
865 .addImm(ImmOffset)
866 .addReg(SPReg);
867 }
868 };
869
870 if (MustSaveLR && HasFastMFLR)
871 SaveLR(LROffset);
872
873 if (MustSaveCR &&
874 !(SingleScratchReg && MustSaveLR)) {
875 assert(HasRedZone && "A red zone is always available on PPC64");
876 BuildMI(MBB, MBBI, dl, StoreWordInst)
877 .addReg(TempReg, getKillRegState(true))
878 .addImm(CRSaveOffset)
879 .addReg(SPReg);
880 }
881
882 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
883 if (!FrameSize) {
884 if (MustSaveLR && !HasFastMFLR)
885 SaveLR(LROffset);
886 return;
887 }
888
889 // Adjust stack pointer: r1 += NegFrameSize.
890 // If there is a preferred stack alignment, align R1 now
891
892 if (HasBP && HasRedZone) {
893 // Save a copy of r1 as the base pointer.
894 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
895 .addReg(SPReg)
896 .addReg(SPReg);
897 }
898
899 // Have we generated a STUX instruction to claim stack frame? If so,
900 // the negated frame size will be placed in ScratchReg.
901 bool HasSTUX =
902 (TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) ||
903 (HasBP && MaxAlign > 1) || isLargeFrame;
904
905 // If we use STUX to update the stack pointer, we need the two scratch
906 // registers TempReg and ScratchReg, we have to save LR here which is stored
907 // in ScratchReg.
908 // If the offset can not be encoded into the store instruction, we also have
909 // to save LR here.
910 // If we are using ROP Protection we need to save the LR here as we cannot
911 // move the hashst instruction past the point where we get the stack frame.
912 if (MustSaveLR && !HasFastMFLR &&
913 (HasSTUX || !isInt<16>(FrameSize + LROffset) || HasROPProtect))
914 SaveLR(LROffset);
915
916 // If FrameSize <= TLI.getStackProbeSize(MF), as POWER ABI requires backchain
917 // pointer is always stored at SP, we will get a free probe due to an essential
918 // STU(X) instruction.
919 if (TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) {
920 // To be consistent with other targets, a pseudo instruction is emitted and
921 // will be later expanded in `inlineStackProbe`.
922 BuildMI(MBB, MBBI, dl,
923 TII.get(isPPC64 ? PPC::PROBED_STACKALLOC_64
924 : PPC::PROBED_STACKALLOC_32))
925 .addDef(TempReg)
926 .addDef(ScratchReg) // ScratchReg stores the old sp.
927 .addImm(NegFrameSize);
928 // FIXME: HasSTUX is only read if HasRedZone is not set, in such case, we
929 // update the ScratchReg to meet the assumption that ScratchReg contains
930 // the NegFrameSize. This solution is rather tricky.
931 if (!HasRedZone) {
932 BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
933 .addReg(ScratchReg)
934 .addReg(SPReg);
935 }
936 } else {
937 // This condition must be kept in sync with canUseAsPrologue.
938 if (HasBP && MaxAlign > 1) {
939 if (isPPC64)
940 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
941 .addReg(SPReg)
942 .addImm(0)
943 .addImm(64 - Log2(MaxAlign));
944 else // PPC32...
945 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
946 .addReg(SPReg)
947 .addImm(0)
948 .addImm(32 - Log2(MaxAlign))
949 .addImm(31);
950 if (!isLargeFrame) {
951 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
952 .addReg(ScratchReg, RegState::Kill)
953 .addImm(NegFrameSize);
954 } else {
955 assert(!SingleScratchReg && "Only a single scratch reg available");
956 TII.materializeImmPostRA(MBB, MBBI, dl, TempReg, NegFrameSize);
957 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
958 .addReg(ScratchReg, RegState::Kill)
959 .addReg(TempReg, RegState::Kill);
960 }
961
962 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
964 .addReg(SPReg)
965 .addReg(ScratchReg);
966 } else if (!isLargeFrame) {
967 BuildMI(MBB, StackUpdateLoc, dl, StoreUpdtInst, SPReg)
968 .addReg(SPReg)
969 .addImm(NegFrameSize)
970 .addReg(SPReg);
971 } else {
972 TII.materializeImmPostRA(MBB, MBBI, dl, ScratchReg, NegFrameSize);
973 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
975 .addReg(SPReg)
976 .addReg(ScratchReg);
977 }
978 }
979
980 // Save the TOC register after the stack pointer update if a prologue TOC
981 // save is required for the function.
982 if (MustSaveTOC) {
983 assert(isELFv2ABI && "TOC saves in the prologue only supported on ELFv2");
984 BuildMI(MBB, StackUpdateLoc, dl, TII.get(PPC::STD))
985 .addReg(TOCReg, getKillRegState(true))
986 .addImm(TOCSaveOffset)
987 .addReg(SPReg);
988 }
989
990 if (!HasRedZone) {
991 assert(!isPPC64 && "A red zone is always available on PPC64");
992 if (HasSTUX) {
993 // The negated frame size is in ScratchReg, and the SPReg has been
994 // decremented by the frame size: SPReg = old SPReg + ScratchReg.
995 // Since FPOffset, PBPOffset, etc. are relative to the beginning of
996 // the stack frame (i.e. the old SP), ideally, we would put the old
997 // SP into a register and use it as the base for the stores. The
998 // problem is that the only available register may be ScratchReg,
999 // which could be R0, and R0 cannot be used as a base address.
1000
1001 // First, set ScratchReg to the old SP. This may need to be modified
1002 // later.
1003 BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
1004 .addReg(ScratchReg, RegState::Kill)
1005 .addReg(SPReg);
1006
1007 if (ScratchReg == PPC::R0) {
1008 // R0 cannot be used as a base register, but it can be used as an
1009 // index in a store-indexed.
1010 int LastOffset = 0;
1011 if (HasFP) {
1012 // R0 += (FPOffset-LastOffset).
1013 // Need addic, since addi treats R0 as 0.
1014 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
1015 .addReg(ScratchReg)
1016 .addImm(FPOffset-LastOffset);
1017 LastOffset = FPOffset;
1018 // Store FP into *R0.
1019 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
1020 .addReg(FPReg, RegState::Kill) // Save FP.
1021 .addReg(PPC::ZERO)
1022 .addReg(ScratchReg); // This will be the index (R0 is ok here).
1023 }
1024 if (FI->usesPICBase()) {
1025 // R0 += (PBPOffset-LastOffset).
1026 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
1027 .addReg(ScratchReg)
1028 .addImm(PBPOffset-LastOffset);
1029 LastOffset = PBPOffset;
1030 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
1031 .addReg(PPC::R30, RegState::Kill) // Save PIC base pointer.
1032 .addReg(PPC::ZERO)
1033 .addReg(ScratchReg); // This will be the index (R0 is ok here).
1034 }
1035 if (HasBP) {
1036 // R0 += (BPOffset-LastOffset).
1037 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
1038 .addReg(ScratchReg)
1039 .addImm(BPOffset-LastOffset);
1040 LastOffset = BPOffset;
1041 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
1042 .addReg(BPReg, RegState::Kill) // Save BP.
1043 .addReg(PPC::ZERO)
1044 .addReg(ScratchReg); // This will be the index (R0 is ok here).
1045 // BP = R0-LastOffset
1046 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), BPReg)
1047 .addReg(ScratchReg, RegState::Kill)
1048 .addImm(-LastOffset);
1049 }
1050 } else {
1051 // ScratchReg is not R0, so use it as the base register. It is
1052 // already set to the old SP, so we can use the offsets directly.
1053
1054 // Now that the stack frame has been allocated, save all the necessary
1055 // registers using ScratchReg as the base address.
1056 if (HasFP)
1057 BuildMI(MBB, MBBI, dl, StoreInst)
1058 .addReg(FPReg)
1059 .addImm(FPOffset)
1060 .addReg(ScratchReg);
1061 if (FI->usesPICBase())
1062 BuildMI(MBB, MBBI, dl, StoreInst)
1063 .addReg(PPC::R30)
1064 .addImm(PBPOffset)
1065 .addReg(ScratchReg);
1066 if (HasBP) {
1067 BuildMI(MBB, MBBI, dl, StoreInst)
1068 .addReg(BPReg)
1069 .addImm(BPOffset)
1070 .addReg(ScratchReg);
1071 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
1072 .addReg(ScratchReg, RegState::Kill)
1073 .addReg(ScratchReg);
1074 }
1075 }
1076 } else {
1077 // The frame size is a known 16-bit constant (fitting in the immediate
1078 // field of STWU). To be here we have to be compiling for PPC32.
1079 // Since the SPReg has been decreased by FrameSize, add it back to each
1080 // offset.
1081 if (HasFP)
1082 BuildMI(MBB, MBBI, dl, StoreInst)
1083 .addReg(FPReg)
1084 .addImm(FrameSize + FPOffset)
1085 .addReg(SPReg);
1086 if (FI->usesPICBase())
1087 BuildMI(MBB, MBBI, dl, StoreInst)
1088 .addReg(PPC::R30)
1089 .addImm(FrameSize + PBPOffset)
1090 .addReg(SPReg);
1091 if (HasBP) {
1092 BuildMI(MBB, MBBI, dl, StoreInst)
1093 .addReg(BPReg)
1094 .addImm(FrameSize + BPOffset)
1095 .addReg(SPReg);
1096 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), BPReg)
1097 .addReg(SPReg)
1098 .addImm(FrameSize);
1099 }
1100 }
1101 }
1102
1103 // Save the LR now.
1104 if (!HasSTUX && MustSaveLR && !HasFastMFLR &&
1105 isInt<16>(FrameSize + LROffset) && !HasROPProtect)
1106 SaveLR(LROffset + FrameSize);
1107
1108 // Add Call Frame Information for the instructions we generated above.
1109 if (needsCFI) {
1110 unsigned CFIIndex;
1111
1112 if (HasBP) {
1113 // Define CFA in terms of BP. Do this in preference to using FP/SP,
1114 // because if the stack needed aligning then CFA won't be at a fixed
1115 // offset from FP/SP.
1116 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
1117 CFIIndex = MF.addFrameInst(
1119 } else {
1120 // Adjust the definition of CFA to account for the change in SP.
1121 assert(NegFrameSize);
1122 CFIIndex = MF.addFrameInst(
1123 MCCFIInstruction::cfiDefCfaOffset(nullptr, -NegFrameSize));
1124 }
1125 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1126 .addCFIIndex(CFIIndex);
1127
1128 if (HasFP) {
1129 // Describe where FP was saved, at a fixed offset from CFA.
1130 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
1131 CFIIndex = MF.addFrameInst(
1132 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
1133 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1134 .addCFIIndex(CFIIndex);
1135 }
1136
1137 if (FI->usesPICBase()) {
1138 // Describe where FP was saved, at a fixed offset from CFA.
1139 unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
1140 CFIIndex = MF.addFrameInst(
1141 MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
1142 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1143 .addCFIIndex(CFIIndex);
1144 }
1145
1146 if (HasBP) {
1147 // Describe where BP was saved, at a fixed offset from CFA.
1148 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
1149 CFIIndex = MF.addFrameInst(
1150 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
1151 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1152 .addCFIIndex(CFIIndex);
1153 }
1154
1155 if (MustSaveLR) {
1156 // Describe where LR was saved, at a fixed offset from CFA.
1157 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
1158 CFIIndex = MF.addFrameInst(
1159 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
1160 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1161 .addCFIIndex(CFIIndex);
1162 }
1163 }
1164
1165 // If there is a frame pointer, copy R1 into R31
1166 if (HasFP) {
1167 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
1168 .addReg(SPReg)
1169 .addReg(SPReg);
1170
1171 if (!HasBP && needsCFI) {
1172 // Change the definition of CFA from SP+offset to FP+offset, because SP
1173 // will change at every alloca.
1174 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
1175 unsigned CFIIndex = MF.addFrameInst(
1177
1178 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1179 .addCFIIndex(CFIIndex);
1180 }
1181 }
1182
1183 if (needsCFI) {
1184 // Describe where callee saved registers were saved, at fixed offsets from
1185 // CFA.
1186 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1187 for (const CalleeSavedInfo &I : CSI) {
1188 MCRegister Reg = I.getReg();
1189 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
1190
1191 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
1192 // subregisters of CR2. We just need to emit a move of CR2.
1193 if (PPC::CRBITRCRegClass.contains(Reg))
1194 continue;
1195
1196 if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
1197 continue;
1198
1199 // For 64-bit SVR4 when we have spilled CRs, the spill location
1200 // is SP+8, not a frame-relative slot.
1201 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1202 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
1203 // the whole CR word. In the ELFv2 ABI, every CR that was
1204 // actually saved gets its own CFI record.
1205 Register CRReg = isELFv2ABI? Reg : PPC::CR2;
1206 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
1207 nullptr, MRI->getDwarfRegNum(CRReg, true), CRSaveOffset));
1208 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1209 .addCFIIndex(CFIIndex);
1210 continue;
1211 }
1212
1213 if (I.isSpilledToReg()) {
1214 unsigned SpilledReg = I.getDstReg();
1215 unsigned CFIRegister = MF.addFrameInst(MCCFIInstruction::createRegister(
1216 nullptr, MRI->getDwarfRegNum(Reg, true),
1217 MRI->getDwarfRegNum(SpilledReg, true)));
1218 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1219 .addCFIIndex(CFIRegister);
1220 } else {
1221 int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
1222 // We have changed the object offset above but we do not want to change
1223 // the actual offsets in the CFI instruction so we have to undo the
1224 // offset change here.
1225 if (MovingStackUpdateDown)
1226 Offset -= NegFrameSize;
1227
1228 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
1229 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
1230 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1231 .addCFIIndex(CFIIndex);
1232 }
1233 }
1234 }
1235}
1236
1238 MachineBasicBlock &PrologMBB) const {
1239 bool isPPC64 = Subtarget.isPPC64();
1240 const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
1241 const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
1242 MachineFrameInfo &MFI = MF.getFrameInfo();
1243 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
1244 // AIX assembler does not support cfi directives.
1245 const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();
1246 auto StackAllocMIPos = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
1247 int Opc = MI.getOpcode();
1248 return Opc == PPC::PROBED_STACKALLOC_64 || Opc == PPC::PROBED_STACKALLOC_32;
1249 });
1250 if (StackAllocMIPos == PrologMBB.end())
1251 return;
1252 const BasicBlock *ProbedBB = PrologMBB.getBasicBlock();
1253 MachineBasicBlock *CurrentMBB = &PrologMBB;
1254 DebugLoc DL = PrologMBB.findDebugLoc(StackAllocMIPos);
1255 MachineInstr &MI = *StackAllocMIPos;
1256 int64_t NegFrameSize = MI.getOperand(2).getImm();
1257 unsigned ProbeSize = TLI.getStackProbeSize(MF);
1258 int64_t NegProbeSize = -(int64_t)ProbeSize;
1259 assert(isInt<32>(NegProbeSize) && "Unhandled probe size");
1260 int64_t NumBlocks = NegFrameSize / NegProbeSize;
1261 int64_t NegResidualSize = NegFrameSize % NegProbeSize;
1262 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
1263 Register ScratchReg = MI.getOperand(0).getReg();
1264 Register FPReg = MI.getOperand(1).getReg();
1265 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1266 bool HasBP = RegInfo->hasBasePointer(MF);
1267 Register BPReg = RegInfo->getBaseRegister(MF);
1268 Align MaxAlign = MFI.getMaxAlign();
1269 bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
1270 const MCInstrDesc &CopyInst = TII.get(isPPC64 ? PPC::OR8 : PPC::OR);
1271 // Subroutines to generate .cfi_* directives.
1274 unsigned RegNum = MRI->getDwarfRegNum(Reg, true);
1275 unsigned CFIIndex = MF.addFrameInst(
1277 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1278 .addCFIIndex(CFIIndex);
1279 };
1280 auto buildDefCFA = [&](MachineBasicBlock &MBB,
1282 int Offset) {
1283 unsigned RegNum = MRI->getDwarfRegNum(Reg, true);
1284 unsigned CFIIndex = MBB.getParent()->addFrameInst(
1285 MCCFIInstruction::cfiDefCfa(nullptr, RegNum, Offset));
1286 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1287 .addCFIIndex(CFIIndex);
1288 };
1289 // Subroutine to determine if we can use the Imm as part of d-form.
1290 auto CanUseDForm = [](int64_t Imm) { return isInt<16>(Imm) && Imm % 4 == 0; };
1291 // Subroutine to materialize the Imm into TempReg.
1292 auto MaterializeImm = [&](MachineBasicBlock &MBB,
1294 Register &TempReg) {
1295 assert(isInt<32>(Imm) && "Unhandled imm");
1296 if (isInt<16>(Imm))
1297 BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LI8 : PPC::LI), TempReg)
1298 .addImm(Imm);
1299 else {
1300 BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
1301 .addImm(Imm >> 16);
1302 BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::ORI8 : PPC::ORI), TempReg)
1303 .addReg(TempReg)
1304 .addImm(Imm & 0xFFFF);
1305 }
1306 };
1307 // Subroutine to store frame pointer and decrease stack pointer by probe size.
1308 auto allocateAndProbe = [&](MachineBasicBlock &MBB,
1309 MachineBasicBlock::iterator MBBI, int64_t NegSize,
1310 Register NegSizeReg, bool UseDForm,
1311 Register StoreReg) {
1312 if (UseDForm)
1313 BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDU : PPC::STWU), SPReg)
1314 .addReg(StoreReg)
1315 .addImm(NegSize)
1316 .addReg(SPReg);
1317 else
1318 BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
1319 .addReg(StoreReg)
1320 .addReg(SPReg)
1321 .addReg(NegSizeReg);
1322 };
1323 // Used to probe stack when realignment is required.
1324 // Note that, according to ABI's requirement, *sp must always equals the
1325 // value of back-chain pointer, only st(w|d)u(x) can be used to update sp.
1326 // Following is pseudo code:
1327 // final_sp = (sp & align) + negframesize;
1328 // neg_gap = final_sp - sp;
1329 // while (neg_gap < negprobesize) {
1330 // stdu fp, negprobesize(sp);
1331 // neg_gap -= negprobesize;
1332 // }
1333 // stdux fp, sp, neg_gap
1334 //
1335 // When HasBP & HasRedzone, back-chain pointer is already saved in BPReg
1336 // before probe code, we don't need to save it, so we get one additional reg
1337 // that can be used to materialize the probeside if needed to use xform.
1338 // Otherwise, we can NOT materialize probeside, so we can only use Dform for
1339 // now.
1340 //
1341 // The allocations are:
1342 // if (HasBP && HasRedzone) {
1343 // r0: materialize the probesize if needed so that we can use xform.
1344 // r12: `neg_gap`
1345 // } else {
1346 // r0: back-chain pointer
1347 // r12: `neg_gap`.
1348 // }
1349 auto probeRealignedStack = [&](MachineBasicBlock &MBB,
1351 Register ScratchReg, Register TempReg) {
1352 assert(HasBP && "The function is supposed to have base pointer when its "
1353 "stack is realigned.");
1354 assert(isPowerOf2_64(ProbeSize) && "Probe size should be power of 2");
1355
1356 // FIXME: We can eliminate this limitation if we get more infomation about
1357 // which part of redzone are already used. Used redzone can be treated
1358 // probed. But there might be `holes' in redzone probed, this could
1359 // complicate the implementation.
1360 assert(ProbeSize >= Subtarget.getRedZoneSize() &&
1361 "Probe size should be larger or equal to the size of red-zone so "
1362 "that red-zone is not clobbered by probing.");
1363
1364 Register &FinalStackPtr = TempReg;
1365 // FIXME: We only support NegProbeSize materializable by DForm currently.
1366 // When HasBP && HasRedzone, we can use xform if we have an additional idle
1367 // register.
1368 NegProbeSize = std::max(NegProbeSize, -((int64_t)1 << 15));
1369 assert(isInt<16>(NegProbeSize) &&
1370 "NegProbeSize should be materializable by DForm");
1371 Register CRReg = PPC::CR0;
1372 // Layout of output assembly kinda like:
1373 // bb.0:
1374 // ...
1375 // sub $scratchreg, $finalsp, r1
1376 // cmpdi $scratchreg, <negprobesize>
1377 // bge bb.2
1378 // bb.1:
1379 // stdu <backchain>, <negprobesize>(r1)
1380 // sub $scratchreg, $scratchreg, negprobesize
1381 // cmpdi $scratchreg, <negprobesize>
1382 // blt bb.1
1383 // bb.2:
1384 // stdux <backchain>, r1, $scratchreg
1385 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
1386 MachineBasicBlock *ProbeLoopBodyMBB = MF.CreateMachineBasicBlock(ProbedBB);
1387 MF.insert(MBBInsertPoint, ProbeLoopBodyMBB);
1388 MachineBasicBlock *ProbeExitMBB = MF.CreateMachineBasicBlock(ProbedBB);
1389 MF.insert(MBBInsertPoint, ProbeExitMBB);
1390 // bb.2
1391 {
1392 Register BackChainPointer = HasRedZone ? BPReg : TempReg;
1393 allocateAndProbe(*ProbeExitMBB, ProbeExitMBB->end(), 0, ScratchReg, false,
1394 BackChainPointer);
1395 if (HasRedZone)
1396 // PROBED_STACKALLOC_64 assumes Operand(1) stores the old sp, copy BPReg
1397 // to TempReg to satisfy it.
1398 BuildMI(*ProbeExitMBB, ProbeExitMBB->end(), DL, CopyInst, TempReg)
1399 .addReg(BPReg)
1400 .addReg(BPReg);
1401 ProbeExitMBB->splice(ProbeExitMBB->end(), &MBB, MBBI, MBB.end());
1402 ProbeExitMBB->transferSuccessorsAndUpdatePHIs(&MBB);
1403 }
1404 // bb.0
1405 {
1406 BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), ScratchReg)
1407 .addReg(SPReg)
1408 .addReg(FinalStackPtr);
1409 if (!HasRedZone)
1410 BuildMI(&MBB, DL, CopyInst, TempReg).addReg(SPReg).addReg(SPReg);
1411 BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI), CRReg)
1412 .addReg(ScratchReg)
1413 .addImm(NegProbeSize);
1414 BuildMI(&MBB, DL, TII.get(PPC::BCC))
1416 .addReg(CRReg)
1417 .addMBB(ProbeExitMBB);
1418 MBB.addSuccessor(ProbeLoopBodyMBB);
1419 MBB.addSuccessor(ProbeExitMBB);
1420 }
1421 // bb.1
1422 {
1423 Register BackChainPointer = HasRedZone ? BPReg : TempReg;
1424 allocateAndProbe(*ProbeLoopBodyMBB, ProbeLoopBodyMBB->end(), NegProbeSize,
1425 0, true /*UseDForm*/, BackChainPointer);
1426 BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::ADDI8 : PPC::ADDI),
1427 ScratchReg)
1428 .addReg(ScratchReg)
1429 .addImm(-NegProbeSize);
1430 BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI),
1431 CRReg)
1432 .addReg(ScratchReg)
1433 .addImm(NegProbeSize);
1434 BuildMI(ProbeLoopBodyMBB, DL, TII.get(PPC::BCC))
1436 .addReg(CRReg)
1437 .addMBB(ProbeLoopBodyMBB);
1438 ProbeLoopBodyMBB->addSuccessor(ProbeExitMBB);
1439 ProbeLoopBodyMBB->addSuccessor(ProbeLoopBodyMBB);
1440 }
1441 // Update liveins.
1442 fullyRecomputeLiveIns({ProbeExitMBB, ProbeLoopBodyMBB});
1443 return ProbeExitMBB;
1444 };
1445 // For case HasBP && MaxAlign > 1, we have to realign the SP by performing
1446 // SP = SP - SP % MaxAlign, thus make the probe more like dynamic probe since
1447 // the offset subtracted from SP is determined by SP's runtime value.
1448 if (HasBP && MaxAlign > 1) {
1449 // Calculate final stack pointer.
1450 if (isPPC64)
1451 BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLDICL), ScratchReg)
1452 .addReg(SPReg)
1453 .addImm(0)
1454 .addImm(64 - Log2(MaxAlign));
1455 else
1456 BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLWINM), ScratchReg)
1457 .addReg(SPReg)
1458 .addImm(0)
1459 .addImm(32 - Log2(MaxAlign))
1460 .addImm(31);
1461 BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF),
1462 FPReg)
1463 .addReg(ScratchReg)
1464 .addReg(SPReg);
1465 MaterializeImm(*CurrentMBB, {MI}, NegFrameSize, ScratchReg);
1466 BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
1467 FPReg)
1468 .addReg(ScratchReg)
1469 .addReg(FPReg);
1470 CurrentMBB = probeRealignedStack(*CurrentMBB, {MI}, ScratchReg, FPReg);
1471 if (needsCFI)
1472 buildDefCFAReg(*CurrentMBB, {MI}, FPReg);
1473 } else {
1474 // Initialize current frame pointer.
1475 BuildMI(*CurrentMBB, {MI}, DL, CopyInst, FPReg).addReg(SPReg).addReg(SPReg);
1476 // Use FPReg to calculate CFA.
1477 if (needsCFI)
1478 buildDefCFA(*CurrentMBB, {MI}, FPReg, 0);
1479 // Probe residual part.
1480 if (NegResidualSize) {
1481 bool ResidualUseDForm = CanUseDForm(NegResidualSize);
1482 if (!ResidualUseDForm)
1483 MaterializeImm(*CurrentMBB, {MI}, NegResidualSize, ScratchReg);
1484 allocateAndProbe(*CurrentMBB, {MI}, NegResidualSize, ScratchReg,
1485 ResidualUseDForm, FPReg);
1486 }
1487 bool UseDForm = CanUseDForm(NegProbeSize);
1488 // If number of blocks is small, just probe them directly.
1489 if (NumBlocks < 3) {
1490 if (!UseDForm)
1491 MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);
1492 for (int i = 0; i < NumBlocks; ++i)
1493 allocateAndProbe(*CurrentMBB, {MI}, NegProbeSize, ScratchReg, UseDForm,
1494 FPReg);
1495 if (needsCFI) {
1496 // Restore using SPReg to calculate CFA.
1497 buildDefCFAReg(*CurrentMBB, {MI}, SPReg);
1498 }
1499 } else {
1500 // Since CTR is a volatile register and current shrinkwrap implementation
1501 // won't choose an MBB in a loop as the PrologMBB, it's safe to synthesize a
1502 // CTR loop to probe.
1503 // Calculate trip count and stores it in CTRReg.
1504 MaterializeImm(*CurrentMBB, {MI}, NumBlocks, ScratchReg);
1505 BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::MTCTR8 : PPC::MTCTR))
1506 .addReg(ScratchReg, RegState::Kill);
1507 if (!UseDForm)
1508 MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);
1509 // Create MBBs of the loop.
1510 MachineFunction::iterator MBBInsertPoint =
1511 std::next(CurrentMBB->getIterator());
1512 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(ProbedBB);
1513 MF.insert(MBBInsertPoint, LoopMBB);
1514 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(ProbedBB);
1515 MF.insert(MBBInsertPoint, ExitMBB);
1516 // Synthesize the loop body.
1517 allocateAndProbe(*LoopMBB, LoopMBB->end(), NegProbeSize, ScratchReg,
1518 UseDForm, FPReg);
1519 BuildMI(LoopMBB, DL, TII.get(isPPC64 ? PPC::BDNZ8 : PPC::BDNZ))
1520 .addMBB(LoopMBB);
1521 LoopMBB->addSuccessor(ExitMBB);
1522 LoopMBB->addSuccessor(LoopMBB);
1523 // Synthesize the exit MBB.
1524 ExitMBB->splice(ExitMBB->end(), CurrentMBB,
1525 std::next(MachineBasicBlock::iterator(MI)),
1526 CurrentMBB->end());
1527 ExitMBB->transferSuccessorsAndUpdatePHIs(CurrentMBB);
1528 CurrentMBB->addSuccessor(LoopMBB);
1529 if (needsCFI) {
1530 // Restore using SPReg to calculate CFA.
1531 buildDefCFAReg(*ExitMBB, ExitMBB->begin(), SPReg);
1532 }
1533 // Update liveins.
1534 fullyRecomputeLiveIns({ExitMBB, LoopMBB});
1535 }
1536 }
1537 ++NumPrologProbed;
1538 MI.eraseFromParent();
1539}
1540
1542 MachineBasicBlock &MBB) const {
1543 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1544 DebugLoc dl;
1545
1546 if (MBBI != MBB.end())
1547 dl = MBBI->getDebugLoc();
1548
1549 const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
1550 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1551
1552 // Get alignment info so we know how to restore the SP.
1553 const MachineFrameInfo &MFI = MF.getFrameInfo();
1554
1555 // Get the number of bytes allocated from the FrameInfo.
1556 int64_t FrameSize = MFI.getStackSize();
1557
1558 // Get processor type.
1559 bool isPPC64 = Subtarget.isPPC64();
1560
1561 // Check if the link register (LR) has been saved.
1563 bool MustSaveLR = FI->mustSaveLR();
1564 const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
1565 bool MustSaveCR = !MustSaveCRs.empty();
1566 // Do we have a frame pointer and/or base pointer for this function?
1567 bool HasFP = hasFP(MF);
1568 bool HasBP = RegInfo->hasBasePointer(MF);
1569 bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
1570 bool HasROPProtect = Subtarget.hasROPProtect();
1571 bool HasPrivileged = Subtarget.hasPrivileged();
1572
1573 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
1574 Register BPReg = RegInfo->getBaseRegister(MF);
1575 Register FPReg = isPPC64 ? PPC::X31 : PPC::R31;
1576 Register ScratchReg;
1577 Register TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
1578 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
1579 : PPC::MTLR );
1580 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
1581 : PPC::LWZ );
1582 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
1583 : PPC::LIS );
1584 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
1585 : PPC::OR );
1586 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
1587 : PPC::ORI );
1588 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
1589 : PPC::ADDI );
1590 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
1591 : PPC::ADD4 );
1592 const MCInstrDesc& LoadWordInst = TII.get( isPPC64 ? PPC::LWZ8
1593 : PPC::LWZ);
1594 const MCInstrDesc& MoveToCRInst = TII.get( isPPC64 ? PPC::MTOCRF8
1595 : PPC::MTOCRF);
1596 const MCInstrDesc &HashChk =
1597 TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHCHKP8 : PPC::HASHCHK8)
1598 : (HasPrivileged ? PPC::HASHCHKP : PPC::HASHCHK));
1599 int64_t LROffset = getReturnSaveOffset();
1600
1601 int64_t FPOffset = 0;
1602
1603 // Using the same bool variable as below to suppress compiler warnings.
1604 bool SingleScratchReg = findScratchRegister(&MBB, true, false, &ScratchReg,
1605 &TempReg);
1606 assert(SingleScratchReg &&
1607 "Could not find an available scratch register");
1608
1609 SingleScratchReg = ScratchReg == TempReg;
1610
1611 if (HasFP) {
1612 int FPIndex = FI->getFramePointerSaveIndex();
1613 assert(FPIndex && "No Frame Pointer Save Slot!");
1614 FPOffset = MFI.getObjectOffset(FPIndex);
1615 }
1616
1617 int64_t BPOffset = 0;
1618 if (HasBP) {
1619 int BPIndex = FI->getBasePointerSaveIndex();
1620 assert(BPIndex && "No Base Pointer Save Slot!");
1621 BPOffset = MFI.getObjectOffset(BPIndex);
1622 }
1623
1624 int64_t PBPOffset = 0;
1625 if (FI->usesPICBase()) {
1626 int PBPIndex = FI->getPICBasePointerSaveIndex();
1627 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
1628 PBPOffset = MFI.getObjectOffset(PBPIndex);
1629 }
1630
1631 bool IsReturnBlock = (MBBI != MBB.end() && MBBI->isReturn());
1632
1633 if (IsReturnBlock) {
1634 unsigned RetOpcode = MBBI->getOpcode();
1635 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
1636 RetOpcode == PPC::TCRETURNdi ||
1637 RetOpcode == PPC::TCRETURNai ||
1638 RetOpcode == PPC::TCRETURNri8 ||
1639 RetOpcode == PPC::TCRETURNdi8 ||
1640 RetOpcode == PPC::TCRETURNai8;
1641
1642 if (UsesTCRet) {
1643 int MaxTCRetDelta = FI->getTailCallSPDelta();
1644 MachineOperand &StackAdjust = MBBI->getOperand(1);
1645 assert(StackAdjust.isImm() && "Expecting immediate value.");
1646 // Adjust stack pointer.
1647 int StackAdj = StackAdjust.getImm();
1648 int Delta = StackAdj - MaxTCRetDelta;
1649 assert((Delta >= 0) && "Delta must be positive");
1650 if (MaxTCRetDelta>0)
1651 FrameSize += (StackAdj +Delta);
1652 else
1653 FrameSize += StackAdj;
1654 }
1655 }
1656
1657 // Frames of 32KB & larger require special handling because they cannot be
1658 // indexed into with a simple LD/LWZ immediate offset operand.
1659 bool isLargeFrame = !isInt<16>(FrameSize);
1660
1661 // On targets without red zone, the SP needs to be restored last, so that
1662 // all live contents of the stack frame are upwards of the SP. This means
1663 // that we cannot restore SP just now, since there may be more registers
1664 // to restore from the stack frame (e.g. R31). If the frame size is not
1665 // a simple immediate value, we will need a spare register to hold the
1666 // restored SP. If the frame size is known and small, we can simply adjust
1667 // the offsets of the registers to be restored, and still use SP to restore
1668 // them. In such case, the final update of SP will be to add the frame
1669 // size to it.
1670 // To simplify the code, set RBReg to the base register used to restore
1671 // values from the stack, and set SPAdd to the value that needs to be added
1672 // to the SP at the end. The default values are as if red zone was present.
1673 unsigned RBReg = SPReg;
1674 uint64_t SPAdd = 0;
1675
1676 // Check if we can move the stack update instruction up the epilogue
1677 // past the callee saves. This will allow the move to LR instruction
1678 // to be executed before the restores of the callee saves which means
1679 // that the callee saves can hide the latency from the MTLR instrcution.
1680 MachineBasicBlock::iterator StackUpdateLoc = MBBI;
1681 if (stackUpdateCanBeMoved(MF)) {
1682 const std::vector<CalleeSavedInfo> & Info = MFI.getCalleeSavedInfo();
1683 for (CalleeSavedInfo CSI : Info) {
1684 // If the callee saved register is spilled to another register abort the
1685 // stack update movement.
1686 if (CSI.isSpilledToReg()) {
1687 StackUpdateLoc = MBBI;
1688 break;
1689 }
1690 int FrIdx = CSI.getFrameIdx();
1691 // If the frame index is not negative the callee saved info belongs to a
1692 // stack object that is not a fixed stack object. We ignore non-fixed
1693 // stack objects because we won't move the update of the stack pointer
1694 // past them.
1695 if (FrIdx >= 0)
1696 continue;
1697
1698 if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0)
1699 StackUpdateLoc--;
1700 else {
1701 // Abort the operation as we can't update all CSR restores.
1702 StackUpdateLoc = MBBI;
1703 break;
1704 }
1705 }
1706 }
1707
1708 if (FrameSize) {
1709 // In the prologue, the loaded (or persistent) stack pointer value is
1710 // offset by the STDU/STDUX/STWU/STWUX instruction. For targets with red
1711 // zone add this offset back now.
1712
1713 // If the function has a base pointer, the stack pointer has been copied
1714 // to it so we can restore it by copying in the other direction.
1715 if (HasRedZone && HasBP) {
1716 BuildMI(MBB, MBBI, dl, OrInst, RBReg).
1717 addReg(BPReg).
1718 addReg(BPReg);
1719 }
1720 // If this function contained a fastcc call and GuaranteedTailCallOpt is
1721 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1722 // call which invalidates the stack pointer value in SP(0). So we use the
1723 // value of R31 in this case. Similar situation exists with setjmp.
1724 else if (FI->hasFastCall() || MF.exposesReturnsTwice()) {
1725 assert(HasFP && "Expecting a valid frame pointer.");
1726 if (!HasRedZone)
1727 RBReg = FPReg;
1728 if (!isLargeFrame) {
1729 BuildMI(MBB, MBBI, dl, AddImmInst, RBReg)
1730 .addReg(FPReg).addImm(FrameSize);
1731 } else {
1732 TII.materializeImmPostRA(MBB, MBBI, dl, ScratchReg, FrameSize);
1733 BuildMI(MBB, MBBI, dl, AddInst)
1734 .addReg(RBReg)
1735 .addReg(FPReg)
1736 .addReg(ScratchReg);
1737 }
1738 } else if (!isLargeFrame && !HasBP && !MFI.hasVarSizedObjects()) {
1739 if (HasRedZone) {
1740 BuildMI(MBB, StackUpdateLoc, dl, AddImmInst, SPReg)
1741 .addReg(SPReg)
1742 .addImm(FrameSize);
1743 } else {
1744 // Make sure that adding FrameSize will not overflow the max offset
1745 // size.
1746 assert(FPOffset <= 0 && BPOffset <= 0 && PBPOffset <= 0 &&
1747 "Local offsets should be negative");
1748 SPAdd = FrameSize;
1749 FPOffset += FrameSize;
1750 BPOffset += FrameSize;
1751 PBPOffset += FrameSize;
1752 }
1753 } else {
1754 // We don't want to use ScratchReg as a base register, because it
1755 // could happen to be R0. Use FP instead, but make sure to preserve it.
1756 if (!HasRedZone) {
1757 // If FP is not saved, copy it to ScratchReg.
1758 if (!HasFP)
1759 BuildMI(MBB, MBBI, dl, OrInst, ScratchReg)
1760 .addReg(FPReg)
1761 .addReg(FPReg);
1762 RBReg = FPReg;
1763 }
1764 BuildMI(MBB, StackUpdateLoc, dl, LoadInst, RBReg)
1765 .addImm(0)
1766 .addReg(SPReg);
1767 }
1768 }
1769 assert(RBReg != ScratchReg && "Should have avoided ScratchReg");
1770
1771 // Lambda to build MTCRF/MTOCRF instruction for restoring CR fields
1772 auto BuildMoveToCR = [&](MachineBasicBlock::iterator InsertPt,
1773 Register SrcReg) {
1774 if (MustSaveCRs.size() == 1)
1775 // Use MTOCRF for single CR field
1776 BuildMI(MBB, InsertPt, dl, MoveToCRInst, MustSaveCRs[0])
1777 .addReg(SrcReg, getKillRegState(true));
1778 else {
1779 // Build CR mask for MTCRF.
1780 unsigned CRMask = 0;
1781 for (unsigned CRField : MustSaveCRs) {
1782 CRMask |= 0x80 >> (CRField - PPC::CR0);
1783 }
1784 BuildMI(MBB, InsertPt, dl, TII.get(isPPC64 ? PPC::MTCRF8 : PPC::MTCRF))
1785 .addImm(CRMask)
1786 .addReg(SrcReg, getKillRegState(true));
1787 }
1788 };
1789
1790 // If there is no red zone, ScratchReg may be needed for holding a useful
1791 // value (although not the base register). Make sure it is not overwritten
1792 // too early.
1793
1794 // If we need to restore both the LR and the CR and we only have one
1795 // available scratch register, we must do them one at a time.
1796 if (MustSaveCR && SingleScratchReg && MustSaveLR) {
1797 // Here TempReg == ScratchReg, and in the absence of red zone ScratchReg
1798 // is live here.
1799 assert(HasRedZone && "Expecting red zone");
1800 BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)
1801 .addImm(CRSaveOffset)
1802 .addReg(SPReg);
1803 BuildMoveToCR(MBBI, TempReg);
1804 }
1805
1806 // Delay restoring of the LR if ScratchReg is needed. This is ok, since
1807 // LR is stored in the caller's stack frame. ScratchReg will be needed
1808 // if RBReg is anything other than SP. We shouldn't use ScratchReg as
1809 // a base register anyway, because it may happen to be R0.
1810 bool LoadedLR = false;
1811 if (MustSaveLR && RBReg == SPReg && isInt<16>(LROffset+SPAdd)) {
1812 BuildMI(MBB, StackUpdateLoc, dl, LoadInst, ScratchReg)
1813 .addImm(LROffset+SPAdd)
1814 .addReg(RBReg);
1815 LoadedLR = true;
1816 }
1817
1818 if (MustSaveCR && !(SingleScratchReg && MustSaveLR)) {
1819 assert(RBReg == SPReg && "Should be using SP as a base register");
1820 BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)
1821 .addImm(CRSaveOffset)
1822 .addReg(RBReg);
1823 }
1824
1825 if (HasFP) {
1826 // If there is red zone, restore FP directly, since SP has already been
1827 // restored. Otherwise, restore the value of FP into ScratchReg.
1828 if (HasRedZone || RBReg == SPReg)
1829 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1830 .addImm(FPOffset)
1831 .addReg(SPReg);
1832 else
1833 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1834 .addImm(FPOffset)
1835 .addReg(RBReg);
1836 }
1837
1838 if (FI->usesPICBase())
1839 BuildMI(MBB, MBBI, dl, LoadInst, PPC::R30)
1840 .addImm(PBPOffset)
1841 .addReg(RBReg);
1842
1843 if (HasBP)
1844 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1845 .addImm(BPOffset)
1846 .addReg(RBReg);
1847
1848 // There is nothing more to be loaded from the stack, so now we can
1849 // restore SP: SP = RBReg + SPAdd.
1850 if (RBReg != SPReg || SPAdd != 0) {
1851 assert(!HasRedZone && "This should not happen with red zone");
1852 // If SPAdd is 0, generate a copy.
1853 if (SPAdd == 0)
1854 BuildMI(MBB, MBBI, dl, OrInst, SPReg)
1855 .addReg(RBReg)
1856 .addReg(RBReg);
1857 else
1858 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1859 .addReg(RBReg)
1860 .addImm(SPAdd);
1861
1862 assert(RBReg != ScratchReg && "Should be using FP or SP as base register");
1863 if (RBReg == FPReg)
1864 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
1865 .addReg(ScratchReg)
1866 .addReg(ScratchReg);
1867
1868 // Now load the LR from the caller's stack frame.
1869 if (MustSaveLR && !LoadedLR)
1870 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1871 .addImm(LROffset)
1872 .addReg(SPReg);
1873 }
1874
1875 if (MustSaveCR &&
1876 !(SingleScratchReg && MustSaveLR))
1877 BuildMoveToCR(MBBI, TempReg);
1878
1879 if (MustSaveLR) {
1880 // If ROP protection is required, an extra instruction is added to compute a
1881 // hash and then compare it to the hash stored in the prologue.
1882 if (HasROPProtect) {
1883 const int SaveIndex = FI->getROPProtectionHashSaveIndex();
1884 const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);
1885 assert((ImmOffset <= -8 && ImmOffset >= -512) &&
1886 "ROP hash check location offset out of range.");
1887 assert(((ImmOffset & 0x7) == 0) &&
1888 "ROP hash check location offset must be 8 byte aligned.");
1889 BuildMI(MBB, StackUpdateLoc, dl, HashChk)
1890 .addReg(ScratchReg)
1891 .addImm(ImmOffset)
1892 .addReg(SPReg);
1893 }
1894 BuildMI(MBB, StackUpdateLoc, dl, MTLRInst).addReg(ScratchReg);
1895 }
1896
1897 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1898 // call optimization
1899 if (IsReturnBlock) {
1900 unsigned RetOpcode = MBBI->getOpcode();
1902 (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1905 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1906
1907 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1908 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1909 .addReg(SPReg).addImm(CallerAllocatedAmt);
1910 } else {
1911 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1912 .addImm(CallerAllocatedAmt >> 16);
1913 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1914 .addReg(ScratchReg, RegState::Kill)
1915 .addImm(CallerAllocatedAmt & 0xFFFF);
1916 BuildMI(MBB, MBBI, dl, AddInst)
1917 .addReg(SPReg)
1918 .addReg(FPReg)
1919 .addReg(ScratchReg);
1920 }
1921 } else {
1922 createTailCallBranchInstr(MBB);
1923 }
1924 }
1925}
1926
1927void PPCFrameLowering::createTailCallBranchInstr(MachineBasicBlock &MBB) const {
1928 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1929
1930 // If we got this far a first terminator should exist.
1931 assert(MBBI != MBB.end() && "Failed to find the first terminator.");
1932
1933 DebugLoc dl = MBBI->getDebugLoc();
1934 const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
1935
1936 // Create branch instruction for pseudo tail call return instruction.
1937 // The TCRETURNdi variants are direct calls. Valid targets for those are
1938 // MO_GlobalAddress operands as well as MO_ExternalSymbol with PC-Rel
1939 // since we can tail call external functions with PC-Rel (i.e. we don't need
1940 // to worry about different TOC pointers). Some of the external functions will
1941 // be MO_GlobalAddress while others like memcpy for example, are going to
1942 // be MO_ExternalSymbol.
1943 unsigned RetOpcode = MBBI->getOpcode();
1944 if (RetOpcode == PPC::TCRETURNdi) {
1945 MBBI = MBB.getLastNonDebugInstr();
1946 MachineOperand &JumpTarget = MBBI->getOperand(0);
1947 if (JumpTarget.isGlobal())
1948 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1949 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1950 else if (JumpTarget.isSymbol())
1951 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1952 addExternalSymbol(JumpTarget.getSymbolName());
1953 else
1954 llvm_unreachable("Expecting Global or External Symbol");
1955 } else if (RetOpcode == PPC::TCRETURNri) {
1956 MBBI = MBB.getLastNonDebugInstr();
1957 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1958 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1959 } else if (RetOpcode == PPC::TCRETURNai) {
1961 MachineOperand &JumpTarget = MBBI->getOperand(0);
1962 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1963 } else if (RetOpcode == PPC::TCRETURNdi8) {
1965 MachineOperand &JumpTarget = MBBI->getOperand(0);
1966 if (JumpTarget.isGlobal())
1967 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1968 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1969 else if (JumpTarget.isSymbol())
1970 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1971 addExternalSymbol(JumpTarget.getSymbolName());
1972 else
1973 llvm_unreachable("Expecting Global or External Symbol");
1974 } else if (RetOpcode == PPC::TCRETURNri8) {
1976 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1977 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1978 } else if (RetOpcode == PPC::TCRETURNai8) {
1980 MachineOperand &JumpTarget = MBBI->getOperand(0);
1981 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1982 }
1983}
1984
1986 BitVector &SavedRegs,
1987 RegScavenger *RS) const {
1989 if (Subtarget.isAIXABI())
1990 updateCalleeSaves(MF, SavedRegs);
1991
1992 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1993
1994 // Do not explicitly save the callee saved VSRp registers.
1995 // The individual VSR subregisters will be saved instead.
1996 SavedRegs.reset(PPC::VSRp26);
1997 SavedRegs.reset(PPC::VSRp27);
1998 SavedRegs.reset(PPC::VSRp28);
1999 SavedRegs.reset(PPC::VSRp29);
2000 SavedRegs.reset(PPC::VSRp30);
2001 SavedRegs.reset(PPC::VSRp31);
2002
2003 // Save and clear the LR state.
2005 MCRegister LR = RegInfo->getRARegister();
2006 FI->setMustSaveLR(MustSaveLR(MF, LR));
2007 SavedRegs.reset(LR);
2008
2009 // Save R31 if necessary
2010 int FPSI = FI->getFramePointerSaveIndex();
2011 const bool isPPC64 = Subtarget.isPPC64();
2012 MachineFrameInfo &MFI = MF.getFrameInfo();
2013
2014 // If the frame pointer save index hasn't been defined yet.
2015 if (!FPSI && needsFP(MF)) {
2016 // Find out what the fix offset of the frame pointer save area.
2017 int FPOffset = getFramePointerSaveOffset();
2018 // Allocate the frame index for frame pointer save area.
2019 FPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
2020 // Save the result.
2021 FI->setFramePointerSaveIndex(FPSI);
2022 }
2023
2024 int BPSI = FI->getBasePointerSaveIndex();
2025 if (!BPSI && RegInfo->hasBasePointer(MF)) {
2026 int BPOffset = getBasePointerSaveOffset();
2027 // Allocate the frame index for the base pointer save area.
2028 BPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
2029 // Save the result.
2030 FI->setBasePointerSaveIndex(BPSI);
2031 }
2032
2033 // Reserve stack space for the PIC Base register (R30).
2034 // Only used in SVR4 32-bit.
2035 if (FI->usesPICBase()) {
2036 int PBPSI = MFI.CreateFixedObject(4, -8, true);
2037 FI->setPICBasePointerSaveIndex(PBPSI);
2038 }
2039
2040 // Make sure we don't explicitly spill r31, because, for example, we have
2041 // some inline asm which explicitly clobbers it, when we otherwise have a
2042 // frame pointer and are using r31's spill slot for the prologue/epilogue
2043 // code. Same goes for the base pointer and the PIC base register.
2044 if (needsFP(MF))
2045 SavedRegs.reset(isPPC64 ? PPC::X31 : PPC::R31);
2046 if (RegInfo->hasBasePointer(MF)) {
2047 SavedRegs.reset(RegInfo->getBaseRegister(MF));
2048 // On AIX, when BaseRegister(R30) is used, need to spill r31 too to match
2049 // AIX trackback table requirement.
2050 if (!needsFP(MF) && !SavedRegs.test(isPPC64 ? PPC::X31 : PPC::R31) &&
2051 Subtarget.isAIXABI()) {
2052 assert(
2053 (RegInfo->getBaseRegister(MF) == (isPPC64 ? PPC::X30 : PPC::R30)) &&
2054 "Invalid base register on AIX!");
2055 SavedRegs.set(isPPC64 ? PPC::X31 : PPC::R31);
2056 }
2057 }
2058 if (FI->usesPICBase())
2059 SavedRegs.reset(PPC::R30);
2060
2061 // Reserve stack space to move the linkage area to in case of a tail call.
2062 int TCSPDelta = 0;
2064 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
2065 MFI.CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
2066 }
2067
2068 // Allocate the nonvolatile CR spill slot iff the function uses CR 2, 3, or 4.
2069 // For 64-bit SVR4, and all flavors of AIX we create a FixedStack
2070 // object at the offset of the CR-save slot in the linkage area. The actual
2071 // save and restore of the condition register will be created as part of the
2072 // prologue and epilogue insertion, but the FixedStack object is needed to
2073 // keep the CalleSavedInfo valid.
2074 if ((SavedRegs.test(PPC::CR2) || SavedRegs.test(PPC::CR3) ||
2075 SavedRegs.test(PPC::CR4))) {
2076 const uint64_t SpillSize = 4; // Condition register is always 4 bytes.
2077 const int64_t SpillOffset =
2078 Subtarget.isPPC64() ? 8 : Subtarget.isAIXABI() ? 4 : -4;
2079 int FrameIdx =
2080 MFI.CreateFixedObject(SpillSize, SpillOffset,
2081 /* IsImmutable */ true, /* IsAliased */ false);
2082 FI->setCRSpillFrameIndex(FrameIdx);
2083 }
2084}
2085
2087 RegScavenger *RS) const {
2088 // Get callee saved register information.
2089 MachineFrameInfo &MFI = MF.getFrameInfo();
2090 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2091
2092 // If the function is shrink-wrapped, and if the function has a tail call, the
2093 // tail call might not be in the new RestoreBlock, so real branch instruction
2094 // won't be generated by emitEpilogue(), because shrink-wrap has chosen new
2095 // RestoreBlock. So we handle this case here.
2096 if (!MFI.getSavePoints().empty() && MFI.hasTailCall()) {
2097 assert(MFI.getRestorePoints().size() < 2 &&
2098 "MFI can't contain multiple restore points!");
2099 for (MachineBasicBlock &MBB : MF) {
2100 if (MBB.isReturnBlock() && (!MFI.getRestorePoints().contains(&MBB)))
2101 createTailCallBranchInstr(MBB);
2102 }
2103 }
2104
2105 // Early exit if no callee saved registers are modified!
2106 if (CSI.empty() && !needsFP(MF)) {
2107 addScavengingSpillSlot(MF, RS);
2108 return;
2109 }
2110
2111 unsigned MinGPR = PPC::R31;
2112 unsigned MinG8R = PPC::X31;
2113 unsigned MinFPR = PPC::F31;
2114 unsigned MinVR = Subtarget.hasSPE() ? PPC::S31 : PPC::V31;
2115
2116 bool HasGPSaveArea = false;
2117 bool HasG8SaveArea = false;
2118 bool HasFPSaveArea = false;
2119 bool HasVRSaveArea = false;
2120
2125
2126 for (const CalleeSavedInfo &I : CSI) {
2127 MCRegister Reg = I.getReg();
2129 (Reg != PPC::X2 && Reg != PPC::R2)) &&
2130 "Not expecting to try to spill R2 in a function that must save TOC");
2131 if (PPC::GPRCRegClass.contains(Reg)) {
2132 HasGPSaveArea = true;
2133
2134 GPRegs.push_back(I);
2135
2136 if (Reg < MinGPR) {
2137 MinGPR = Reg;
2138 }
2139 } else if (PPC::G8RCRegClass.contains(Reg)) {
2140 HasG8SaveArea = true;
2141
2142 G8Regs.push_back(I);
2143
2144 if (Reg < MinG8R) {
2145 MinG8R = Reg;
2146 }
2147 } else if (PPC::F8RCRegClass.contains(Reg)) {
2148 HasFPSaveArea = true;
2149
2150 FPRegs.push_back(I);
2151
2152 if (Reg < MinFPR) {
2153 MinFPR = Reg;
2154 }
2155 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
2156 PPC::CRRCRegClass.contains(Reg)) {
2157 ; // do nothing, as we already know whether CRs are spilled
2158 } else if (PPC::VRRCRegClass.contains(Reg) ||
2159 PPC::SPERCRegClass.contains(Reg)) {
2160 // Altivec and SPE are mutually exclusive, but have the same stack
2161 // alignment requirements, so overload the save area for both cases.
2162 HasVRSaveArea = true;
2163
2164 VRegs.push_back(I);
2165
2166 if (Reg < MinVR) {
2167 MinVR = Reg;
2168 }
2169 } else {
2170 llvm_unreachable("Unknown RegisterClass!");
2171 }
2172 }
2173
2175 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2176
2177 int64_t LowerBound = 0;
2178
2179 // Take into account stack space reserved for tail calls.
2180 int TCSPDelta = 0;
2182 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
2183 LowerBound = TCSPDelta;
2184 }
2185
2186 // The Floating-point register save area is right below the back chain word
2187 // of the previous stack frame.
2188 if (HasFPSaveArea) {
2189 for (const CalleeSavedInfo &FPReg : FPRegs) {
2190 int FI = FPReg.getFrameIdx();
2191
2192 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2193 }
2194
2195 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
2196 }
2197
2198 // Check whether the frame pointer register is allocated. If so, make sure it
2199 // is spilled to the correct offset.
2200 if (needsFP(MF)) {
2201 int FI = PFI->getFramePointerSaveIndex();
2202 assert(FI && "No Frame Pointer Save Slot!");
2203 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2204 // FP is R31/X31, so no need to update MinGPR/MinG8R.
2205 HasGPSaveArea = true;
2206 }
2207
2208 if (PFI->usesPICBase()) {
2209 int FI = PFI->getPICBasePointerSaveIndex();
2210 assert(FI && "No PIC Base Pointer Save Slot!");
2211 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2212
2213 MinGPR = std::min<unsigned>(MinGPR, PPC::R30);
2214 HasGPSaveArea = true;
2215 }
2216
2217 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
2218 if (RegInfo->hasBasePointer(MF)) {
2219 int FI = PFI->getBasePointerSaveIndex();
2220 assert(FI && "No Base Pointer Save Slot!");
2221 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2222
2223 Register BP = RegInfo->getBaseRegister(MF);
2224 if (PPC::G8RCRegClass.contains(BP)) {
2225 MinG8R = std::min<unsigned>(MinG8R, BP);
2226 HasG8SaveArea = true;
2227 } else if (PPC::GPRCRegClass.contains(BP)) {
2228 MinGPR = std::min<unsigned>(MinGPR, BP);
2229 HasGPSaveArea = true;
2230 }
2231 }
2232
2233 // General register save area starts right below the Floating-point
2234 // register save area.
2235 if (HasGPSaveArea || HasG8SaveArea) {
2236 // Move general register save area spill slots down, taking into account
2237 // the size of the Floating-point register save area.
2238 for (const CalleeSavedInfo &GPReg : GPRegs) {
2239 if (!GPReg.isSpilledToReg()) {
2240 int FI = GPReg.getFrameIdx();
2241 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2242 }
2243 }
2244
2245 // Move general register save area spill slots down, taking into account
2246 // the size of the Floating-point register save area.
2247 for (const CalleeSavedInfo &G8Reg : G8Regs) {
2248 if (!G8Reg.isSpilledToReg()) {
2249 int FI = G8Reg.getFrameIdx();
2250 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2251 }
2252 }
2253
2254 unsigned MinReg =
2255 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
2256 TRI->getEncodingValue(MinG8R));
2257
2258 const unsigned GPRegSize = Subtarget.isPPC64() ? 8 : 4;
2259 LowerBound -= (31 - MinReg + 1) * GPRegSize;
2260 }
2261
2262 // For 32-bit only, the CR save area is below the general register
2263 // save area. For 64-bit SVR4, the CR save area is addressed relative
2264 // to the stack pointer and hence does not need an adjustment here.
2265 // Only CR2 (the first nonvolatile spilled) has an associated frame
2266 // index so that we have a single uniform save area.
2267 if (spillsCR(MF) && Subtarget.is32BitELFABI()) {
2268 // Adjust the frame index of the CR spill slot.
2269 for (const auto &CSInfo : CSI) {
2270 if (CSInfo.getReg() == PPC::CR2) {
2271 int FI = CSInfo.getFrameIdx();
2272 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2273 break;
2274 }
2275 }
2276
2277 LowerBound -= 4; // The CR save area is always 4 bytes long.
2278 }
2279
2280 // Both Altivec and SPE have the same alignment and padding requirements
2281 // within the stack frame.
2282 if (HasVRSaveArea) {
2283 // Insert alignment padding, we need 16-byte alignment. Note: for positive
2284 // number the alignment formula is : y = (x + (n-1)) & (~(n-1)). But since
2285 // we are using negative number here (the stack grows downward). We should
2286 // use formula : y = x & (~(n-1)). Where x is the size before aligning, n
2287 // is the alignment size ( n = 16 here) and y is the size after aligning.
2288 assert(LowerBound <= 0 && "Expect LowerBound have a non-positive value!");
2289 LowerBound &= ~(15);
2290
2291 for (const CalleeSavedInfo &VReg : VRegs) {
2292 int FI = VReg.getFrameIdx();
2293
2294 MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2295 }
2296 }
2297
2298 addScavengingSpillSlot(MF, RS);
2299}
2300
2301void
2303 RegScavenger *RS) const {
2304 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
2305 // a large stack, which will require scavenging a register to materialize a
2306 // large offset.
2307
2308 // We need to have a scavenger spill slot for spills if the frame size is
2309 // large. In case there is no free register for large-offset addressing,
2310 // this slot is used for the necessary emergency spill. Also, we need the
2311 // slot for dynamic stack allocations.
2312
2313 // The scavenger might be invoked if the frame offset does not fit into
2314 // the 16-bit immediate in case of not SPE and 8-bit in case of SPE.
2315 // We don't know the complete frame size here because we've not yet computed
2316 // callee-saved register spills or the needed alignment padding.
2317 unsigned StackSize = determineFrameLayout(MF, true);
2318 MachineFrameInfo &MFI = MF.getFrameInfo();
2319 bool NeedSpills = Subtarget.hasSPE() ? !isInt<8>(StackSize) : !isInt<16>(StackSize);
2320
2321 if (MFI.hasVarSizedObjects() || spillsCR(MF) || hasNonRISpills(MF) ||
2322 (hasSpills(MF) && NeedSpills)) {
2323 const TargetRegisterClass &GPRC = PPC::GPRCRegClass;
2324 const TargetRegisterClass &G8RC = PPC::G8RCRegClass;
2325 const TargetRegisterClass &RC = Subtarget.isPPC64() ? G8RC : GPRC;
2326 const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();
2327 unsigned Size = TRI.getSpillSize(RC);
2328 Align Alignment = TRI.getSpillAlign(RC);
2329 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(Size, Alignment));
2330
2331 // Might we have over-aligned allocas?
2332 bool HasAlVars =
2333 MFI.hasVarSizedObjects() && MFI.getMaxAlign() > getStackAlign();
2334
2335 // These kinds of spills might need two registers.
2336 if (spillsCR(MF) || HasAlVars)
2337 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(Size, Alignment));
2338 }
2339}
2340
2341// This function checks if a callee saved gpr can be spilled to a volatile
2342// vector register. This occurs for leaf functions when the option
2343// ppc-enable-pe-vector-spills is enabled. If there are any remaining registers
2344// which were not spilled to vectors, return false so the target independent
2345// code can handle them by assigning a FrameIdx to a stack slot.
2348 std::vector<CalleeSavedInfo> &CSI) const {
2349
2350 if (CSI.empty())
2351 return true; // Early exit if no callee saved registers are modified!
2352
2353 const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
2354 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
2355 const MachineRegisterInfo &MRI = MF.getRegInfo();
2356
2357 if (Subtarget.hasSPE()) {
2358 // In case of SPE we only have SuperRegs and CRs
2359 // in our CalleSaveInfo vector.
2360
2361 for (auto &CalleeSaveReg : CSI) {
2362 MCRegister Reg = CalleeSaveReg.getReg();
2363 MCRegister Lower = RegInfo->getSubReg(Reg, PPC::sub_32);
2364 MCRegister Higher = RegInfo->getSubReg(Reg, PPC::sub_32_hi_phony);
2365
2366 if ( // Check only for SuperRegs.
2367 Lower &&
2368 // Replace Reg if only lower-32 bits modified
2369 !MRI.isPhysRegModified(Higher))
2370 CalleeSaveReg = CalleeSavedInfo(Lower);
2371 }
2372 }
2373
2374 // Early exit if cannot spill gprs to volatile vector registers.
2375 MachineFrameInfo &MFI = MF.getFrameInfo();
2376 if (!EnablePEVectorSpills || MFI.hasCalls() || !Subtarget.hasP9Vector())
2377 return false;
2378
2379 // Build a BitVector of VSRs that can be used for spilling GPRs.
2380 BitVector BVAllocatable = TRI->getAllocatableSet(MF);
2381 BitVector BVCalleeSaved(TRI->getNumRegs());
2382 for (unsigned i = 0; CSRegs[i]; ++i)
2383 BVCalleeSaved.set(CSRegs[i]);
2384
2385 for (unsigned Reg : BVAllocatable.set_bits()) {
2386 // Set to 0 if the register is not a volatile VSX register, or if it is
2387 // used in the function.
2388 if (BVCalleeSaved[Reg] || !PPC::VSRCRegClass.contains(Reg) ||
2389 MRI.isPhysRegUsed(Reg))
2390 BVAllocatable.reset(Reg);
2391 }
2392
2393 bool AllSpilledToReg = true;
2394 unsigned LastVSRUsedForSpill = 0;
2395 for (auto &CS : CSI) {
2396 if (BVAllocatable.none())
2397 return false;
2398
2399 MCRegister Reg = CS.getReg();
2400
2401 if (!PPC::G8RCRegClass.contains(Reg)) {
2402 AllSpilledToReg = false;
2403 continue;
2404 }
2405
2406 // For P9, we can reuse LastVSRUsedForSpill to spill two GPRs
2407 // into one VSR using the mtvsrdd instruction.
2408 if (LastVSRUsedForSpill != 0) {
2409 CS.setDstReg(LastVSRUsedForSpill);
2410 BVAllocatable.reset(LastVSRUsedForSpill);
2411 LastVSRUsedForSpill = 0;
2412 continue;
2413 }
2414
2415 unsigned VolatileVFReg = BVAllocatable.find_first();
2416 if (VolatileVFReg < BVAllocatable.size()) {
2417 CS.setDstReg(VolatileVFReg);
2418 LastVSRUsedForSpill = VolatileVFReg;
2419 } else {
2420 AllSpilledToReg = false;
2421 }
2422 }
2423 return AllSpilledToReg;
2424}
2425
2429
2430 MachineFunction *MF = MBB.getParent();
2431 const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
2433 bool MustSaveTOC = FI->mustSaveTOC();
2434 DebugLoc DL;
2435 bool CRSpilled = false;
2436 MachineInstrBuilder CRMIB;
2437 BitVector Spilled(TRI->getNumRegs());
2438
2439 VSRContainingGPRs.clear();
2440
2441 // Map each VSR to GPRs to be spilled with into it. Single VSR can contain one
2442 // or two GPRs, so we need table to record information for later save/restore.
2443 for (const CalleeSavedInfo &Info : CSI) {
2444 if (Info.isSpilledToReg()) {
2445 auto &SpilledVSR = VSRContainingGPRs[Info.getDstReg()];
2446 assert(SpilledVSR.second == 0 &&
2447 "Can't spill more than two GPRs into VSR!");
2448 if (SpilledVSR.first == 0)
2449 SpilledVSR.first = Info.getReg();
2450 else
2451 SpilledVSR.second = Info.getReg();
2452 }
2453 }
2454
2455 for (const CalleeSavedInfo &I : CSI) {
2456 MCRegister Reg = I.getReg();
2457
2458 // CR2 through CR4 are the nonvolatile CR fields.
2459 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
2460
2461 // Add the callee-saved register as live-in; it's killed at the spill.
2462 // Do not do this for callee-saved registers that are live-in to the
2463 // function because they will already be marked live-in and this will be
2464 // adding it for a second time. It is an error to add the same register
2465 // to the set more than once.
2466 const MachineRegisterInfo &MRI = MF->getRegInfo();
2467 bool IsLiveIn = MRI.isLiveIn(Reg);
2468 if (!IsLiveIn)
2469 MBB.addLiveIn(Reg);
2470
2471 if (CRSpilled && IsCRField) {
2472 CRMIB.addReg(Reg, RegState::ImplicitKill);
2473 continue;
2474 }
2475
2476 // The actual spill will happen in the prologue.
2477 if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
2478 continue;
2479
2480 // Insert the spill to the stack frame.
2481 if (IsCRField) {
2482 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
2483 if (!Subtarget.is32BitELFABI()) {
2484 // The actual spill will happen at the start of the prologue.
2485 FuncInfo->addMustSaveCR(Reg);
2486 } else {
2487 CRSpilled = true;
2488 FuncInfo->setSpillsCR();
2489
2490 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
2491 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
2492 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
2494
2495 MBB.insert(MI, CRMIB);
2496 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
2497 .addReg(PPC::R12,
2498 getKillRegState(true)),
2499 I.getFrameIdx()));
2500 }
2501 } else {
2502 if (I.isSpilledToReg()) {
2503 unsigned Dst = I.getDstReg();
2504
2505 if (Spilled[Dst])
2506 continue;
2507
2508 const auto &VSR = VSRContainingGPRs[Dst];
2509 if (VSR.second != 0) {
2510 assert(Subtarget.hasP9Vector() &&
2511 "mtvsrdd is unavailable on pre-P9 targets.");
2512
2513 NumPESpillVSR += 2;
2514 BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRDD), Dst)
2515 .addReg(VSR.first, getKillRegState(true))
2516 .addReg(VSR.second, getKillRegState(true));
2517 } else if (VSR.second == 0) {
2518 assert(Subtarget.hasP8Vector() &&
2519 "Can't move GPR to VSR on pre-P8 targets.");
2520
2521 ++NumPESpillVSR;
2522 BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRD),
2523 TRI->getSubReg(Dst, PPC::sub_64))
2524 .addReg(VSR.first, getKillRegState(true));
2525 } else {
2526 llvm_unreachable("More than two GPRs spilled to a VSR!");
2527 }
2528 Spilled.set(Dst);
2529 } else {
2530 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2531 // Use !IsLiveIn for the kill flag.
2532 // We do not want to kill registers that are live in this function
2533 // before their use because they will become undefined registers.
2534 // Functions without NoUnwind need to preserve the order of elements in
2535 // saved vector registers.
2536 if (Subtarget.needsSwapsForVSXMemOps() &&
2537 !MF->getFunction().hasFnAttribute(Attribute::NoUnwind))
2538 TII.storeRegToStackSlotNoUpd(MBB, MI, Reg, !IsLiveIn, I.getFrameIdx(),
2539 RC);
2540 else
2541 TII.storeRegToStackSlot(MBB, MI, Reg, !IsLiveIn, I.getFrameIdx(), RC,
2542 Register());
2543 }
2544 }
2545 }
2546 return true;
2547}
2548
2549static void restoreCRs(bool is31, bool CR2Spilled, bool CR3Spilled,
2550 bool CR4Spilled, MachineBasicBlock &MBB,
2552 ArrayRef<CalleeSavedInfo> CSI, unsigned CSIIndex) {
2553
2554 MachineFunction *MF = MBB.getParent();
2555 const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
2556 DebugLoc DL;
2557 unsigned MoveReg = PPC::R12;
2558
2559 // 32-bit: FP-relative
2560 MBB.insert(MI,
2561 addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ), MoveReg),
2562 CSI[CSIIndex].getFrameIdx()));
2563 // Count how many CR fields need restoring
2564 unsigned NumCRs =
2565 (CR2Spilled ? 1 : 0) + (CR3Spilled ? 1 : 0) + (CR4Spilled ? 1 : 0);
2566
2567 assert(NumCRs >= 1 &&
2568 "Requires at least one non-volatile CR field to be restored.");
2569
2570 if (NumCRs == 1) {
2571 // Use MTOCRF for single CR field
2572 unsigned CRReg = CR2Spilled ? PPC::CR2 : (CR3Spilled ? PPC::CR3 : PPC::CR4);
2573 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::MTOCRF), CRReg)
2574 .addReg(MoveReg, getKillRegState(true)));
2575 } else {
2576 // Use MTCRF for multiple CR fields.
2577 unsigned CRMask = 0;
2578 if (CR2Spilled)
2579 CRMask |= 0x20;
2580 if (CR3Spilled)
2581 CRMask |= 0x10;
2582 if (CR4Spilled)
2583 CRMask |= 0x08;
2584 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::MTCRF))
2585 .addImm(CRMask)
2586 .addReg(MoveReg, getKillRegState(true)));
2587 }
2588}
2589
2593 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2595 I->getOpcode() == PPC::ADJCALLSTACKUP) {
2596 // Add (actually subtract) back the amount the callee popped on return.
2597 if (int CalleeAmt = I->getOperand(1).getImm()) {
2598 bool is64Bit = Subtarget.isPPC64();
2599 CalleeAmt *= -1;
2600 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
2601 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
2602 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
2603 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
2604 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
2605 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
2606 const DebugLoc &dl = I->getDebugLoc();
2607
2608 if (isInt<16>(CalleeAmt)) {
2609 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
2610 .addReg(StackReg, RegState::Kill)
2611 .addImm(CalleeAmt);
2612 } else {
2614 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
2615 .addImm(CalleeAmt >> 16);
2616 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
2617 .addReg(TmpReg, RegState::Kill)
2618 .addImm(CalleeAmt & 0xFFFF);
2619 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
2620 .addReg(StackReg, RegState::Kill)
2621 .addReg(TmpReg);
2622 }
2623 }
2624 }
2625 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
2626 return MBB.erase(I);
2627}
2628
2629static bool isCalleeSavedCR(unsigned Reg) {
2630 return PPC::CR2 == Reg || Reg == PPC::CR3 || Reg == PPC::CR4;
2631}
2632
2636 MachineFunction *MF = MBB.getParent();
2637 const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
2639 bool MustSaveTOC = FI->mustSaveTOC();
2640 bool CR2Spilled = false;
2641 bool CR3Spilled = false;
2642 bool CR4Spilled = false;
2643 unsigned CSIIndex = 0;
2644 BitVector Restored(TRI->getNumRegs());
2645
2646 // Initialize insertion-point logic; we will be restoring in reverse
2647 // order of spill.
2648 MachineBasicBlock::iterator I = MI, BeforeI = I;
2649 bool AtStart = I == MBB.begin();
2650
2651 if (!AtStart)
2652 --BeforeI;
2653
2654 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
2655 MCRegister Reg = CSI[i].getReg();
2656
2657 if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
2658 continue;
2659
2660 // Restore of callee saved condition register field is handled during
2661 // epilogue insertion.
2662 if (isCalleeSavedCR(Reg) && !Subtarget.is32BitELFABI())
2663 continue;
2664
2665 if (Reg == PPC::CR2) {
2666 CR2Spilled = true;
2667 // The spill slot is associated only with CR2, which is the
2668 // first nonvolatile spilled. Save it here.
2669 CSIIndex = i;
2670 continue;
2671 } else if (Reg == PPC::CR3) {
2672 CR3Spilled = true;
2673 continue;
2674 } else if (Reg == PPC::CR4) {
2675 CR4Spilled = true;
2676 continue;
2677 } else {
2678 // On 32-bit ELF when we first encounter a non-CR register after seeing at
2679 // least one CR register, restore all spilled CRs together.
2680 if (CR2Spilled || CR3Spilled || CR4Spilled) {
2681 bool is31 = needsFP(*MF);
2682 restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI,
2683 CSIIndex);
2684 CR2Spilled = CR3Spilled = CR4Spilled = false;
2685 }
2686
2687 if (CSI[i].isSpilledToReg()) {
2688 DebugLoc DL;
2689 unsigned Dst = CSI[i].getDstReg();
2690
2691 if (Restored[Dst])
2692 continue;
2693
2694 const auto &VSR = VSRContainingGPRs[Dst];
2695 if (VSR.second != 0) {
2696 assert(Subtarget.hasP9Vector());
2697 NumPEReloadVSR += 2;
2698 BuildMI(MBB, I, DL, TII.get(PPC::MFVSRLD), VSR.second).addReg(Dst);
2699 BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD), VSR.first)
2700 .addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));
2701 } else if (VSR.second == 0) {
2702 assert(Subtarget.hasP8Vector());
2703 ++NumPEReloadVSR;
2704 BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD), VSR.first)
2705 .addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));
2706 } else {
2707 llvm_unreachable("More than two GPRs spilled to a VSR!");
2708 }
2709
2710 Restored.set(Dst);
2711
2712 } else {
2713 // Default behavior for non-CR saves.
2714 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2715
2716 // Functions without NoUnwind need to preserve the order of elements in
2717 // saved vector registers.
2718 if (Subtarget.needsSwapsForVSXMemOps() &&
2719 !MF->getFunction().hasFnAttribute(Attribute::NoUnwind))
2720 TII.loadRegFromStackSlotNoUpd(MBB, I, Reg, CSI[i].getFrameIdx(), RC);
2721 else
2722 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(), RC,
2723 Register());
2724
2725 assert(I != MBB.begin() &&
2726 "loadRegFromStackSlot didn't insert any code!");
2727 }
2728 }
2729
2730 // Insert in reverse order.
2731 if (AtStart)
2732 I = MBB.begin();
2733 else {
2734 I = BeforeI;
2735 ++I;
2736 }
2737 }
2738
2739 // If we haven't yet spilled the CRs, do so now.
2740 if (CR2Spilled || CR3Spilled || CR4Spilled) {
2741 assert(Subtarget.is32BitELFABI() &&
2742 "Only set CR[2|3|4]Spilled on 32-bit SVR4.");
2743 bool is31 = needsFP(*MF);
2744 restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI, CSIIndex);
2745 }
2746
2747 return true;
2748}
2749
2751 return TOCSaveOffset;
2752}
2753
2755 return FramePointerSaveOffset;
2756}
2757
2759 return BasePointerSaveOffset;
2760}
2761
2764 return false;
2765 return !MF.getSubtarget<PPCSubtarget>().is32BitELFABI();
2766}
2767
2769 BitVector &SavedRegs) const {
2770 // The AIX ABI uses traceback tables for EH which require that if callee-saved
2771 // register N is used, all registers N-31 must be saved/restored.
2772 // NOTE: The check for AIX is not actually what is relevant. Traceback tables
2773 // on Linux have the same requirements. It is just that AIX is the only ABI
2774 // for which we actually use traceback tables. If another ABI needs to be
2775 // supported that also uses them, we can add a check such as
2776 // Subtarget.usesTraceBackTables().
2777 assert(Subtarget.isAIXABI() &&
2778 "Function updateCalleeSaves should only be called for AIX.");
2779
2780 // If there are no callee saves then there is nothing to do.
2781 if (SavedRegs.none())
2782 return;
2783
2784 const MCPhysReg *CSRegs =
2785 Subtarget.getRegisterInfo()->getCalleeSavedRegs(&MF);
2786 MCPhysReg LowestGPR = PPC::R31;
2787 MCPhysReg LowestG8R = PPC::X31;
2788 MCPhysReg LowestFPR = PPC::F31;
2789 MCPhysReg LowestVR = PPC::V31;
2790
2791 // Traverse the CSRs twice so as not to rely on ascending ordering of
2792 // registers in the array. The first pass finds the lowest numbered
2793 // register and the second pass marks all higher numbered registers
2794 // for spilling.
2795 for (int i = 0; CSRegs[i]; i++) {
2796 // Get the lowest numbered register for each class that actually needs
2797 // to be saved.
2798 MCPhysReg Cand = CSRegs[i];
2799 if (!SavedRegs.test(Cand))
2800 continue;
2801 // When R2/X2 is a CSR and not used for passing arguments, it is allocated
2802 // earlier than other volatile registers. R2/X2 is not contiguous with
2803 // R13/X13 to R31/X31.
2804 if (Cand == PPC::X2 || Cand == PPC::R2) {
2805 SavedRegs.set(Cand);
2806 continue;
2807 }
2808
2809 if (PPC::GPRCRegClass.contains(Cand) && Cand < LowestGPR)
2810 LowestGPR = Cand;
2811 else if (PPC::G8RCRegClass.contains(Cand) && Cand < LowestG8R)
2812 LowestG8R = Cand;
2813 else if ((PPC::F4RCRegClass.contains(Cand) ||
2814 PPC::F8RCRegClass.contains(Cand)) &&
2815 Cand < LowestFPR)
2816 LowestFPR = Cand;
2817 else if (PPC::VRRCRegClass.contains(Cand) && Cand < LowestVR)
2818 LowestVR = Cand;
2819 }
2820
2821 for (int i = 0; CSRegs[i]; i++) {
2822 MCPhysReg Cand = CSRegs[i];
2823 if ((PPC::GPRCRegClass.contains(Cand) && Cand > LowestGPR) ||
2824 (PPC::G8RCRegClass.contains(Cand) && Cand > LowestG8R) ||
2825 ((PPC::F4RCRegClass.contains(Cand) ||
2826 PPC::F8RCRegClass.contains(Cand)) &&
2827 Cand > LowestFPR) ||
2828 (PPC::VRRCRegClass.contains(Cand) && Cand > LowestVR))
2829 SavedRegs.set(Cand);
2830 }
2831}
2832
2834 // On PPC64, we use `stux r1, r1, <scratch_reg>` to extend the stack;
2835 // use `add r1, r1, <scratch_reg>` to release the stack frame.
2836 // Scratch register contains a signed 64-bit number, which is negative
2837 // when extending the stack and is positive when releasing the stack frame.
2838 // To make `stux` and `add` paired, the absolute value of the number contained
2839 // in the scratch register should be the same. Thus the maximum stack size
2840 // is (2^63)-1, i.e., INT64_MAX.
2841 if (Subtarget.isPPC64())
2842 return INT64_MAX;
2843
2845}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static LVOptions Options
Definition LVOptions.cpp:25
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static bool MustSaveLR(const MachineFunction &MF, MCRegister LR)
MustSaveLR - Return true if this function requires that we save the LR register onto the stack in the...
#define CALLEE_SAVED_VRS
static bool hasSpills(const MachineFunction &MF)
static unsigned computeCRSaveOffset(const PPCSubtarget &STI)
static void restoreCRs(bool is31, bool CR2Spilled, bool CR3Spilled, bool CR4Spilled, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, unsigned CSIIndex)
static unsigned computeReturnSaveOffset(const PPCSubtarget &STI)
#define CALLEE_SAVED_FPRS
static cl::opt< bool > EnablePEVectorSpills("ppc-enable-pe-vector-spills", cl::desc("Enable spills in prologue to vector registers."), cl::init(false), cl::Hidden)
#define CALLEE_SAVED_GPRS32
#define CALLEE_SAVED_GPRS64
static unsigned computeLinkageSize(const PPCSubtarget &STI)
static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI)
static bool isCalleeSavedCR(unsigned Reg)
static unsigned computeTOCSaveOffset(const PPCSubtarget &STI)
static bool hasNonRISpills(const MachineFunction &MF)
static bool spillsCR(const MachineFunction &MF)
static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI)
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static void buildDefCFAReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned Reg, const SystemZInstrInfo *ZII)
static bool is64Bit(const char *name)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:317
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:181
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:324
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:207
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition DebugLoc.h:126
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
An instruction for reading from memory.
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition MCDwarf.h:635
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2, SMLoc Loc={})
.cfi_register Previous value of Register1 is saved in register Register2.
Definition MCDwarf.h:685
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:628
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:670
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:643
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:411
Describe properties that are true of each instruction in the target description file.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
virtual int64_t getDwarfRegNum(MCRegister Reg, bool isEH) const
Map a target register to an equivalent dwarf register number.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
bool hasCalls() const
Return true if the current function has any function calls.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
bool hasPatchPoint() const
This method may be called any time after instruction selection is complete to determine if there is a...
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
bool hasTailCall() const
Returns true if the function contains a tail call.
bool hasStackMap() const
This method may be called any time after instruction selection is complete to determine if there is a...
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
const SaveRestorePoints & getRestorePoints() const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
const SaveRestorePoints & getSavePoints() const
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
LLVM_ABI bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
const char * getSymbolName() const
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
def_iterator def_begin(Register RegNo) const
LLVM_ABI bool isLiveIn(Register Reg) const
defusechain_iterator< false, true, false, true, false > def_iterator
def_iterator/def_begin/def_end - Walk all defs of the specified register.
static def_iterator def_end()
LLVM_ABI bool isPhysRegModified(MCRegister PhysReg, bool SkipNoReturnDef=false) const
Return true if the specified register is modified in this function.
LLVM_ABI bool isPhysRegUsed(MCRegister PhysReg, bool SkipRegMaskTest=false) const
Return true if the specified register is modified or read in this function.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
uint64_t getReturnSaveOffset() const
getReturnSaveOffset - Return the previous frame offset to save the return address.
bool needsFP(const MachineFunction &MF) const
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a epilogue for the target.
uint64_t getStackThreshold() const override
getStackThreshold - Return the maximum stack size
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool hasFPImpl(const MachineFunction &MF) const override
uint64_t getFramePointerSaveOffset() const
getFramePointerSaveOffset - Return the previous frame offset to save the frame pointer.
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
unsigned getLinkageSize() const
getLinkageSize - Return the size of the PowerPC ABI linkage area.
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const override
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
bool canUseAsPrologue(const MachineBasicBlock &MBB) const override
Methods used by shrink wrapping to determine if MBB can be used for the function prologue/epilogue.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
void replaceFPWithRealFP(MachineFunction &MF) const
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
uint64_t determineFrameLayout(const MachineFunction &MF, bool UseEstimate=false, unsigned *NewMaxCallFrameSize=nullptr) const
Determine the frame layout but do not update the machine function.
void addScavengingSpillSlot(MachineFunction &MF, RegScavenger *RS) const
PPCFrameLowering(const PPCSubtarget &STI)
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
This function will assign callee saved gprs to volatile vector registers for prologue spills when app...
uint64_t determineFrameLayoutAndUpdate(MachineFunction &MF, bool UseEstimate=false) const
Determine the frame layout and update the machine function.
void updateCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const
void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologMBB) const override
Replace a StackProbe stub (if any) with the actual probe code inline.
uint64_t getTOCSaveOffset() const
getTOCSaveOffset - Return the previous frame offset to save the TOC register – 64-bit SVR4 ABI only.
uint64_t getBasePointerSaveOffset() const
getBasePointerSaveOffset - Return the previous frame offset to save the base pointer.
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
const SmallVectorImpl< Register > & getMustSaveCRs() const
void addMustSaveCR(Register Reg)
unsigned getMinReservedArea() const
void setMustSaveLR(bool U)
MustSaveLR - This is set when the prolog/epilog inserter does its initial scan of the function.
bool hasBasePointer(const MachineFunction &MF) const
const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const override
Code Generation virtual methods...
bool is32BitELFABI() const
bool isAIXABI() const
const PPCInstrInfo * getInstrInfo() const override
unsigned getRedZoneSize() const
bool isELFv2ABI() const
const PPCTargetMachine & getTargetMachine() const
const PPCRegisterInfo * getRegisterInfo() const override
bool hasInlineStackProbe(const MachineFunction &MF) const override
unsigned getStackProbeSize(const MachineFunction &MF) const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual uint64_t getStackThreshold() const
getStackThreshold - Return the maximum stack size
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
bool isPositionIndependent() const
TargetOptions Options
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
self_iterator getIterator()
Definition ilist_node.h:123
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Kill
The last use of a register.
constexpr RegState getKillRegState(bool B)
static const MachineInstrBuilder & addFrameReference(const MachineInstrBuilder &MIB, int FI, int Offset=0, bool mem=true)
addFrameReference - This function is used to add a reference to the base of an abstract object on the...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39