Path: blob/main/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCFrameLowering.cpp
35266 views
//===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains the PPC implementation of TargetFrameLowering class.9//10//===----------------------------------------------------------------------===//1112#include "PPCFrameLowering.h"13#include "MCTargetDesc/PPCPredicates.h"14#include "PPCInstrBuilder.h"15#include "PPCInstrInfo.h"16#include "PPCMachineFunctionInfo.h"17#include "PPCSubtarget.h"18#include "PPCTargetMachine.h"19#include "llvm/ADT/Statistic.h"20#include "llvm/CodeGen/LivePhysRegs.h"21#include "llvm/CodeGen/MachineFrameInfo.h"22#include "llvm/CodeGen/MachineFunction.h"23#include "llvm/CodeGen/MachineInstrBuilder.h"24#include "llvm/CodeGen/MachineModuleInfo.h"25#include "llvm/CodeGen/MachineRegisterInfo.h"26#include "llvm/CodeGen/RegisterScavenging.h"27#include "llvm/IR/Function.h"28#include "llvm/Target/TargetOptions.h"2930using namespace llvm;3132#define DEBUG_TYPE "framelowering"33STATISTIC(NumPESpillVSR, "Number of spills to vector in prologue");34STATISTIC(NumPEReloadVSR, "Number of reloads from vector in epilogue");35STATISTIC(NumPrologProbed, "Number of prologues probed");3637static cl::opt<bool>38EnablePEVectorSpills("ppc-enable-pe-vector-spills",39cl::desc("Enable spills in prologue to vector registers."),40cl::init(false), cl::Hidden);4142static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {43if (STI.isAIXABI())44return STI.isPPC64() ? 16 : 8;45// SVR4 ABI:46return STI.isPPC64() ? 16 : 4;47}4849static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {50if (STI.isAIXABI())51return STI.isPPC64() ? 40 : 20;52return STI.isELFv2ABI() ? 24 : 40;53}5455static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {56// First slot in the general register save area.57return STI.isPPC64() ? -8U : -4U;58}5960static unsigned computeLinkageSize(const PPCSubtarget &STI) {61if (STI.isAIXABI() || STI.isPPC64())62return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);6364// 32-bit SVR4 ABI:65return 8;66}6768static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {69// Third slot in the general purpose register save area.70if (STI.is32BitELFABI() && STI.getTargetMachine().isPositionIndependent())71return -12U;7273// Second slot in the general purpose register save area.74return STI.isPPC64() ? -16U : -8U;75}7677static unsigned computeCRSaveOffset(const PPCSubtarget &STI) {78return (STI.isAIXABI() && !STI.isPPC64()) ? 4 : 8;79}8081PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)82: TargetFrameLowering(TargetFrameLowering::StackGrowsDown,83STI.getPlatformStackAlignment(), 0),84Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),85TOCSaveOffset(computeTOCSaveOffset(Subtarget)),86FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),87LinkageSize(computeLinkageSize(Subtarget)),88BasePointerSaveOffset(computeBasePointerSaveOffset(Subtarget)),89CRSaveOffset(computeCRSaveOffset(Subtarget)) {}9091// With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.92const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(93unsigned &NumEntries) const {9495// Floating-point register save area offsets.96#define CALLEE_SAVED_FPRS \97{PPC::F31, -8}, \98{PPC::F30, -16}, \99{PPC::F29, -24}, \100{PPC::F28, -32}, \101{PPC::F27, -40}, \102{PPC::F26, -48}, \103{PPC::F25, -56}, \104{PPC::F24, -64}, \105{PPC::F23, -72}, \106{PPC::F22, -80}, \107{PPC::F21, -88}, \108{PPC::F20, -96}, \109{PPC::F19, -104}, \110{PPC::F18, -112}, \111{PPC::F17, -120}, \112{PPC::F16, -128}, \113{PPC::F15, -136}, \114{PPC::F14, -144}115116// 32-bit general purpose register save area offsets shared by ELF and117// AIX. AIX has an extra CSR with r13.118#define CALLEE_SAVED_GPRS32 \119{PPC::R31, -4}, \120{PPC::R30, -8}, \121{PPC::R29, -12}, \122{PPC::R28, -16}, \123{PPC::R27, -20}, \124{PPC::R26, -24}, \125{PPC::R25, -28}, \126{PPC::R24, -32}, \127{PPC::R23, -36}, \128{PPC::R22, -40}, \129{PPC::R21, -44}, \130{PPC::R20, -48}, \131{PPC::R19, -52}, \132{PPC::R18, -56}, \133{PPC::R17, -60}, \134{PPC::R16, -64}, \135{PPC::R15, -68}, \136{PPC::R14, -72}137138// 64-bit general purpose register save area offsets.139#define CALLEE_SAVED_GPRS64 \140{PPC::X31, -8}, \141{PPC::X30, -16}, \142{PPC::X29, -24}, \143{PPC::X28, -32}, \144{PPC::X27, -40}, \145{PPC::X26, -48}, \146{PPC::X25, -56}, \147{PPC::X24, -64}, \148{PPC::X23, -72}, \149{PPC::X22, -80}, \150{PPC::X21, -88}, \151{PPC::X20, -96}, \152{PPC::X19, -104}, \153{PPC::X18, -112}, \154{PPC::X17, -120}, \155{PPC::X16, -128}, \156{PPC::X15, -136}, \157{PPC::X14, -144}158159// Vector register save area offsets.160#define CALLEE_SAVED_VRS \161{PPC::V31, -16}, \162{PPC::V30, -32}, \163{PPC::V29, -48}, \164{PPC::V28, -64}, \165{PPC::V27, -80}, \166{PPC::V26, -96}, \167{PPC::V25, -112}, \168{PPC::V24, -128}, \169{PPC::V23, -144}, \170{PPC::V22, -160}, \171{PPC::V21, -176}, \172{PPC::V20, -192}173174// Note that the offsets here overlap, but this is fixed up in175// processFunctionBeforeFrameFinalized.176177static const SpillSlot ELFOffsets32[] = {178CALLEE_SAVED_FPRS,179CALLEE_SAVED_GPRS32,180181// CR save area offset. We map each of the nonvolatile CR fields182// to the slot for CR2, which is the first of the nonvolatile CR183// fields to be assigned, so that we only allocate one save slot.184// See PPCRegisterInfo::hasReservedSpillSlot() for more information.185{PPC::CR2, -4},186187// VRSAVE save area offset.188{PPC::VRSAVE, -4},189190CALLEE_SAVED_VRS,191192// SPE register save area (overlaps Vector save area).193{PPC::S31, -8},194{PPC::S30, -16},195{PPC::S29, -24},196{PPC::S28, -32},197{PPC::S27, -40},198{PPC::S26, -48},199{PPC::S25, -56},200{PPC::S24, -64},201{PPC::S23, -72},202{PPC::S22, -80},203{PPC::S21, -88},204{PPC::S20, -96},205{PPC::S19, -104},206{PPC::S18, -112},207{PPC::S17, -120},208{PPC::S16, -128},209{PPC::S15, -136},210{PPC::S14, -144}};211212static const SpillSlot ELFOffsets64[] = {213CALLEE_SAVED_FPRS,214CALLEE_SAVED_GPRS64,215216// VRSAVE save area offset.217{PPC::VRSAVE, -4},218CALLEE_SAVED_VRS219};220221static const SpillSlot AIXOffsets32[] = {CALLEE_SAVED_FPRS,222CALLEE_SAVED_GPRS32,223// Add AIX's extra CSR.224{PPC::R13, -76},225CALLEE_SAVED_VRS};226227static const SpillSlot AIXOffsets64[] = {228CALLEE_SAVED_FPRS, CALLEE_SAVED_GPRS64, CALLEE_SAVED_VRS};229230if (Subtarget.is64BitELFABI()) {231NumEntries = std::size(ELFOffsets64);232return ELFOffsets64;233}234235if (Subtarget.is32BitELFABI()) {236NumEntries = std::size(ELFOffsets32);237return ELFOffsets32;238}239240assert(Subtarget.isAIXABI() && "Unexpected ABI.");241242if (Subtarget.isPPC64()) {243NumEntries = std::size(AIXOffsets64);244return AIXOffsets64;245}246247NumEntries = std::size(AIXOffsets32);248return AIXOffsets32;249}250251static bool spillsCR(const MachineFunction &MF) {252const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();253return FuncInfo->isCRSpilled();254}255256static bool hasSpills(const MachineFunction &MF) {257const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();258return FuncInfo->hasSpills();259}260261static bool hasNonRISpills(const MachineFunction &MF) {262const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();263return FuncInfo->hasNonRISpills();264}265266/// MustSaveLR - Return true if this function requires that we save the LR267/// register onto the stack in the prolog and restore it in the epilog of the268/// function.269static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {270const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();271272// We need a save/restore of LR if there is any def of LR (which is273// defined by calls, including the PIC setup sequence), or if there is274// some use of the LR stack slot (e.g. for builtin_return_address).275// (LR comes in 32 and 64 bit versions.)276MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);277return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();278}279280/// determineFrameLayoutAndUpdate - Determine the size of the frame and maximum281/// call frame size. Update the MachineFunction object with the stack size.282uint64_t283PPCFrameLowering::determineFrameLayoutAndUpdate(MachineFunction &MF,284bool UseEstimate) const {285unsigned NewMaxCallFrameSize = 0;286uint64_t FrameSize = determineFrameLayout(MF, UseEstimate,287&NewMaxCallFrameSize);288MF.getFrameInfo().setStackSize(FrameSize);289MF.getFrameInfo().setMaxCallFrameSize(NewMaxCallFrameSize);290return FrameSize;291}292293/// determineFrameLayout - Determine the size of the frame and maximum call294/// frame size.295uint64_t296PPCFrameLowering::determineFrameLayout(const MachineFunction &MF,297bool UseEstimate,298unsigned *NewMaxCallFrameSize) const {299const MachineFrameInfo &MFI = MF.getFrameInfo();300const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();301302// Get the number of bytes to allocate from the FrameInfo303uint64_t FrameSize =304UseEstimate ? MFI.estimateStackSize(MF) : MFI.getStackSize();305306// Get stack alignments. The frame must be aligned to the greatest of these:307Align TargetAlign = getStackAlign(); // alignment required per the ABI308Align MaxAlign = MFI.getMaxAlign(); // algmt required by data in frame309Align Alignment = std::max(TargetAlign, MaxAlign);310311const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();312313unsigned LR = RegInfo->getRARegister();314bool DisableRedZone = MF.getFunction().hasFnAttribute(Attribute::NoRedZone);315bool CanUseRedZone = !MFI.hasVarSizedObjects() && // No dynamic alloca.316!MFI.adjustsStack() && // No calls.317!MustSaveLR(MF, LR) && // No need to save LR.318!FI->mustSaveTOC() && // No need to save TOC.319!RegInfo->hasBasePointer(MF) && // No special alignment.320!MFI.isFrameAddressTaken();321322// Note: for PPC32 SVR4ABI, we can still generate stackless323// code if all local vars are reg-allocated.324bool FitsInRedZone = FrameSize <= Subtarget.getRedZoneSize();325326// Check whether we can skip adjusting the stack pointer (by using red zone)327if (!DisableRedZone && CanUseRedZone && FitsInRedZone) {328// No need for frame329return 0;330}331332// Get the maximum call frame size of all the calls.333unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();334335// Maximum call frame needs to be at least big enough for linkage area.336unsigned minCallFrameSize = getLinkageSize();337maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);338339// If we have dynamic alloca then maxCallFrameSize needs to be aligned so340// that allocations will be aligned.341if (MFI.hasVarSizedObjects())342maxCallFrameSize = alignTo(maxCallFrameSize, Alignment);343344// Update the new max call frame size if the caller passes in a valid pointer.345if (NewMaxCallFrameSize)346*NewMaxCallFrameSize = maxCallFrameSize;347348// Include call frame size in total.349FrameSize += maxCallFrameSize;350351// Make sure the frame is aligned.352FrameSize = alignTo(FrameSize, Alignment);353354return FrameSize;355}356357// hasFP - Return true if the specified function actually has a dedicated frame358// pointer register.359bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {360const MachineFrameInfo &MFI = MF.getFrameInfo();361// FIXME: This is pretty much broken by design: hasFP() might be called really362// early, before the stack layout was calculated and thus hasFP() might return363// true or false here depending on the time of call.364return (MFI.getStackSize()) && needsFP(MF);365}366367// needsFP - Return true if the specified function should have a dedicated frame368// pointer register. This is true if the function has variable sized allocas or369// if frame pointer elimination is disabled.370bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {371const MachineFrameInfo &MFI = MF.getFrameInfo();372373// Naked functions have no stack frame pushed, so we don't have a frame374// pointer.375if (MF.getFunction().hasFnAttribute(Attribute::Naked))376return false;377378return MF.getTarget().Options.DisableFramePointerElim(MF) ||379MFI.hasVarSizedObjects() || MFI.hasStackMap() || MFI.hasPatchPoint() ||380MF.exposesReturnsTwice() ||381(MF.getTarget().Options.GuaranteedTailCallOpt &&382MF.getInfo<PPCFunctionInfo>()->hasFastCall());383}384385void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {386// When there is dynamic alloca in this function, we can not use the frame387// pointer X31/R31 for the frameaddress lowering. In this case, only X1/R1388// always points to the backchain.389bool is31 = needsFP(MF) && !MF.getFrameInfo().hasVarSizedObjects();390unsigned FPReg = is31 ? PPC::R31 : PPC::R1;391unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;392393const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();394bool HasBP = RegInfo->hasBasePointer(MF);395unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;396unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FP8Reg;397398for (MachineBasicBlock &MBB : MF)399for (MachineBasicBlock::iterator MBBI = MBB.end(); MBBI != MBB.begin();) {400--MBBI;401for (MachineOperand &MO : MBBI->operands()) {402if (!MO.isReg())403continue;404405switch (MO.getReg()) {406case PPC::FP:407MO.setReg(FPReg);408break;409case PPC::FP8:410MO.setReg(FP8Reg);411break;412case PPC::BP:413MO.setReg(BPReg);414break;415case PPC::BP8:416MO.setReg(BP8Reg);417break;418419}420}421}422}423424/* This function will do the following:425- If MBB is an entry or exit block, set SR1 and SR2 to R0 and R12426respectively (defaults recommended by the ABI) and return true427- If MBB is not an entry block, initialize the register scavenger and look428for available registers.429- If the defaults (R0/R12) are available, return true430- If TwoUniqueRegsRequired is set to true, it looks for two unique431registers. 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 to434PPC::NoRegister and return false.435436Note that if both SR1 and SR2 are valid parameters and TwoUniqueRegsRequired437is not set, this function will attempt to find two different registers, but438still return true if only one register is available (and set SR1 == SR2).439*/440bool441PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,442bool UseAtEnd,443bool TwoUniqueRegsRequired,444Register *SR1,445Register *SR2) const {446RegScavenger RS;447Register R0 = Subtarget.isPPC64() ? PPC::X0 : PPC::R0;448Register R12 = Subtarget.isPPC64() ? PPC::X12 : PPC::R12;449450// Set the defaults for the two scratch registers.451if (SR1)452*SR1 = R0;453454if (SR2) {455assert (SR1 && "Asking for the second scratch register but not the first?");456*SR2 = R12;457}458459// If MBB is an entry or exit block, use R0 and R12 as the scratch registers.460if ((UseAtEnd && MBB->isReturnBlock()) ||461(!UseAtEnd && (&MBB->getParent()->front() == MBB)))462return true;463464if (UseAtEnd) {465// The scratch register will be used before the first terminator (or at the466// end of the block if there are no terminators).467MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();468if (MBBI == MBB->begin()) {469RS.enterBasicBlock(*MBB);470} else {471RS.enterBasicBlockEnd(*MBB);472RS.backward(MBBI);473}474} else {475// The scratch register will be used at the start of the block.476RS.enterBasicBlock(*MBB);477}478479// If the two registers are available, we're all good.480// Note that we only return here if both R0 and R12 are available because481// although the function may not require two unique registers, it may benefit482// from having two so we should try to provide them.483if (!RS.isRegUsed(R0) && !RS.isRegUsed(R12))484return true;485486// Get the list of callee-saved registers for the target.487const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();488const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MBB->getParent());489490// Get all the available registers in the block.491BitVector BV = RS.getRegsAvailable(Subtarget.isPPC64() ? &PPC::G8RCRegClass :492&PPC::GPRCRegClass);493494// We shouldn't use callee-saved registers as scratch registers as they may be495// available when looking for a candidate block for shrink wrapping but not496// available when the actual prologue/epilogue is being emitted because they497// were added as live-in to the prologue block by PrologueEpilogueInserter.498for (int i = 0; CSRegs[i]; ++i)499BV.reset(CSRegs[i]);500501// Set the first scratch register to the first available one.502if (SR1) {503int FirstScratchReg = BV.find_first();504*SR1 = FirstScratchReg == -1 ? (unsigned)PPC::NoRegister : FirstScratchReg;505}506507// 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 two509// or to whatever SR1 is set to if this function doesn't require two.510if (SR2) {511int SecondScratchReg = BV.find_next(*SR1);512if (SecondScratchReg != -1)513*SR2 = SecondScratchReg;514else515*SR2 = TwoUniqueRegsRequired ? Register() : *SR1;516}517518// Now that we've done our best to provide both registers, double check519// whether we were unable to provide enough.520if (BV.count() < (TwoUniqueRegsRequired ? 2U : 1U))521return false;522523return true;524}525526// 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 scratch528// register is available, we can adjust for that by not overlapping the spill529// 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 for532// large frame and large probe size.533bool534PPCFrameLowering::twoUniqueScratchRegsRequired(MachineBasicBlock *MBB) const {535const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();536MachineFunction &MF = *(MBB->getParent());537bool HasBP = RegInfo->hasBasePointer(MF);538unsigned FrameSize = determineFrameLayout(MF);539int NegFrameSize = -FrameSize;540bool IsLargeFrame = !isInt<16>(NegFrameSize);541MachineFrameInfo &MFI = MF.getFrameInfo();542Align MaxAlign = MFI.getMaxAlign();543bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();544const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();545546return ((IsLargeFrame || !HasRedZone) && HasBP && MaxAlign > 1) ||547TLI.hasInlineStackProbe(MF);548}549550bool PPCFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {551MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);552553return findScratchRegister(TmpMBB, false,554twoUniqueScratchRegsRequired(TmpMBB));555}556557bool PPCFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {558MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);559560return findScratchRegister(TmpMBB, true);561}562563bool PPCFrameLowering::stackUpdateCanBeMoved(MachineFunction &MF) const {564const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();565PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();566567// Abort if there is no register info or function info.568if (!RegInfo || !FI)569return false;570571// Only move the stack update on ELFv2 ABI and PPC64.572if (!Subtarget.isELFv2ABI() || !Subtarget.isPPC64())573return false;574575// Check the frame size first and return false if it does not fit the576// requirements.577// We need a non-zero frame size as well as a frame that will fit in the red578// zone. This is because by moving the stack pointer update we are now storing579// to the red zone until the stack pointer is updated. If we get an interrupt580// inside the prologue but before the stack update we now have a number of581// stores to the red zone and those stores must all fit.582MachineFrameInfo &MFI = MF.getFrameInfo();583unsigned FrameSize = MFI.getStackSize();584if (!FrameSize || FrameSize > Subtarget.getRedZoneSize())585return false;586587// Frame pointers and base pointers complicate matters so don't do anything588// if we have them. For example having a frame pointer will sometimes require589// a copy of r1 into r31 and that makes keeping track of updates to r1 more590// difficult. Similar situation exists with setjmp.591if (hasFP(MF) || RegInfo->hasBasePointer(MF) || MF.exposesReturnsTwice())592return false;593594// Calls to fast_cc functions use different rules for passing parameters on595// the stack from the ABI and using PIC base in the function imposes596// similar restrictions to using the base pointer. It is not generally safe597// to move the stack pointer update in these situations.598if (FI->hasFastCall() || FI->usesPICBase())599return false;600601// Finally we can move the stack update if we do not require register602// scavenging. Register scavenging can introduce more spills and so603// may make the frame size larger than we have computed.604return !RegInfo->requiresFrameIndexScavenging(MF);605}606607void PPCFrameLowering::emitPrologue(MachineFunction &MF,608MachineBasicBlock &MBB) const {609MachineBasicBlock::iterator MBBI = MBB.begin();610MachineFrameInfo &MFI = MF.getFrameInfo();611const PPCInstrInfo &TII = *Subtarget.getInstrInfo();612const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();613const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();614615const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();616DebugLoc dl;617// AIX assembler does not support cfi directives.618const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();619620const bool HasFastMFLR = Subtarget.hasFastMFLR();621622// Get processor type.623bool isPPC64 = Subtarget.isPPC64();624// Get the ABI.625bool isSVR4ABI = Subtarget.isSVR4ABI();626bool isELFv2ABI = Subtarget.isELFv2ABI();627assert((isSVR4ABI || Subtarget.isAIXABI()) && "Unsupported PPC ABI.");628629// Work out frame sizes.630uint64_t FrameSize = determineFrameLayoutAndUpdate(MF);631int64_t NegFrameSize = -FrameSize;632if (!isPPC64 && (!isInt<32>(FrameSize) || !isInt<32>(NegFrameSize)))633llvm_unreachable("Unhandled stack size!");634635if (MFI.isFrameAddressTaken())636replaceFPWithRealFP(MF);637638// Check if the link register (LR) must be saved.639PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();640bool MustSaveLR = FI->mustSaveLR();641bool MustSaveTOC = FI->mustSaveTOC();642const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();643bool MustSaveCR = !MustSaveCRs.empty();644// Do we have a frame pointer and/or base pointer for this function?645bool HasFP = hasFP(MF);646bool HasBP = RegInfo->hasBasePointer(MF);647bool HasRedZone = isPPC64 || !isSVR4ABI;648bool HasROPProtect = Subtarget.hasROPProtect();649bool HasPrivileged = Subtarget.hasPrivileged();650651Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;652Register BPReg = RegInfo->getBaseRegister(MF);653Register FPReg = isPPC64 ? PPC::X31 : PPC::R31;654Register LRReg = isPPC64 ? PPC::LR8 : PPC::LR;655Register TOCReg = isPPC64 ? PPC::X2 : PPC::R2;656Register ScratchReg;657Register TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg658// ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)659const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8660: PPC::MFLR );661const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD662: PPC::STW );663const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU664: PPC::STWU );665const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX666: PPC::STWUX);667const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8668: PPC::OR );669const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8670: PPC::SUBFC);671const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8672: PPC::SUBFIC);673const MCInstrDesc &MoveFromCondRegInst = TII.get(isPPC64 ? PPC::MFCR8674: PPC::MFCR);675const MCInstrDesc &StoreWordInst = TII.get(isPPC64 ? PPC::STW8 : PPC::STW);676const MCInstrDesc &HashST =677TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHSTP8 : PPC::HASHST8)678: (HasPrivileged ? PPC::HASHSTP : PPC::HASHST));679680// 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 no682// 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.684assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&685"FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");686687// Using the same bool variable as below to suppress compiler warnings.688bool SingleScratchReg = findScratchRegister(689&MBB, false, twoUniqueScratchRegsRequired(&MBB), &ScratchReg, &TempReg);690assert(SingleScratchReg &&691"Required number of registers not available in this block");692693SingleScratchReg = ScratchReg == TempReg;694695int64_t LROffset = getReturnSaveOffset();696697int64_t FPOffset = 0;698if (HasFP) {699MachineFrameInfo &MFI = MF.getFrameInfo();700int FPIndex = FI->getFramePointerSaveIndex();701assert(FPIndex && "No Frame Pointer Save Slot!");702FPOffset = MFI.getObjectOffset(FPIndex);703}704705int64_t BPOffset = 0;706if (HasBP) {707MachineFrameInfo &MFI = MF.getFrameInfo();708int BPIndex = FI->getBasePointerSaveIndex();709assert(BPIndex && "No Base Pointer Save Slot!");710BPOffset = MFI.getObjectOffset(BPIndex);711}712713int64_t PBPOffset = 0;714if (FI->usesPICBase()) {715MachineFrameInfo &MFI = MF.getFrameInfo();716int PBPIndex = FI->getPICBasePointerSaveIndex();717assert(PBPIndex && "No PIC Base Pointer Save Slot!");718PBPOffset = MFI.getObjectOffset(PBPIndex);719}720721// Get stack alignments.722Align MaxAlign = MFI.getMaxAlign();723if (HasBP && MaxAlign > 1)724assert(Log2(MaxAlign) < 16 && "Invalid alignment!");725726// Frames of 32KB & larger require special handling because they cannot be727// indexed into with a simple STDU/STWU/STD/STW immediate offset operand.728bool isLargeFrame = !isInt<16>(NegFrameSize);729730// Check if we can move the stack update instruction (stdu) down the prologue731// past the callee saves. Hopefully this will avoid the situation where the732// saves are waiting for the update on the store with update to complete.733MachineBasicBlock::iterator StackUpdateLoc = MBBI;734bool MovingStackUpdateDown = false;735736// Check if we can move the stack update.737if (stackUpdateCanBeMoved(MF)) {738const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();739for (CalleeSavedInfo CSI : Info) {740// If the callee saved register is spilled to a register instead of the741// 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 not744// spill any callee saved registers to stack.745// 2) We have a situation where we still have to update the stack pointer746// even though some registers are spilled to other registers. In747// this case the current code moves the stack update to an incorrect748// position.749// In either case we should abort moving the stack update operation.750if (CSI.isSpilledToReg()) {751StackUpdateLoc = MBBI;752MovingStackUpdateDown = false;753break;754}755756int FrIdx = CSI.getFrameIdx();757// If the frame index is not negative the callee saved info belongs to a758// stack object that is not a fixed stack object. We ignore non-fixed759// stack objects because we won't move the stack update pointer past them.760if (FrIdx >= 0)761continue;762763if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0) {764StackUpdateLoc++;765MovingStackUpdateDown = true;766} else {767// We need all of the Frame Indices to meet these conditions.768// If they do not, abort the whole operation.769StackUpdateLoc = MBBI;770MovingStackUpdateDown = false;771break;772}773}774775// If the operation was not aborted then update the object offset.776if (MovingStackUpdateDown) {777for (CalleeSavedInfo CSI : Info) {778int FrIdx = CSI.getFrameIdx();779if (FrIdx < 0)780MFI.setObjectOffset(FrIdx, MFI.getObjectOffset(FrIdx) + NegFrameSize);781}782}783}784785// Where in the prologue we move the CR fields depends on how many scratch786// registers we have, and if we need to save the link register or not. This787// lambda is to avoid duplicating the logic in 2 places.788auto BuildMoveFromCR = [&]() {789if (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 use792// mfocrf to selectively save just that field, because mfocrf has short793// latency compares to mfcr.794assert(isPPC64 && "V2 ABI is 64-bit only.");795MachineInstrBuilder MIB =796BuildMI(MBB, MBBI, dl, TII.get(PPC::MFOCRF8), TempReg);797MIB.addReg(MustSaveCRs[0], RegState::Kill);798} else {799MachineInstrBuilder MIB =800BuildMI(MBB, MBBI, dl, MoveFromCondRegInst, TempReg);801for (unsigned CRfield : MustSaveCRs)802MIB.addReg(CRfield, RegState::ImplicitKill);803}804};805806// If we need to spill the CR and the LR but we don't have two separate807// registers available, we must spill them one at a time808if (MustSaveCR && SingleScratchReg && MustSaveLR) {809BuildMoveFromCR();810BuildMI(MBB, MBBI, dl, StoreWordInst)811.addReg(TempReg, getKillRegState(true))812.addImm(CRSaveOffset)813.addReg(SPReg);814}815816if (MustSaveLR)817BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);818819if (MustSaveCR && !(SingleScratchReg && MustSaveLR))820BuildMoveFromCR();821822if (HasRedZone) {823if (HasFP)824BuildMI(MBB, MBBI, dl, StoreInst)825.addReg(FPReg)826.addImm(FPOffset)827.addReg(SPReg);828if (FI->usesPICBase())829BuildMI(MBB, MBBI, dl, StoreInst)830.addReg(PPC::R30)831.addImm(PBPOffset)832.addReg(SPReg);833if (HasBP)834BuildMI(MBB, MBBI, dl, StoreInst)835.addReg(BPReg)836.addImm(BPOffset)837.addReg(SPReg);838}839840// Generate the instruction to store the LR. In the case where ROP protection841// is required the register holding the LR should not be killed as it will be842// used by the hash store instruction.843auto SaveLR = [&](int64_t Offset) {844assert(MustSaveLR && "LR is not required to be saved!");845BuildMI(MBB, StackUpdateLoc, dl, StoreInst)846.addReg(ScratchReg, getKillRegState(!HasROPProtect))847.addImm(Offset)848.addReg(SPReg);849850// Add the ROP protection Hash Store instruction.851// NOTE: This is technically a violation of the ABI. The hash can be saved852// up to 512 bytes into the Protected Zone. This can be outside of the853// initial 288 byte volatile program storage region in the Protected Zone.854// However, this restriction will be removed in an upcoming revision of the855// ABI.856if (HasROPProtect) {857const int SaveIndex = FI->getROPProtectionHashSaveIndex();858const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);859assert((ImmOffset <= -8 && ImmOffset >= -512) &&860"ROP hash save offset out of range.");861assert(((ImmOffset & 0x7) == 0) &&862"ROP hash save offset must be 8 byte aligned.");863BuildMI(MBB, StackUpdateLoc, dl, HashST)864.addReg(ScratchReg, getKillRegState(true))865.addImm(ImmOffset)866.addReg(SPReg);867}868};869870if (MustSaveLR && HasFastMFLR)871SaveLR(LROffset);872873if (MustSaveCR &&874!(SingleScratchReg && MustSaveLR)) {875assert(HasRedZone && "A red zone is always available on PPC64");876BuildMI(MBB, MBBI, dl, StoreWordInst)877.addReg(TempReg, getKillRegState(true))878.addImm(CRSaveOffset)879.addReg(SPReg);880}881882// Skip the rest if this is a leaf function & all spills fit in the Red Zone.883if (!FrameSize) {884if (MustSaveLR && !HasFastMFLR)885SaveLR(LROffset);886return;887}888889// Adjust stack pointer: r1 += NegFrameSize.890// If there is a preferred stack alignment, align R1 now891892if (HasBP && HasRedZone) {893// Save a copy of r1 as the base pointer.894BuildMI(MBB, MBBI, dl, OrInst, BPReg)895.addReg(SPReg)896.addReg(SPReg);897}898899// Have we generated a STUX instruction to claim stack frame? If so,900// the negated frame size will be placed in ScratchReg.901bool HasSTUX =902(TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) ||903(HasBP && MaxAlign > 1) || isLargeFrame;904905// If we use STUX to update the stack pointer, we need the two scratch906// registers TempReg and ScratchReg, we have to save LR here which is stored907// in ScratchReg.908// If the offset can not be encoded into the store instruction, we also have909// to save LR here.910if (MustSaveLR && !HasFastMFLR &&911(HasSTUX || !isInt<16>(FrameSize + LROffset)))912SaveLR(LROffset);913914// If FrameSize <= TLI.getStackProbeSize(MF), as POWER ABI requires backchain915// pointer is always stored at SP, we will get a free probe due to an essential916// STU(X) instruction.917if (TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) {918// To be consistent with other targets, a pseudo instruction is emitted and919// will be later expanded in `inlineStackProbe`.920BuildMI(MBB, MBBI, dl,921TII.get(isPPC64 ? PPC::PROBED_STACKALLOC_64922: PPC::PROBED_STACKALLOC_32))923.addDef(TempReg)924.addDef(ScratchReg) // ScratchReg stores the old sp.925.addImm(NegFrameSize);926// FIXME: HasSTUX is only read if HasRedZone is not set, in such case, we927// update the ScratchReg to meet the assumption that ScratchReg contains928// the NegFrameSize. This solution is rather tricky.929if (!HasRedZone) {930BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)931.addReg(ScratchReg)932.addReg(SPReg);933}934} else {935// This condition must be kept in sync with canUseAsPrologue.936if (HasBP && MaxAlign > 1) {937if (isPPC64)938BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)939.addReg(SPReg)940.addImm(0)941.addImm(64 - Log2(MaxAlign));942else // PPC32...943BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)944.addReg(SPReg)945.addImm(0)946.addImm(32 - Log2(MaxAlign))947.addImm(31);948if (!isLargeFrame) {949BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)950.addReg(ScratchReg, RegState::Kill)951.addImm(NegFrameSize);952} else {953assert(!SingleScratchReg && "Only a single scratch reg available");954TII.materializeImmPostRA(MBB, MBBI, dl, TempReg, NegFrameSize);955BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)956.addReg(ScratchReg, RegState::Kill)957.addReg(TempReg, RegState::Kill);958}959960BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)961.addReg(SPReg, RegState::Kill)962.addReg(SPReg)963.addReg(ScratchReg);964} else if (!isLargeFrame) {965BuildMI(MBB, StackUpdateLoc, dl, StoreUpdtInst, SPReg)966.addReg(SPReg)967.addImm(NegFrameSize)968.addReg(SPReg);969} else {970TII.materializeImmPostRA(MBB, MBBI, dl, ScratchReg, NegFrameSize);971BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)972.addReg(SPReg, RegState::Kill)973.addReg(SPReg)974.addReg(ScratchReg);975}976}977978// Save the TOC register after the stack pointer update if a prologue TOC979// save is required for the function.980if (MustSaveTOC) {981assert(isELFv2ABI && "TOC saves in the prologue only supported on ELFv2");982BuildMI(MBB, StackUpdateLoc, dl, TII.get(PPC::STD))983.addReg(TOCReg, getKillRegState(true))984.addImm(TOCSaveOffset)985.addReg(SPReg);986}987988if (!HasRedZone) {989assert(!isPPC64 && "A red zone is always available on PPC64");990if (HasSTUX) {991// The negated frame size is in ScratchReg, and the SPReg has been992// decremented by the frame size: SPReg = old SPReg + ScratchReg.993// Since FPOffset, PBPOffset, etc. are relative to the beginning of994// the stack frame (i.e. the old SP), ideally, we would put the old995// SP into a register and use it as the base for the stores. The996// problem is that the only available register may be ScratchReg,997// which could be R0, and R0 cannot be used as a base address.998999// First, set ScratchReg to the old SP. This may need to be modified1000// later.1001BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)1002.addReg(ScratchReg, RegState::Kill)1003.addReg(SPReg);10041005if (ScratchReg == PPC::R0) {1006// R0 cannot be used as a base register, but it can be used as an1007// index in a store-indexed.1008int LastOffset = 0;1009if (HasFP) {1010// R0 += (FPOffset-LastOffset).1011// Need addic, since addi treats R0 as 0.1012BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)1013.addReg(ScratchReg)1014.addImm(FPOffset-LastOffset);1015LastOffset = FPOffset;1016// Store FP into *R0.1017BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))1018.addReg(FPReg, RegState::Kill) // Save FP.1019.addReg(PPC::ZERO)1020.addReg(ScratchReg); // This will be the index (R0 is ok here).1021}1022if (FI->usesPICBase()) {1023// R0 += (PBPOffset-LastOffset).1024BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)1025.addReg(ScratchReg)1026.addImm(PBPOffset-LastOffset);1027LastOffset = PBPOffset;1028BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))1029.addReg(PPC::R30, RegState::Kill) // Save PIC base pointer.1030.addReg(PPC::ZERO)1031.addReg(ScratchReg); // This will be the index (R0 is ok here).1032}1033if (HasBP) {1034// R0 += (BPOffset-LastOffset).1035BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)1036.addReg(ScratchReg)1037.addImm(BPOffset-LastOffset);1038LastOffset = BPOffset;1039BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))1040.addReg(BPReg, RegState::Kill) // Save BP.1041.addReg(PPC::ZERO)1042.addReg(ScratchReg); // This will be the index (R0 is ok here).1043// BP = R0-LastOffset1044BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), BPReg)1045.addReg(ScratchReg, RegState::Kill)1046.addImm(-LastOffset);1047}1048} else {1049// ScratchReg is not R0, so use it as the base register. It is1050// already set to the old SP, so we can use the offsets directly.10511052// Now that the stack frame has been allocated, save all the necessary1053// registers using ScratchReg as the base address.1054if (HasFP)1055BuildMI(MBB, MBBI, dl, StoreInst)1056.addReg(FPReg)1057.addImm(FPOffset)1058.addReg(ScratchReg);1059if (FI->usesPICBase())1060BuildMI(MBB, MBBI, dl, StoreInst)1061.addReg(PPC::R30)1062.addImm(PBPOffset)1063.addReg(ScratchReg);1064if (HasBP) {1065BuildMI(MBB, MBBI, dl, StoreInst)1066.addReg(BPReg)1067.addImm(BPOffset)1068.addReg(ScratchReg);1069BuildMI(MBB, MBBI, dl, OrInst, BPReg)1070.addReg(ScratchReg, RegState::Kill)1071.addReg(ScratchReg);1072}1073}1074} else {1075// The frame size is a known 16-bit constant (fitting in the immediate1076// field of STWU). To be here we have to be compiling for PPC32.1077// Since the SPReg has been decreased by FrameSize, add it back to each1078// offset.1079if (HasFP)1080BuildMI(MBB, MBBI, dl, StoreInst)1081.addReg(FPReg)1082.addImm(FrameSize + FPOffset)1083.addReg(SPReg);1084if (FI->usesPICBase())1085BuildMI(MBB, MBBI, dl, StoreInst)1086.addReg(PPC::R30)1087.addImm(FrameSize + PBPOffset)1088.addReg(SPReg);1089if (HasBP) {1090BuildMI(MBB, MBBI, dl, StoreInst)1091.addReg(BPReg)1092.addImm(FrameSize + BPOffset)1093.addReg(SPReg);1094BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), BPReg)1095.addReg(SPReg)1096.addImm(FrameSize);1097}1098}1099}11001101// Save the LR now.1102if (!HasSTUX && MustSaveLR && !HasFastMFLR && isInt<16>(FrameSize + LROffset))1103SaveLR(LROffset + FrameSize);11041105// Add Call Frame Information for the instructions we generated above.1106if (needsCFI) {1107unsigned CFIIndex;11081109if (HasBP) {1110// Define CFA in terms of BP. Do this in preference to using FP/SP,1111// because if the stack needed aligning then CFA won't be at a fixed1112// offset from FP/SP.1113unsigned Reg = MRI->getDwarfRegNum(BPReg, true);1114CFIIndex = MF.addFrameInst(1115MCCFIInstruction::createDefCfaRegister(nullptr, Reg));1116} else {1117// Adjust the definition of CFA to account for the change in SP.1118assert(NegFrameSize);1119CFIIndex = MF.addFrameInst(1120MCCFIInstruction::cfiDefCfaOffset(nullptr, -NegFrameSize));1121}1122BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1123.addCFIIndex(CFIIndex);11241125if (HasFP) {1126// Describe where FP was saved, at a fixed offset from CFA.1127unsigned Reg = MRI->getDwarfRegNum(FPReg, true);1128CFIIndex = MF.addFrameInst(1129MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));1130BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1131.addCFIIndex(CFIIndex);1132}11331134if (FI->usesPICBase()) {1135// Describe where FP was saved, at a fixed offset from CFA.1136unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);1137CFIIndex = MF.addFrameInst(1138MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));1139BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1140.addCFIIndex(CFIIndex);1141}11421143if (HasBP) {1144// Describe where BP was saved, at a fixed offset from CFA.1145unsigned Reg = MRI->getDwarfRegNum(BPReg, true);1146CFIIndex = MF.addFrameInst(1147MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));1148BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1149.addCFIIndex(CFIIndex);1150}11511152if (MustSaveLR) {1153// Describe where LR was saved, at a fixed offset from CFA.1154unsigned Reg = MRI->getDwarfRegNum(LRReg, true);1155CFIIndex = MF.addFrameInst(1156MCCFIInstruction::createOffset(nullptr, Reg, LROffset));1157BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1158.addCFIIndex(CFIIndex);1159}1160}11611162// If there is a frame pointer, copy R1 into R311163if (HasFP) {1164BuildMI(MBB, MBBI, dl, OrInst, FPReg)1165.addReg(SPReg)1166.addReg(SPReg);11671168if (!HasBP && needsCFI) {1169// Change the definition of CFA from SP+offset to FP+offset, because SP1170// will change at every alloca.1171unsigned Reg = MRI->getDwarfRegNum(FPReg, true);1172unsigned CFIIndex = MF.addFrameInst(1173MCCFIInstruction::createDefCfaRegister(nullptr, Reg));11741175BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1176.addCFIIndex(CFIIndex);1177}1178}11791180if (needsCFI) {1181// Describe where callee saved registers were saved, at fixed offsets from1182// CFA.1183const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();1184for (const CalleeSavedInfo &I : CSI) {1185Register Reg = I.getReg();1186if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;11871188// This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just1189// subregisters of CR2. We just need to emit a move of CR2.1190if (PPC::CRBITRCRegClass.contains(Reg))1191continue;11921193if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)1194continue;11951196// For 64-bit SVR4 when we have spilled CRs, the spill location1197// is SP+8, not a frame-relative slot.1198if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {1199// In the ELFv1 ABI, only CR2 is noted in CFI and stands in for1200// the whole CR word. In the ELFv2 ABI, every CR that was1201// actually saved gets its own CFI record.1202Register CRReg = isELFv2ABI? Reg : PPC::CR2;1203unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(1204nullptr, MRI->getDwarfRegNum(CRReg, true), CRSaveOffset));1205BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1206.addCFIIndex(CFIIndex);1207continue;1208}12091210if (I.isSpilledToReg()) {1211unsigned SpilledReg = I.getDstReg();1212unsigned CFIRegister = MF.addFrameInst(MCCFIInstruction::createRegister(1213nullptr, MRI->getDwarfRegNum(Reg, true),1214MRI->getDwarfRegNum(SpilledReg, true)));1215BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1216.addCFIIndex(CFIRegister);1217} else {1218int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());1219// We have changed the object offset above but we do not want to change1220// the actual offsets in the CFI instruction so we have to undo the1221// offset change here.1222if (MovingStackUpdateDown)1223Offset -= NegFrameSize;12241225unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(1226nullptr, MRI->getDwarfRegNum(Reg, true), Offset));1227BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))1228.addCFIIndex(CFIIndex);1229}1230}1231}1232}12331234void PPCFrameLowering::inlineStackProbe(MachineFunction &MF,1235MachineBasicBlock &PrologMBB) const {1236bool isPPC64 = Subtarget.isPPC64();1237const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();1238const PPCInstrInfo &TII = *Subtarget.getInstrInfo();1239MachineFrameInfo &MFI = MF.getFrameInfo();1240const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();1241// AIX assembler does not support cfi directives.1242const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();1243auto StackAllocMIPos = llvm::find_if(PrologMBB, [](MachineInstr &MI) {1244int Opc = MI.getOpcode();1245return Opc == PPC::PROBED_STACKALLOC_64 || Opc == PPC::PROBED_STACKALLOC_32;1246});1247if (StackAllocMIPos == PrologMBB.end())1248return;1249const BasicBlock *ProbedBB = PrologMBB.getBasicBlock();1250MachineBasicBlock *CurrentMBB = &PrologMBB;1251DebugLoc DL = PrologMBB.findDebugLoc(StackAllocMIPos);1252MachineInstr &MI = *StackAllocMIPos;1253int64_t NegFrameSize = MI.getOperand(2).getImm();1254unsigned ProbeSize = TLI.getStackProbeSize(MF);1255int64_t NegProbeSize = -(int64_t)ProbeSize;1256assert(isInt<32>(NegProbeSize) && "Unhandled probe size");1257int64_t NumBlocks = NegFrameSize / NegProbeSize;1258int64_t NegResidualSize = NegFrameSize % NegProbeSize;1259Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;1260Register ScratchReg = MI.getOperand(0).getReg();1261Register FPReg = MI.getOperand(1).getReg();1262const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();1263bool HasBP = RegInfo->hasBasePointer(MF);1264Register BPReg = RegInfo->getBaseRegister(MF);1265Align MaxAlign = MFI.getMaxAlign();1266bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();1267const MCInstrDesc &CopyInst = TII.get(isPPC64 ? PPC::OR8 : PPC::OR);1268// Subroutines to generate .cfi_* directives.1269auto buildDefCFAReg = [&](MachineBasicBlock &MBB,1270MachineBasicBlock::iterator MBBI, Register Reg) {1271unsigned RegNum = MRI->getDwarfRegNum(Reg, true);1272unsigned CFIIndex = MF.addFrameInst(1273MCCFIInstruction::createDefCfaRegister(nullptr, RegNum));1274BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))1275.addCFIIndex(CFIIndex);1276};1277auto buildDefCFA = [&](MachineBasicBlock &MBB,1278MachineBasicBlock::iterator MBBI, Register Reg,1279int Offset) {1280unsigned RegNum = MRI->getDwarfRegNum(Reg, true);1281unsigned CFIIndex = MBB.getParent()->addFrameInst(1282MCCFIInstruction::cfiDefCfa(nullptr, RegNum, Offset));1283BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))1284.addCFIIndex(CFIIndex);1285};1286// Subroutine to determine if we can use the Imm as part of d-form.1287auto CanUseDForm = [](int64_t Imm) { return isInt<16>(Imm) && Imm % 4 == 0; };1288// Subroutine to materialize the Imm into TempReg.1289auto MaterializeImm = [&](MachineBasicBlock &MBB,1290MachineBasicBlock::iterator MBBI, int64_t Imm,1291Register &TempReg) {1292assert(isInt<32>(Imm) && "Unhandled imm");1293if (isInt<16>(Imm))1294BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LI8 : PPC::LI), TempReg)1295.addImm(Imm);1296else {1297BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)1298.addImm(Imm >> 16);1299BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::ORI8 : PPC::ORI), TempReg)1300.addReg(TempReg)1301.addImm(Imm & 0xFFFF);1302}1303};1304// Subroutine to store frame pointer and decrease stack pointer by probe size.1305auto allocateAndProbe = [&](MachineBasicBlock &MBB,1306MachineBasicBlock::iterator MBBI, int64_t NegSize,1307Register NegSizeReg, bool UseDForm,1308Register StoreReg) {1309if (UseDForm)1310BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDU : PPC::STWU), SPReg)1311.addReg(StoreReg)1312.addImm(NegSize)1313.addReg(SPReg);1314else1315BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)1316.addReg(StoreReg)1317.addReg(SPReg)1318.addReg(NegSizeReg);1319};1320// Used to probe stack when realignment is required.1321// Note that, according to ABI's requirement, *sp must always equals the1322// value of back-chain pointer, only st(w|d)u(x) can be used to update sp.1323// Following is pseudo code:1324// final_sp = (sp & align) + negframesize;1325// neg_gap = final_sp - sp;1326// while (neg_gap < negprobesize) {1327// stdu fp, negprobesize(sp);1328// neg_gap -= negprobesize;1329// }1330// stdux fp, sp, neg_gap1331//1332// When HasBP & HasRedzone, back-chain pointer is already saved in BPReg1333// before probe code, we don't need to save it, so we get one additional reg1334// that can be used to materialize the probeside if needed to use xform.1335// Otherwise, we can NOT materialize probeside, so we can only use Dform for1336// now.1337//1338// The allocations are:1339// if (HasBP && HasRedzone) {1340// r0: materialize the probesize if needed so that we can use xform.1341// r12: `neg_gap`1342// } else {1343// r0: back-chain pointer1344// r12: `neg_gap`.1345// }1346auto probeRealignedStack = [&](MachineBasicBlock &MBB,1347MachineBasicBlock::iterator MBBI,1348Register ScratchReg, Register TempReg) {1349assert(HasBP && "The function is supposed to have base pointer when its "1350"stack is realigned.");1351assert(isPowerOf2_64(ProbeSize) && "Probe size should be power of 2");13521353// FIXME: We can eliminate this limitation if we get more infomation about1354// which part of redzone are already used. Used redzone can be treated1355// probed. But there might be `holes' in redzone probed, this could1356// complicate the implementation.1357assert(ProbeSize >= Subtarget.getRedZoneSize() &&1358"Probe size should be larger or equal to the size of red-zone so "1359"that red-zone is not clobbered by probing.");13601361Register &FinalStackPtr = TempReg;1362// FIXME: We only support NegProbeSize materializable by DForm currently.1363// When HasBP && HasRedzone, we can use xform if we have an additional idle1364// register.1365NegProbeSize = std::max(NegProbeSize, -((int64_t)1 << 15));1366assert(isInt<16>(NegProbeSize) &&1367"NegProbeSize should be materializable by DForm");1368Register CRReg = PPC::CR0;1369// Layout of output assembly kinda like:1370// bb.0:1371// ...1372// sub $scratchreg, $finalsp, r11373// cmpdi $scratchreg, <negprobesize>1374// bge bb.21375// bb.1:1376// stdu <backchain>, <negprobesize>(r1)1377// sub $scratchreg, $scratchreg, negprobesize1378// cmpdi $scratchreg, <negprobesize>1379// blt bb.11380// bb.2:1381// stdux <backchain>, r1, $scratchreg1382MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());1383MachineBasicBlock *ProbeLoopBodyMBB = MF.CreateMachineBasicBlock(ProbedBB);1384MF.insert(MBBInsertPoint, ProbeLoopBodyMBB);1385MachineBasicBlock *ProbeExitMBB = MF.CreateMachineBasicBlock(ProbedBB);1386MF.insert(MBBInsertPoint, ProbeExitMBB);1387// bb.21388{1389Register BackChainPointer = HasRedZone ? BPReg : TempReg;1390allocateAndProbe(*ProbeExitMBB, ProbeExitMBB->end(), 0, ScratchReg, false,1391BackChainPointer);1392if (HasRedZone)1393// PROBED_STACKALLOC_64 assumes Operand(1) stores the old sp, copy BPReg1394// to TempReg to satisfy it.1395BuildMI(*ProbeExitMBB, ProbeExitMBB->end(), DL, CopyInst, TempReg)1396.addReg(BPReg)1397.addReg(BPReg);1398ProbeExitMBB->splice(ProbeExitMBB->end(), &MBB, MBBI, MBB.end());1399ProbeExitMBB->transferSuccessorsAndUpdatePHIs(&MBB);1400}1401// bb.01402{1403BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), ScratchReg)1404.addReg(SPReg)1405.addReg(FinalStackPtr);1406if (!HasRedZone)1407BuildMI(&MBB, DL, CopyInst, TempReg).addReg(SPReg).addReg(SPReg);1408BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI), CRReg)1409.addReg(ScratchReg)1410.addImm(NegProbeSize);1411BuildMI(&MBB, DL, TII.get(PPC::BCC))1412.addImm(PPC::PRED_GE)1413.addReg(CRReg)1414.addMBB(ProbeExitMBB);1415MBB.addSuccessor(ProbeLoopBodyMBB);1416MBB.addSuccessor(ProbeExitMBB);1417}1418// bb.11419{1420Register BackChainPointer = HasRedZone ? BPReg : TempReg;1421allocateAndProbe(*ProbeLoopBodyMBB, ProbeLoopBodyMBB->end(), NegProbeSize,14220, true /*UseDForm*/, BackChainPointer);1423BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::ADDI8 : PPC::ADDI),1424ScratchReg)1425.addReg(ScratchReg)1426.addImm(-NegProbeSize);1427BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI),1428CRReg)1429.addReg(ScratchReg)1430.addImm(NegProbeSize);1431BuildMI(ProbeLoopBodyMBB, DL, TII.get(PPC::BCC))1432.addImm(PPC::PRED_LT)1433.addReg(CRReg)1434.addMBB(ProbeLoopBodyMBB);1435ProbeLoopBodyMBB->addSuccessor(ProbeExitMBB);1436ProbeLoopBodyMBB->addSuccessor(ProbeLoopBodyMBB);1437}1438// Update liveins.1439fullyRecomputeLiveIns({ProbeExitMBB, ProbeLoopBodyMBB});1440return ProbeExitMBB;1441};1442// For case HasBP && MaxAlign > 1, we have to realign the SP by performing1443// SP = SP - SP % MaxAlign, thus make the probe more like dynamic probe since1444// the offset subtracted from SP is determined by SP's runtime value.1445if (HasBP && MaxAlign > 1) {1446// Calculate final stack pointer.1447if (isPPC64)1448BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLDICL), ScratchReg)1449.addReg(SPReg)1450.addImm(0)1451.addImm(64 - Log2(MaxAlign));1452else1453BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLWINM), ScratchReg)1454.addReg(SPReg)1455.addImm(0)1456.addImm(32 - Log2(MaxAlign))1457.addImm(31);1458BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF),1459FPReg)1460.addReg(ScratchReg)1461.addReg(SPReg);1462MaterializeImm(*CurrentMBB, {MI}, NegFrameSize, ScratchReg);1463BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::ADD8 : PPC::ADD4),1464FPReg)1465.addReg(ScratchReg)1466.addReg(FPReg);1467CurrentMBB = probeRealignedStack(*CurrentMBB, {MI}, ScratchReg, FPReg);1468if (needsCFI)1469buildDefCFAReg(*CurrentMBB, {MI}, FPReg);1470} else {1471// Initialize current frame pointer.1472BuildMI(*CurrentMBB, {MI}, DL, CopyInst, FPReg).addReg(SPReg).addReg(SPReg);1473// Use FPReg to calculate CFA.1474if (needsCFI)1475buildDefCFA(*CurrentMBB, {MI}, FPReg, 0);1476// Probe residual part.1477if (NegResidualSize) {1478bool ResidualUseDForm = CanUseDForm(NegResidualSize);1479if (!ResidualUseDForm)1480MaterializeImm(*CurrentMBB, {MI}, NegResidualSize, ScratchReg);1481allocateAndProbe(*CurrentMBB, {MI}, NegResidualSize, ScratchReg,1482ResidualUseDForm, FPReg);1483}1484bool UseDForm = CanUseDForm(NegProbeSize);1485// If number of blocks is small, just probe them directly.1486if (NumBlocks < 3) {1487if (!UseDForm)1488MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);1489for (int i = 0; i < NumBlocks; ++i)1490allocateAndProbe(*CurrentMBB, {MI}, NegProbeSize, ScratchReg, UseDForm,1491FPReg);1492if (needsCFI) {1493// Restore using SPReg to calculate CFA.1494buildDefCFAReg(*CurrentMBB, {MI}, SPReg);1495}1496} else {1497// Since CTR is a volatile register and current shrinkwrap implementation1498// won't choose an MBB in a loop as the PrologMBB, it's safe to synthesize a1499// CTR loop to probe.1500// Calculate trip count and stores it in CTRReg.1501MaterializeImm(*CurrentMBB, {MI}, NumBlocks, ScratchReg);1502BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::MTCTR8 : PPC::MTCTR))1503.addReg(ScratchReg, RegState::Kill);1504if (!UseDForm)1505MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);1506// Create MBBs of the loop.1507MachineFunction::iterator MBBInsertPoint =1508std::next(CurrentMBB->getIterator());1509MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(ProbedBB);1510MF.insert(MBBInsertPoint, LoopMBB);1511MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(ProbedBB);1512MF.insert(MBBInsertPoint, ExitMBB);1513// Synthesize the loop body.1514allocateAndProbe(*LoopMBB, LoopMBB->end(), NegProbeSize, ScratchReg,1515UseDForm, FPReg);1516BuildMI(LoopMBB, DL, TII.get(isPPC64 ? PPC::BDNZ8 : PPC::BDNZ))1517.addMBB(LoopMBB);1518LoopMBB->addSuccessor(ExitMBB);1519LoopMBB->addSuccessor(LoopMBB);1520// Synthesize the exit MBB.1521ExitMBB->splice(ExitMBB->end(), CurrentMBB,1522std::next(MachineBasicBlock::iterator(MI)),1523CurrentMBB->end());1524ExitMBB->transferSuccessorsAndUpdatePHIs(CurrentMBB);1525CurrentMBB->addSuccessor(LoopMBB);1526if (needsCFI) {1527// Restore using SPReg to calculate CFA.1528buildDefCFAReg(*ExitMBB, ExitMBB->begin(), SPReg);1529}1530// Update liveins.1531fullyRecomputeLiveIns({ExitMBB, LoopMBB});1532}1533}1534++NumPrologProbed;1535MI.eraseFromParent();1536}15371538void PPCFrameLowering::emitEpilogue(MachineFunction &MF,1539MachineBasicBlock &MBB) const {1540MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();1541DebugLoc dl;15421543if (MBBI != MBB.end())1544dl = MBBI->getDebugLoc();15451546const PPCInstrInfo &TII = *Subtarget.getInstrInfo();1547const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();15481549// Get alignment info so we know how to restore the SP.1550const MachineFrameInfo &MFI = MF.getFrameInfo();15511552// Get the number of bytes allocated from the FrameInfo.1553int64_t FrameSize = MFI.getStackSize();15541555// Get processor type.1556bool isPPC64 = Subtarget.isPPC64();15571558// Check if the link register (LR) has been saved.1559PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();1560bool MustSaveLR = FI->mustSaveLR();1561const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();1562bool MustSaveCR = !MustSaveCRs.empty();1563// Do we have a frame pointer and/or base pointer for this function?1564bool HasFP = hasFP(MF);1565bool HasBP = RegInfo->hasBasePointer(MF);1566bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();1567bool HasROPProtect = Subtarget.hasROPProtect();1568bool HasPrivileged = Subtarget.hasPrivileged();15691570Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;1571Register BPReg = RegInfo->getBaseRegister(MF);1572Register FPReg = isPPC64 ? PPC::X31 : PPC::R31;1573Register ScratchReg;1574Register TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg1575const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR81576: PPC::MTLR );1577const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD1578: PPC::LWZ );1579const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS81580: PPC::LIS );1581const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR81582: PPC::OR );1583const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI81584: PPC::ORI );1585const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI81586: PPC::ADDI );1587const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD81588: PPC::ADD4 );1589const MCInstrDesc& LoadWordInst = TII.get( isPPC64 ? PPC::LWZ81590: PPC::LWZ);1591const MCInstrDesc& MoveToCRInst = TII.get( isPPC64 ? PPC::MTOCRF81592: PPC::MTOCRF);1593const MCInstrDesc &HashChk =1594TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHCHKP8 : PPC::HASHCHK8)1595: (HasPrivileged ? PPC::HASHCHKP : PPC::HASHCHK));1596int64_t LROffset = getReturnSaveOffset();15971598int64_t FPOffset = 0;15991600// Using the same bool variable as below to suppress compiler warnings.1601bool SingleScratchReg = findScratchRegister(&MBB, true, false, &ScratchReg,1602&TempReg);1603assert(SingleScratchReg &&1604"Could not find an available scratch register");16051606SingleScratchReg = ScratchReg == TempReg;16071608if (HasFP) {1609int FPIndex = FI->getFramePointerSaveIndex();1610assert(FPIndex && "No Frame Pointer Save Slot!");1611FPOffset = MFI.getObjectOffset(FPIndex);1612}16131614int64_t BPOffset = 0;1615if (HasBP) {1616int BPIndex = FI->getBasePointerSaveIndex();1617assert(BPIndex && "No Base Pointer Save Slot!");1618BPOffset = MFI.getObjectOffset(BPIndex);1619}16201621int64_t PBPOffset = 0;1622if (FI->usesPICBase()) {1623int PBPIndex = FI->getPICBasePointerSaveIndex();1624assert(PBPIndex && "No PIC Base Pointer Save Slot!");1625PBPOffset = MFI.getObjectOffset(PBPIndex);1626}16271628bool IsReturnBlock = (MBBI != MBB.end() && MBBI->isReturn());16291630if (IsReturnBlock) {1631unsigned RetOpcode = MBBI->getOpcode();1632bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||1633RetOpcode == PPC::TCRETURNdi ||1634RetOpcode == PPC::TCRETURNai ||1635RetOpcode == PPC::TCRETURNri8 ||1636RetOpcode == PPC::TCRETURNdi8 ||1637RetOpcode == PPC::TCRETURNai8;16381639if (UsesTCRet) {1640int MaxTCRetDelta = FI->getTailCallSPDelta();1641MachineOperand &StackAdjust = MBBI->getOperand(1);1642assert(StackAdjust.isImm() && "Expecting immediate value.");1643// Adjust stack pointer.1644int StackAdj = StackAdjust.getImm();1645int Delta = StackAdj - MaxTCRetDelta;1646assert((Delta >= 0) && "Delta must be positive");1647if (MaxTCRetDelta>0)1648FrameSize += (StackAdj +Delta);1649else1650FrameSize += StackAdj;1651}1652}16531654// Frames of 32KB & larger require special handling because they cannot be1655// indexed into with a simple LD/LWZ immediate offset operand.1656bool isLargeFrame = !isInt<16>(FrameSize);16571658// On targets without red zone, the SP needs to be restored last, so that1659// all live contents of the stack frame are upwards of the SP. This means1660// that we cannot restore SP just now, since there may be more registers1661// to restore from the stack frame (e.g. R31). If the frame size is not1662// a simple immediate value, we will need a spare register to hold the1663// restored SP. If the frame size is known and small, we can simply adjust1664// the offsets of the registers to be restored, and still use SP to restore1665// them. In such case, the final update of SP will be to add the frame1666// size to it.1667// To simplify the code, set RBReg to the base register used to restore1668// values from the stack, and set SPAdd to the value that needs to be added1669// to the SP at the end. The default values are as if red zone was present.1670unsigned RBReg = SPReg;1671uint64_t SPAdd = 0;16721673// Check if we can move the stack update instruction up the epilogue1674// past the callee saves. This will allow the move to LR instruction1675// to be executed before the restores of the callee saves which means1676// that the callee saves can hide the latency from the MTLR instrcution.1677MachineBasicBlock::iterator StackUpdateLoc = MBBI;1678if (stackUpdateCanBeMoved(MF)) {1679const std::vector<CalleeSavedInfo> & Info = MFI.getCalleeSavedInfo();1680for (CalleeSavedInfo CSI : Info) {1681// If the callee saved register is spilled to another register abort the1682// stack update movement.1683if (CSI.isSpilledToReg()) {1684StackUpdateLoc = MBBI;1685break;1686}1687int FrIdx = CSI.getFrameIdx();1688// If the frame index is not negative the callee saved info belongs to a1689// stack object that is not a fixed stack object. We ignore non-fixed1690// stack objects because we won't move the update of the stack pointer1691// past them.1692if (FrIdx >= 0)1693continue;16941695if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0)1696StackUpdateLoc--;1697else {1698// Abort the operation as we can't update all CSR restores.1699StackUpdateLoc = MBBI;1700break;1701}1702}1703}17041705if (FrameSize) {1706// In the prologue, the loaded (or persistent) stack pointer value is1707// offset by the STDU/STDUX/STWU/STWUX instruction. For targets with red1708// zone add this offset back now.17091710// If the function has a base pointer, the stack pointer has been copied1711// to it so we can restore it by copying in the other direction.1712if (HasRedZone && HasBP) {1713BuildMI(MBB, MBBI, dl, OrInst, RBReg).1714addReg(BPReg).1715addReg(BPReg);1716}1717// If this function contained a fastcc call and GuaranteedTailCallOpt is1718// enabled (=> hasFastCall()==true) the fastcc call might contain a tail1719// call which invalidates the stack pointer value in SP(0). So we use the1720// value of R31 in this case. Similar situation exists with setjmp.1721else if (FI->hasFastCall() || MF.exposesReturnsTwice()) {1722assert(HasFP && "Expecting a valid frame pointer.");1723if (!HasRedZone)1724RBReg = FPReg;1725if (!isLargeFrame) {1726BuildMI(MBB, MBBI, dl, AddImmInst, RBReg)1727.addReg(FPReg).addImm(FrameSize);1728} else {1729TII.materializeImmPostRA(MBB, MBBI, dl, ScratchReg, FrameSize);1730BuildMI(MBB, MBBI, dl, AddInst)1731.addReg(RBReg)1732.addReg(FPReg)1733.addReg(ScratchReg);1734}1735} else if (!isLargeFrame && !HasBP && !MFI.hasVarSizedObjects()) {1736if (HasRedZone) {1737BuildMI(MBB, StackUpdateLoc, dl, AddImmInst, SPReg)1738.addReg(SPReg)1739.addImm(FrameSize);1740} else {1741// Make sure that adding FrameSize will not overflow the max offset1742// size.1743assert(FPOffset <= 0 && BPOffset <= 0 && PBPOffset <= 0 &&1744"Local offsets should be negative");1745SPAdd = FrameSize;1746FPOffset += FrameSize;1747BPOffset += FrameSize;1748PBPOffset += FrameSize;1749}1750} else {1751// We don't want to use ScratchReg as a base register, because it1752// could happen to be R0. Use FP instead, but make sure to preserve it.1753if (!HasRedZone) {1754// If FP is not saved, copy it to ScratchReg.1755if (!HasFP)1756BuildMI(MBB, MBBI, dl, OrInst, ScratchReg)1757.addReg(FPReg)1758.addReg(FPReg);1759RBReg = FPReg;1760}1761BuildMI(MBB, StackUpdateLoc, dl, LoadInst, RBReg)1762.addImm(0)1763.addReg(SPReg);1764}1765}1766assert(RBReg != ScratchReg && "Should have avoided ScratchReg");1767// If there is no red zone, ScratchReg may be needed for holding a useful1768// value (although not the base register). Make sure it is not overwritten1769// too early.17701771// If we need to restore both the LR and the CR and we only have one1772// available scratch register, we must do them one at a time.1773if (MustSaveCR && SingleScratchReg && MustSaveLR) {1774// Here TempReg == ScratchReg, and in the absence of red zone ScratchReg1775// is live here.1776assert(HasRedZone && "Expecting red zone");1777BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)1778.addImm(CRSaveOffset)1779.addReg(SPReg);1780for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)1781BuildMI(MBB, MBBI, dl, MoveToCRInst, MustSaveCRs[i])1782.addReg(TempReg, getKillRegState(i == e-1));1783}17841785// Delay restoring of the LR if ScratchReg is needed. This is ok, since1786// LR is stored in the caller's stack frame. ScratchReg will be needed1787// if RBReg is anything other than SP. We shouldn't use ScratchReg as1788// a base register anyway, because it may happen to be R0.1789bool LoadedLR = false;1790if (MustSaveLR && RBReg == SPReg && isInt<16>(LROffset+SPAdd)) {1791BuildMI(MBB, StackUpdateLoc, dl, LoadInst, ScratchReg)1792.addImm(LROffset+SPAdd)1793.addReg(RBReg);1794LoadedLR = true;1795}17961797if (MustSaveCR && !(SingleScratchReg && MustSaveLR)) {1798assert(RBReg == SPReg && "Should be using SP as a base register");1799BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)1800.addImm(CRSaveOffset)1801.addReg(RBReg);1802}18031804if (HasFP) {1805// If there is red zone, restore FP directly, since SP has already been1806// restored. Otherwise, restore the value of FP into ScratchReg.1807if (HasRedZone || RBReg == SPReg)1808BuildMI(MBB, MBBI, dl, LoadInst, FPReg)1809.addImm(FPOffset)1810.addReg(SPReg);1811else1812BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)1813.addImm(FPOffset)1814.addReg(RBReg);1815}18161817if (FI->usesPICBase())1818BuildMI(MBB, MBBI, dl, LoadInst, PPC::R30)1819.addImm(PBPOffset)1820.addReg(RBReg);18211822if (HasBP)1823BuildMI(MBB, MBBI, dl, LoadInst, BPReg)1824.addImm(BPOffset)1825.addReg(RBReg);18261827// There is nothing more to be loaded from the stack, so now we can1828// restore SP: SP = RBReg + SPAdd.1829if (RBReg != SPReg || SPAdd != 0) {1830assert(!HasRedZone && "This should not happen with red zone");1831// If SPAdd is 0, generate a copy.1832if (SPAdd == 0)1833BuildMI(MBB, MBBI, dl, OrInst, SPReg)1834.addReg(RBReg)1835.addReg(RBReg);1836else1837BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)1838.addReg(RBReg)1839.addImm(SPAdd);18401841assert(RBReg != ScratchReg && "Should be using FP or SP as base register");1842if (RBReg == FPReg)1843BuildMI(MBB, MBBI, dl, OrInst, FPReg)1844.addReg(ScratchReg)1845.addReg(ScratchReg);18461847// Now load the LR from the caller's stack frame.1848if (MustSaveLR && !LoadedLR)1849BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)1850.addImm(LROffset)1851.addReg(SPReg);1852}18531854if (MustSaveCR &&1855!(SingleScratchReg && MustSaveLR))1856for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)1857BuildMI(MBB, MBBI, dl, MoveToCRInst, MustSaveCRs[i])1858.addReg(TempReg, getKillRegState(i == e-1));18591860if (MustSaveLR) {1861// If ROP protection is required, an extra instruction is added to compute a1862// hash and then compare it to the hash stored in the prologue.1863if (HasROPProtect) {1864const int SaveIndex = FI->getROPProtectionHashSaveIndex();1865const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);1866assert((ImmOffset <= -8 && ImmOffset >= -512) &&1867"ROP hash check location offset out of range.");1868assert(((ImmOffset & 0x7) == 0) &&1869"ROP hash check location offset must be 8 byte aligned.");1870BuildMI(MBB, StackUpdateLoc, dl, HashChk)1871.addReg(ScratchReg)1872.addImm(ImmOffset)1873.addReg(SPReg);1874}1875BuildMI(MBB, StackUpdateLoc, dl, MTLRInst).addReg(ScratchReg);1876}18771878// Callee pop calling convention. Pop parameter/linkage area. Used for tail1879// call optimization1880if (IsReturnBlock) {1881unsigned RetOpcode = MBBI->getOpcode();1882if (MF.getTarget().Options.GuaranteedTailCallOpt &&1883(RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&1884MF.getFunction().getCallingConv() == CallingConv::Fast) {1885PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();1886unsigned CallerAllocatedAmt = FI->getMinReservedArea();18871888if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {1889BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)1890.addReg(SPReg).addImm(CallerAllocatedAmt);1891} else {1892BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)1893.addImm(CallerAllocatedAmt >> 16);1894BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)1895.addReg(ScratchReg, RegState::Kill)1896.addImm(CallerAllocatedAmt & 0xFFFF);1897BuildMI(MBB, MBBI, dl, AddInst)1898.addReg(SPReg)1899.addReg(FPReg)1900.addReg(ScratchReg);1901}1902} else {1903createTailCallBranchInstr(MBB);1904}1905}1906}19071908void PPCFrameLowering::createTailCallBranchInstr(MachineBasicBlock &MBB) const {1909MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();19101911// If we got this far a first terminator should exist.1912assert(MBBI != MBB.end() && "Failed to find the first terminator.");19131914DebugLoc dl = MBBI->getDebugLoc();1915const PPCInstrInfo &TII = *Subtarget.getInstrInfo();19161917// Create branch instruction for pseudo tail call return instruction.1918// The TCRETURNdi variants are direct calls. Valid targets for those are1919// MO_GlobalAddress operands as well as MO_ExternalSymbol with PC-Rel1920// since we can tail call external functions with PC-Rel (i.e. we don't need1921// to worry about different TOC pointers). Some of the external functions will1922// be MO_GlobalAddress while others like memcpy for example, are going to1923// be MO_ExternalSymbol.1924unsigned RetOpcode = MBBI->getOpcode();1925if (RetOpcode == PPC::TCRETURNdi) {1926MBBI = MBB.getLastNonDebugInstr();1927MachineOperand &JumpTarget = MBBI->getOperand(0);1928if (JumpTarget.isGlobal())1929BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).1930addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());1931else if (JumpTarget.isSymbol())1932BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).1933addExternalSymbol(JumpTarget.getSymbolName());1934else1935llvm_unreachable("Expecting Global or External Symbol");1936} else if (RetOpcode == PPC::TCRETURNri) {1937MBBI = MBB.getLastNonDebugInstr();1938assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");1939BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));1940} else if (RetOpcode == PPC::TCRETURNai) {1941MBBI = MBB.getLastNonDebugInstr();1942MachineOperand &JumpTarget = MBBI->getOperand(0);1943BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());1944} else if (RetOpcode == PPC::TCRETURNdi8) {1945MBBI = MBB.getLastNonDebugInstr();1946MachineOperand &JumpTarget = MBBI->getOperand(0);1947if (JumpTarget.isGlobal())1948BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).1949addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());1950else if (JumpTarget.isSymbol())1951BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).1952addExternalSymbol(JumpTarget.getSymbolName());1953else1954llvm_unreachable("Expecting Global or External Symbol");1955} else if (RetOpcode == PPC::TCRETURNri8) {1956MBBI = MBB.getLastNonDebugInstr();1957assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");1958BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));1959} else if (RetOpcode == PPC::TCRETURNai8) {1960MBBI = MBB.getLastNonDebugInstr();1961MachineOperand &JumpTarget = MBBI->getOperand(0);1962BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());1963}1964}19651966void PPCFrameLowering::determineCalleeSaves(MachineFunction &MF,1967BitVector &SavedRegs,1968RegScavenger *RS) const {1969TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);1970if (Subtarget.isAIXABI())1971updateCalleeSaves(MF, SavedRegs);19721973const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();19741975// Do not explicitly save the callee saved VSRp registers.1976// The individual VSR subregisters will be saved instead.1977SavedRegs.reset(PPC::VSRp26);1978SavedRegs.reset(PPC::VSRp27);1979SavedRegs.reset(PPC::VSRp28);1980SavedRegs.reset(PPC::VSRp29);1981SavedRegs.reset(PPC::VSRp30);1982SavedRegs.reset(PPC::VSRp31);19831984// Save and clear the LR state.1985PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();1986unsigned LR = RegInfo->getRARegister();1987FI->setMustSaveLR(MustSaveLR(MF, LR));1988SavedRegs.reset(LR);19891990// Save R31 if necessary1991int FPSI = FI->getFramePointerSaveIndex();1992const bool isPPC64 = Subtarget.isPPC64();1993MachineFrameInfo &MFI = MF.getFrameInfo();19941995// If the frame pointer save index hasn't been defined yet.1996if (!FPSI && needsFP(MF)) {1997// Find out what the fix offset of the frame pointer save area.1998int FPOffset = getFramePointerSaveOffset();1999// Allocate the frame index for frame pointer save area.2000FPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);2001// Save the result.2002FI->setFramePointerSaveIndex(FPSI);2003}20042005int BPSI = FI->getBasePointerSaveIndex();2006if (!BPSI && RegInfo->hasBasePointer(MF)) {2007int BPOffset = getBasePointerSaveOffset();2008// Allocate the frame index for the base pointer save area.2009BPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);2010// Save the result.2011FI->setBasePointerSaveIndex(BPSI);2012}20132014// Reserve stack space for the PIC Base register (R30).2015// Only used in SVR4 32-bit.2016if (FI->usesPICBase()) {2017int PBPSI = MFI.CreateFixedObject(4, -8, true);2018FI->setPICBasePointerSaveIndex(PBPSI);2019}20202021// Make sure we don't explicitly spill r31, because, for example, we have2022// some inline asm which explicitly clobbers it, when we otherwise have a2023// frame pointer and are using r31's spill slot for the prologue/epilogue2024// code. Same goes for the base pointer and the PIC base register.2025if (needsFP(MF))2026SavedRegs.reset(isPPC64 ? PPC::X31 : PPC::R31);2027if (RegInfo->hasBasePointer(MF)) {2028SavedRegs.reset(RegInfo->getBaseRegister(MF));2029// On AIX, when BaseRegister(R30) is used, need to spill r31 too to match2030// AIX trackback table requirement.2031if (!needsFP(MF) && !SavedRegs.test(isPPC64 ? PPC::X31 : PPC::R31) &&2032Subtarget.isAIXABI()) {2033assert(2034(RegInfo->getBaseRegister(MF) == (isPPC64 ? PPC::X30 : PPC::R30)) &&2035"Invalid base register on AIX!");2036SavedRegs.set(isPPC64 ? PPC::X31 : PPC::R31);2037}2038}2039if (FI->usesPICBase())2040SavedRegs.reset(PPC::R30);20412042// Reserve stack space to move the linkage area to in case of a tail call.2043int TCSPDelta = 0;2044if (MF.getTarget().Options.GuaranteedTailCallOpt &&2045(TCSPDelta = FI->getTailCallSPDelta()) < 0) {2046MFI.CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);2047}20482049// Allocate the nonvolatile CR spill slot iff the function uses CR 2, 3, or 4.2050// For 64-bit SVR4, and all flavors of AIX we create a FixedStack2051// object at the offset of the CR-save slot in the linkage area. The actual2052// save and restore of the condition register will be created as part of the2053// prologue and epilogue insertion, but the FixedStack object is needed to2054// keep the CalleSavedInfo valid.2055if ((SavedRegs.test(PPC::CR2) || SavedRegs.test(PPC::CR3) ||2056SavedRegs.test(PPC::CR4))) {2057const uint64_t SpillSize = 4; // Condition register is always 4 bytes.2058const int64_t SpillOffset =2059Subtarget.isPPC64() ? 8 : Subtarget.isAIXABI() ? 4 : -4;2060int FrameIdx =2061MFI.CreateFixedObject(SpillSize, SpillOffset,2062/* IsImmutable */ true, /* IsAliased */ false);2063FI->setCRSpillFrameIndex(FrameIdx);2064}2065}20662067void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,2068RegScavenger *RS) const {2069// Get callee saved register information.2070MachineFrameInfo &MFI = MF.getFrameInfo();2071const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();20722073// If the function is shrink-wrapped, and if the function has a tail call, the2074// tail call might not be in the new RestoreBlock, so real branch instruction2075// won't be generated by emitEpilogue(), because shrink-wrap has chosen new2076// RestoreBlock. So we handle this case here.2077if (MFI.getSavePoint() && MFI.hasTailCall()) {2078MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();2079for (MachineBasicBlock &MBB : MF) {2080if (MBB.isReturnBlock() && (&MBB) != RestoreBlock)2081createTailCallBranchInstr(MBB);2082}2083}20842085// Early exit if no callee saved registers are modified!2086if (CSI.empty() && !needsFP(MF)) {2087addScavengingSpillSlot(MF, RS);2088return;2089}20902091unsigned MinGPR = PPC::R31;2092unsigned MinG8R = PPC::X31;2093unsigned MinFPR = PPC::F31;2094unsigned MinVR = Subtarget.hasSPE() ? PPC::S31 : PPC::V31;20952096bool HasGPSaveArea = false;2097bool HasG8SaveArea = false;2098bool HasFPSaveArea = false;2099bool HasVRSaveArea = false;21002101SmallVector<CalleeSavedInfo, 18> GPRegs;2102SmallVector<CalleeSavedInfo, 18> G8Regs;2103SmallVector<CalleeSavedInfo, 18> FPRegs;2104SmallVector<CalleeSavedInfo, 18> VRegs;21052106for (const CalleeSavedInfo &I : CSI) {2107Register Reg = I.getReg();2108assert((!MF.getInfo<PPCFunctionInfo>()->mustSaveTOC() ||2109(Reg != PPC::X2 && Reg != PPC::R2)) &&2110"Not expecting to try to spill R2 in a function that must save TOC");2111if (PPC::GPRCRegClass.contains(Reg)) {2112HasGPSaveArea = true;21132114GPRegs.push_back(I);21152116if (Reg < MinGPR) {2117MinGPR = Reg;2118}2119} else if (PPC::G8RCRegClass.contains(Reg)) {2120HasG8SaveArea = true;21212122G8Regs.push_back(I);21232124if (Reg < MinG8R) {2125MinG8R = Reg;2126}2127} else if (PPC::F8RCRegClass.contains(Reg)) {2128HasFPSaveArea = true;21292130FPRegs.push_back(I);21312132if (Reg < MinFPR) {2133MinFPR = Reg;2134}2135} else if (PPC::CRBITRCRegClass.contains(Reg) ||2136PPC::CRRCRegClass.contains(Reg)) {2137; // do nothing, as we already know whether CRs are spilled2138} else if (PPC::VRRCRegClass.contains(Reg) ||2139PPC::SPERCRegClass.contains(Reg)) {2140// Altivec and SPE are mutually exclusive, but have the same stack2141// alignment requirements, so overload the save area for both cases.2142HasVRSaveArea = true;21432144VRegs.push_back(I);21452146if (Reg < MinVR) {2147MinVR = Reg;2148}2149} else {2150llvm_unreachable("Unknown RegisterClass!");2151}2152}21532154PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();2155const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();21562157int64_t LowerBound = 0;21582159// Take into account stack space reserved for tail calls.2160int TCSPDelta = 0;2161if (MF.getTarget().Options.GuaranteedTailCallOpt &&2162(TCSPDelta = PFI->getTailCallSPDelta()) < 0) {2163LowerBound = TCSPDelta;2164}21652166// The Floating-point register save area is right below the back chain word2167// of the previous stack frame.2168if (HasFPSaveArea) {2169for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {2170int FI = FPRegs[i].getFrameIdx();21712172MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));2173}21742175LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;2176}21772178// Check whether the frame pointer register is allocated. If so, make sure it2179// is spilled to the correct offset.2180if (needsFP(MF)) {2181int FI = PFI->getFramePointerSaveIndex();2182assert(FI && "No Frame Pointer Save Slot!");2183MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));2184// FP is R31/X31, so no need to update MinGPR/MinG8R.2185HasGPSaveArea = true;2186}21872188if (PFI->usesPICBase()) {2189int FI = PFI->getPICBasePointerSaveIndex();2190assert(FI && "No PIC Base Pointer Save Slot!");2191MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));21922193MinGPR = std::min<unsigned>(MinGPR, PPC::R30);2194HasGPSaveArea = true;2195}21962197const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();2198if (RegInfo->hasBasePointer(MF)) {2199int FI = PFI->getBasePointerSaveIndex();2200assert(FI && "No Base Pointer Save Slot!");2201MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));22022203Register BP = RegInfo->getBaseRegister(MF);2204if (PPC::G8RCRegClass.contains(BP)) {2205MinG8R = std::min<unsigned>(MinG8R, BP);2206HasG8SaveArea = true;2207} else if (PPC::GPRCRegClass.contains(BP)) {2208MinGPR = std::min<unsigned>(MinGPR, BP);2209HasGPSaveArea = true;2210}2211}22122213// General register save area starts right below the Floating-point2214// register save area.2215if (HasGPSaveArea || HasG8SaveArea) {2216// Move general register save area spill slots down, taking into account2217// the size of the Floating-point register save area.2218for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {2219if (!GPRegs[i].isSpilledToReg()) {2220int FI = GPRegs[i].getFrameIdx();2221MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));2222}2223}22242225// Move general register save area spill slots down, taking into account2226// the size of the Floating-point register save area.2227for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {2228if (!G8Regs[i].isSpilledToReg()) {2229int FI = G8Regs[i].getFrameIdx();2230MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));2231}2232}22332234unsigned MinReg =2235std::min<unsigned>(TRI->getEncodingValue(MinGPR),2236TRI->getEncodingValue(MinG8R));22372238const unsigned GPRegSize = Subtarget.isPPC64() ? 8 : 4;2239LowerBound -= (31 - MinReg + 1) * GPRegSize;2240}22412242// For 32-bit only, the CR save area is below the general register2243// save area. For 64-bit SVR4, the CR save area is addressed relative2244// to the stack pointer and hence does not need an adjustment here.2245// Only CR2 (the first nonvolatile spilled) has an associated frame2246// index so that we have a single uniform save area.2247if (spillsCR(MF) && Subtarget.is32BitELFABI()) {2248// Adjust the frame index of the CR spill slot.2249for (const auto &CSInfo : CSI) {2250if (CSInfo.getReg() == PPC::CR2) {2251int FI = CSInfo.getFrameIdx();2252MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));2253break;2254}2255}22562257LowerBound -= 4; // The CR save area is always 4 bytes long.2258}22592260// Both Altivec and SPE have the same alignment and padding requirements2261// within the stack frame.2262if (HasVRSaveArea) {2263// Insert alignment padding, we need 16-byte alignment. Note: for positive2264// number the alignment formula is : y = (x + (n-1)) & (~(n-1)). But since2265// we are using negative number here (the stack grows downward). We should2266// use formula : y = x & (~(n-1)). Where x is the size before aligning, n2267// is the alignment size ( n = 16 here) and y is the size after aligning.2268assert(LowerBound <= 0 && "Expect LowerBound have a non-positive value!");2269LowerBound &= ~(15);22702271for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {2272int FI = VRegs[i].getFrameIdx();22732274MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));2275}2276}22772278addScavengingSpillSlot(MF, RS);2279}22802281void2282PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,2283RegScavenger *RS) const {2284// Reserve a slot closest to SP or frame pointer if we have a dynalloc or2285// a large stack, which will require scavenging a register to materialize a2286// large offset.22872288// We need to have a scavenger spill slot for spills if the frame size is2289// large. In case there is no free register for large-offset addressing,2290// this slot is used for the necessary emergency spill. Also, we need the2291// slot for dynamic stack allocations.22922293// The scavenger might be invoked if the frame offset does not fit into2294// the 16-bit immediate in case of not SPE and 8-bit in case of SPE.2295// We don't know the complete frame size here because we've not yet computed2296// callee-saved register spills or the needed alignment padding.2297unsigned StackSize = determineFrameLayout(MF, true);2298MachineFrameInfo &MFI = MF.getFrameInfo();2299bool NeedSpills = Subtarget.hasSPE() ? !isInt<8>(StackSize) : !isInt<16>(StackSize);23002301if (MFI.hasVarSizedObjects() || spillsCR(MF) || hasNonRISpills(MF) ||2302(hasSpills(MF) && NeedSpills)) {2303const TargetRegisterClass &GPRC = PPC::GPRCRegClass;2304const TargetRegisterClass &G8RC = PPC::G8RCRegClass;2305const TargetRegisterClass &RC = Subtarget.isPPC64() ? G8RC : GPRC;2306const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();2307unsigned Size = TRI.getSpillSize(RC);2308Align Alignment = TRI.getSpillAlign(RC);2309RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Alignment, false));23102311// Might we have over-aligned allocas?2312bool HasAlVars =2313MFI.hasVarSizedObjects() && MFI.getMaxAlign() > getStackAlign();23142315// These kinds of spills might need two registers.2316if (spillsCR(MF) || HasAlVars)2317RS->addScavengingFrameIndex(2318MFI.CreateStackObject(Size, Alignment, false));2319}2320}23212322// This function checks if a callee saved gpr can be spilled to a volatile2323// vector register. This occurs for leaf functions when the option2324// ppc-enable-pe-vector-spills is enabled. If there are any remaining registers2325// which were not spilled to vectors, return false so the target independent2326// code can handle them by assigning a FrameIdx to a stack slot.2327bool PPCFrameLowering::assignCalleeSavedSpillSlots(2328MachineFunction &MF, const TargetRegisterInfo *TRI,2329std::vector<CalleeSavedInfo> &CSI) const {23302331if (CSI.empty())2332return true; // Early exit if no callee saved registers are modified!23332334const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();2335const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);2336const MachineRegisterInfo &MRI = MF.getRegInfo();23372338if (Subtarget.hasSPE()) {2339// In case of SPE we only have SuperRegs and CRs2340// in our CalleSaveInfo vector.23412342for (auto &CalleeSaveReg : CSI) {2343MCPhysReg Reg = CalleeSaveReg.getReg();2344MCPhysReg Lower = RegInfo->getSubReg(Reg, 1);2345MCPhysReg Higher = RegInfo->getSubReg(Reg, 2);23462347if ( // Check only for SuperRegs.2348Lower &&2349// Replace Reg if only lower-32 bits modified2350!MRI.isPhysRegModified(Higher))2351CalleeSaveReg = CalleeSavedInfo(Lower);2352}2353}23542355// Early exit if cannot spill gprs to volatile vector registers.2356MachineFrameInfo &MFI = MF.getFrameInfo();2357if (!EnablePEVectorSpills || MFI.hasCalls() || !Subtarget.hasP9Vector())2358return false;23592360// Build a BitVector of VSRs that can be used for spilling GPRs.2361BitVector BVAllocatable = TRI->getAllocatableSet(MF);2362BitVector BVCalleeSaved(TRI->getNumRegs());2363for (unsigned i = 0; CSRegs[i]; ++i)2364BVCalleeSaved.set(CSRegs[i]);23652366for (unsigned Reg : BVAllocatable.set_bits()) {2367// Set to 0 if the register is not a volatile VSX register, or if it is2368// used in the function.2369if (BVCalleeSaved[Reg] || !PPC::VSRCRegClass.contains(Reg) ||2370MRI.isPhysRegUsed(Reg))2371BVAllocatable.reset(Reg);2372}23732374bool AllSpilledToReg = true;2375unsigned LastVSRUsedForSpill = 0;2376for (auto &CS : CSI) {2377if (BVAllocatable.none())2378return false;23792380Register Reg = CS.getReg();23812382if (!PPC::G8RCRegClass.contains(Reg)) {2383AllSpilledToReg = false;2384continue;2385}23862387// For P9, we can reuse LastVSRUsedForSpill to spill two GPRs2388// into one VSR using the mtvsrdd instruction.2389if (LastVSRUsedForSpill != 0) {2390CS.setDstReg(LastVSRUsedForSpill);2391BVAllocatable.reset(LastVSRUsedForSpill);2392LastVSRUsedForSpill = 0;2393continue;2394}23952396unsigned VolatileVFReg = BVAllocatable.find_first();2397if (VolatileVFReg < BVAllocatable.size()) {2398CS.setDstReg(VolatileVFReg);2399LastVSRUsedForSpill = VolatileVFReg;2400} else {2401AllSpilledToReg = false;2402}2403}2404return AllSpilledToReg;2405}24062407bool PPCFrameLowering::spillCalleeSavedRegisters(2408MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,2409ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {24102411MachineFunction *MF = MBB.getParent();2412const PPCInstrInfo &TII = *Subtarget.getInstrInfo();2413PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();2414bool MustSaveTOC = FI->mustSaveTOC();2415DebugLoc DL;2416bool CRSpilled = false;2417MachineInstrBuilder CRMIB;2418BitVector Spilled(TRI->getNumRegs());24192420VSRContainingGPRs.clear();24212422// Map each VSR to GPRs to be spilled with into it. Single VSR can contain one2423// or two GPRs, so we need table to record information for later save/restore.2424for (const CalleeSavedInfo &Info : CSI) {2425if (Info.isSpilledToReg()) {2426auto &SpilledVSR =2427VSRContainingGPRs.FindAndConstruct(Info.getDstReg()).second;2428assert(SpilledVSR.second == 0 &&2429"Can't spill more than two GPRs into VSR!");2430if (SpilledVSR.first == 0)2431SpilledVSR.first = Info.getReg();2432else2433SpilledVSR.second = Info.getReg();2434}2435}24362437for (const CalleeSavedInfo &I : CSI) {2438Register Reg = I.getReg();24392440// CR2 through CR4 are the nonvolatile CR fields.2441bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;24422443// Add the callee-saved register as live-in; it's killed at the spill.2444// Do not do this for callee-saved registers that are live-in to the2445// function because they will already be marked live-in and this will be2446// adding it for a second time. It is an error to add the same register2447// to the set more than once.2448const MachineRegisterInfo &MRI = MF->getRegInfo();2449bool IsLiveIn = MRI.isLiveIn(Reg);2450if (!IsLiveIn)2451MBB.addLiveIn(Reg);24522453if (CRSpilled && IsCRField) {2454CRMIB.addReg(Reg, RegState::ImplicitKill);2455continue;2456}24572458// The actual spill will happen in the prologue.2459if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)2460continue;24612462// Insert the spill to the stack frame.2463if (IsCRField) {2464PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();2465if (!Subtarget.is32BitELFABI()) {2466// The actual spill will happen at the start of the prologue.2467FuncInfo->addMustSaveCR(Reg);2468} else {2469CRSpilled = true;2470FuncInfo->setSpillsCR();24712472// 32-bit: FP-relative. Note that we made sure CR2-CR4 all have2473// the same frame index in PPCRegisterInfo::hasReservedSpillSlot.2474CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)2475.addReg(Reg, RegState::ImplicitKill);24762477MBB.insert(MI, CRMIB);2478MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))2479.addReg(PPC::R12,2480getKillRegState(true)),2481I.getFrameIdx()));2482}2483} else {2484if (I.isSpilledToReg()) {2485unsigned Dst = I.getDstReg();24862487if (Spilled[Dst])2488continue;24892490if (VSRContainingGPRs[Dst].second != 0) {2491assert(Subtarget.hasP9Vector() &&2492"mtvsrdd is unavailable on pre-P9 targets.");24932494NumPESpillVSR += 2;2495BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRDD), Dst)2496.addReg(VSRContainingGPRs[Dst].first, getKillRegState(true))2497.addReg(VSRContainingGPRs[Dst].second, getKillRegState(true));2498} else if (VSRContainingGPRs[Dst].second == 0) {2499assert(Subtarget.hasP8Vector() &&2500"Can't move GPR to VSR on pre-P8 targets.");25012502++NumPESpillVSR;2503BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRD),2504TRI->getSubReg(Dst, PPC::sub_64))2505.addReg(VSRContainingGPRs[Dst].first, getKillRegState(true));2506} else {2507llvm_unreachable("More than two GPRs spilled to a VSR!");2508}2509Spilled.set(Dst);2510} else {2511const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);2512// Use !IsLiveIn for the kill flag.2513// We do not want to kill registers that are live in this function2514// before their use because they will become undefined registers.2515// Functions without NoUnwind need to preserve the order of elements in2516// saved vector registers.2517if (Subtarget.needsSwapsForVSXMemOps() &&2518!MF->getFunction().hasFnAttribute(Attribute::NoUnwind))2519TII.storeRegToStackSlotNoUpd(MBB, MI, Reg, !IsLiveIn,2520I.getFrameIdx(), RC, TRI);2521else2522TII.storeRegToStackSlot(MBB, MI, Reg, !IsLiveIn, I.getFrameIdx(), RC,2523TRI, Register());2524}2525}2526}2527return true;2528}25292530static void restoreCRs(bool is31, bool CR2Spilled, bool CR3Spilled,2531bool CR4Spilled, MachineBasicBlock &MBB,2532MachineBasicBlock::iterator MI,2533ArrayRef<CalleeSavedInfo> CSI, unsigned CSIIndex) {25342535MachineFunction *MF = MBB.getParent();2536const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();2537DebugLoc DL;2538unsigned MoveReg = PPC::R12;25392540// 32-bit: FP-relative2541MBB.insert(MI,2542addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ), MoveReg),2543CSI[CSIIndex].getFrameIdx()));25442545unsigned RestoreOp = PPC::MTOCRF;2546if (CR2Spilled)2547MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)2548.addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));25492550if (CR3Spilled)2551MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)2552.addReg(MoveReg, getKillRegState(!CR4Spilled)));25532554if (CR4Spilled)2555MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)2556.addReg(MoveReg, getKillRegState(true)));2557}25582559MachineBasicBlock::iterator PPCFrameLowering::2560eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,2561MachineBasicBlock::iterator I) const {2562const TargetInstrInfo &TII = *Subtarget.getInstrInfo();2563if (MF.getTarget().Options.GuaranteedTailCallOpt &&2564I->getOpcode() == PPC::ADJCALLSTACKUP) {2565// Add (actually subtract) back the amount the callee popped on return.2566if (int CalleeAmt = I->getOperand(1).getImm()) {2567bool is64Bit = Subtarget.isPPC64();2568CalleeAmt *= -1;2569unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;2570unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;2571unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;2572unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;2573unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;2574unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;2575const DebugLoc &dl = I->getDebugLoc();25762577if (isInt<16>(CalleeAmt)) {2578BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)2579.addReg(StackReg, RegState::Kill)2580.addImm(CalleeAmt);2581} else {2582MachineBasicBlock::iterator MBBI = I;2583BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)2584.addImm(CalleeAmt >> 16);2585BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)2586.addReg(TmpReg, RegState::Kill)2587.addImm(CalleeAmt & 0xFFFF);2588BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)2589.addReg(StackReg, RegState::Kill)2590.addReg(TmpReg);2591}2592}2593}2594// Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.2595return MBB.erase(I);2596}25972598static bool isCalleeSavedCR(unsigned Reg) {2599return PPC::CR2 == Reg || Reg == PPC::CR3 || Reg == PPC::CR4;2600}26012602bool PPCFrameLowering::restoreCalleeSavedRegisters(2603MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,2604MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {2605MachineFunction *MF = MBB.getParent();2606const PPCInstrInfo &TII = *Subtarget.getInstrInfo();2607PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();2608bool MustSaveTOC = FI->mustSaveTOC();2609bool CR2Spilled = false;2610bool CR3Spilled = false;2611bool CR4Spilled = false;2612unsigned CSIIndex = 0;2613BitVector Restored(TRI->getNumRegs());26142615// Initialize insertion-point logic; we will be restoring in reverse2616// order of spill.2617MachineBasicBlock::iterator I = MI, BeforeI = I;2618bool AtStart = I == MBB.begin();26192620if (!AtStart)2621--BeforeI;26222623for (unsigned i = 0, e = CSI.size(); i != e; ++i) {2624Register Reg = CSI[i].getReg();26252626if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)2627continue;26282629// Restore of callee saved condition register field is handled during2630// epilogue insertion.2631if (isCalleeSavedCR(Reg) && !Subtarget.is32BitELFABI())2632continue;26332634if (Reg == PPC::CR2) {2635CR2Spilled = true;2636// The spill slot is associated only with CR2, which is the2637// first nonvolatile spilled. Save it here.2638CSIIndex = i;2639continue;2640} else if (Reg == PPC::CR3) {2641CR3Spilled = true;2642continue;2643} else if (Reg == PPC::CR4) {2644CR4Spilled = true;2645continue;2646} else {2647// On 32-bit ELF when we first encounter a non-CR register after seeing at2648// least one CR register, restore all spilled CRs together.2649if (CR2Spilled || CR3Spilled || CR4Spilled) {2650bool is31 = needsFP(*MF);2651restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI,2652CSIIndex);2653CR2Spilled = CR3Spilled = CR4Spilled = false;2654}26552656if (CSI[i].isSpilledToReg()) {2657DebugLoc DL;2658unsigned Dst = CSI[i].getDstReg();26592660if (Restored[Dst])2661continue;26622663if (VSRContainingGPRs[Dst].second != 0) {2664assert(Subtarget.hasP9Vector());2665NumPEReloadVSR += 2;2666BuildMI(MBB, I, DL, TII.get(PPC::MFVSRLD),2667VSRContainingGPRs[Dst].second)2668.addReg(Dst);2669BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD),2670VSRContainingGPRs[Dst].first)2671.addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));2672} else if (VSRContainingGPRs[Dst].second == 0) {2673assert(Subtarget.hasP8Vector());2674++NumPEReloadVSR;2675BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD),2676VSRContainingGPRs[Dst].first)2677.addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));2678} else {2679llvm_unreachable("More than two GPRs spilled to a VSR!");2680}26812682Restored.set(Dst);26832684} else {2685// Default behavior for non-CR saves.2686const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);26872688// Functions without NoUnwind need to preserve the order of elements in2689// saved vector registers.2690if (Subtarget.needsSwapsForVSXMemOps() &&2691!MF->getFunction().hasFnAttribute(Attribute::NoUnwind))2692TII.loadRegFromStackSlotNoUpd(MBB, I, Reg, CSI[i].getFrameIdx(), RC,2693TRI);2694else2695TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI,2696Register());26972698assert(I != MBB.begin() &&2699"loadRegFromStackSlot didn't insert any code!");2700}2701}27022703// Insert in reverse order.2704if (AtStart)2705I = MBB.begin();2706else {2707I = BeforeI;2708++I;2709}2710}27112712// If we haven't yet spilled the CRs, do so now.2713if (CR2Spilled || CR3Spilled || CR4Spilled) {2714assert(Subtarget.is32BitELFABI() &&2715"Only set CR[2|3|4]Spilled on 32-bit SVR4.");2716bool is31 = needsFP(*MF);2717restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI, CSIIndex);2718}27192720return true;2721}27222723uint64_t PPCFrameLowering::getTOCSaveOffset() const {2724return TOCSaveOffset;2725}27262727uint64_t PPCFrameLowering::getFramePointerSaveOffset() const {2728return FramePointerSaveOffset;2729}27302731uint64_t PPCFrameLowering::getBasePointerSaveOffset() const {2732return BasePointerSaveOffset;2733}27342735bool PPCFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {2736if (MF.getInfo<PPCFunctionInfo>()->shrinkWrapDisabled())2737return false;2738return !MF.getSubtarget<PPCSubtarget>().is32BitELFABI();2739}27402741void PPCFrameLowering::updateCalleeSaves(const MachineFunction &MF,2742BitVector &SavedRegs) const {2743// The AIX ABI uses traceback tables for EH which require that if callee-saved2744// register N is used, all registers N-31 must be saved/restored.2745// NOTE: The check for AIX is not actually what is relevant. Traceback tables2746// on Linux have the same requirements. It is just that AIX is the only ABI2747// for which we actually use traceback tables. If another ABI needs to be2748// supported that also uses them, we can add a check such as2749// Subtarget.usesTraceBackTables().2750assert(Subtarget.isAIXABI() &&2751"Function updateCalleeSaves should only be called for AIX.");27522753// If there are no callee saves then there is nothing to do.2754if (SavedRegs.none())2755return;27562757const MCPhysReg *CSRegs =2758Subtarget.getRegisterInfo()->getCalleeSavedRegs(&MF);2759MCPhysReg LowestGPR = PPC::R31;2760MCPhysReg LowestG8R = PPC::X31;2761MCPhysReg LowestFPR = PPC::F31;2762MCPhysReg LowestVR = PPC::V31;27632764// Traverse the CSRs twice so as not to rely on ascending ordering of2765// registers in the array. The first pass finds the lowest numbered2766// register and the second pass marks all higher numbered registers2767// for spilling.2768for (int i = 0; CSRegs[i]; i++) {2769// Get the lowest numbered register for each class that actually needs2770// to be saved.2771MCPhysReg Cand = CSRegs[i];2772if (!SavedRegs.test(Cand))2773continue;2774if (PPC::GPRCRegClass.contains(Cand) && Cand < LowestGPR)2775LowestGPR = Cand;2776else if (PPC::G8RCRegClass.contains(Cand) && Cand < LowestG8R)2777LowestG8R = Cand;2778else if ((PPC::F4RCRegClass.contains(Cand) ||2779PPC::F8RCRegClass.contains(Cand)) &&2780Cand < LowestFPR)2781LowestFPR = Cand;2782else if (PPC::VRRCRegClass.contains(Cand) && Cand < LowestVR)2783LowestVR = Cand;2784}27852786for (int i = 0; CSRegs[i]; i++) {2787MCPhysReg Cand = CSRegs[i];2788if ((PPC::GPRCRegClass.contains(Cand) && Cand > LowestGPR) ||2789(PPC::G8RCRegClass.contains(Cand) && Cand > LowestG8R) ||2790((PPC::F4RCRegClass.contains(Cand) ||2791PPC::F8RCRegClass.contains(Cand)) &&2792Cand > LowestFPR) ||2793(PPC::VRRCRegClass.contains(Cand) && Cand > LowestVR))2794SavedRegs.set(Cand);2795}2796}27972798uint64_t PPCFrameLowering::getStackThreshold() const {2799// On PPC64, we use `stux r1, r1, <scratch_reg>` to extend the stack;2800// use `add r1, r1, <scratch_reg>` to release the stack frame.2801// Scratch register contains a signed 64-bit number, which is negative2802// when extending the stack and is positive when releasing the stack frame.2803// To make `stux` and `add` paired, the absolute value of the number contained2804// in the scratch register should be the same. Thus the maximum stack size2805// is (2^63)-1, i.e., LONG_MAX.2806if (Subtarget.isPPC64())2807return LONG_MAX;28082809return TargetFrameLowering::getStackThreshold();2810}281128122813