LLVM 24.0.0git
LoongArchFrameLowering.cpp
Go to the documentation of this file.
1//===-- LoongArchFrameLowering.cpp - LoongArch Frame Information -*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the LoongArch implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
15#include "LoongArchSubtarget.h"
26#include "llvm/MC/MCDwarf.h"
27
28using namespace llvm;
29
30#define DEBUG_TYPE "loongarch-frame-lowering"
31
32// Return true if the specified function should have a dedicated frame
33// pointer register. This is true if frame pointer elimination is
34// disabled, if it needs dynamic stack realignment, if the function has
35// variable sized allocas, if the frame address is taken, or if the reserved
36// call frame is too large to reach the emergency spill slot from SP.
38 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
39
40 const MachineFrameInfo &MFI = MF.getFrameInfo();
41
42 if (MF.disableFramePointerElim() || RegInfo->hasStackRealignment(MF) ||
44 return true;
45
47 uint64_t MaxCallFrameSize = MFI.getMaxCallFrameSize();
48 if (STI.is64Bit() ? !isInt<15>(MaxCallFrameSize)
49 : !isInt<12>(MaxCallFrameSize))
50 return true;
51 }
52
53 return false;
54}
55
57 const MachineFrameInfo &MFI = MF.getFrameInfo();
58 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
59
60 return MFI.hasVarSizedObjects() && TRI->hasStackRealignment(MF);
61}
62
63void LoongArchFrameLowering::adjustReg(MachineBasicBlock &MBB,
65 const DebugLoc &DL, Register DestReg,
66 Register SrcReg, int64_t Val,
67 MachineInstr::MIFlag Flag) const {
68 const LoongArchInstrInfo *TII = STI.getInstrInfo();
69 bool IsLA64 = STI.is64Bit();
70 unsigned Addi = IsLA64 ? LoongArch::ADDI_D : LoongArch::ADDI_W;
71
72 if (DestReg == SrcReg && Val == 0)
73 return;
74
75 if (isInt<12>(Val)) {
76 // addi.w/d $DstReg, $SrcReg, Val
77 BuildMI(MBB, MBBI, DL, TII->get(Addi), DestReg)
78 .addReg(SrcReg)
79 .addImm(Val)
80 .setMIFlag(Flag);
81 return;
82 }
83
84 // Try to split the offset across two ADDIs. We need to keep the stack pointer
85 // aligned after each ADDI. We need to determine the maximum value we can put
86 // in each ADDI. In the negative direction, we can use -2048 which is always
87 // sufficiently aligned. In the positive direction, we need to find the
88 // largest 12-bit immediate that is aligned. Exclude -4096 since it can be
89 // created with LU12I.W.
90 assert(getStackAlign().value() < 2048 && "Stack alignment too large");
91 int64_t MaxPosAdjStep = 2048 - getStackAlign().value();
92 if (Val > -4096 && Val <= (2 * MaxPosAdjStep)) {
93 int64_t FirstAdj = Val < 0 ? -2048 : MaxPosAdjStep;
94 Val -= FirstAdj;
95 BuildMI(MBB, MBBI, DL, TII->get(Addi), DestReg)
96 .addReg(SrcReg)
97 .addImm(FirstAdj)
98 .setMIFlag(Flag);
99 BuildMI(MBB, MBBI, DL, TII->get(Addi), DestReg)
100 .addReg(DestReg, RegState::Kill)
101 .addImm(Val)
102 .setMIFlag(Flag);
103 return;
104 }
105
106 unsigned Opc = IsLA64 ? LoongArch::ADD_D : LoongArch::ADD_W;
107 if (Val < 0) {
108 Val = -Val;
109 Opc = IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W;
110 }
111
112 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
113 Register ScratchReg = MRI.createVirtualRegister(&LoongArch::GPRRegClass);
114 TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
115 BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
116 .addReg(SrcReg)
117 .addReg(ScratchReg, RegState::Kill)
118 .setMIFlag(Flag);
119}
120
121// Determine the size of the frame and maximum call frame size.
122void LoongArchFrameLowering::determineFrameLayout(MachineFunction &MF) const {
123 MachineFrameInfo &MFI = MF.getFrameInfo();
124
125 // Get the number of bytes to allocate from the FrameInfo.
126 uint64_t FrameSize = MFI.getStackSize();
127
128 // Make sure the frame is aligned.
129 FrameSize = alignTo(FrameSize, getStackAlign());
130
131 // Update frame info.
132 MFI.setStackSize(FrameSize);
133}
134
136 const MachineFunction &MF) {
137 uint64_t FuncSize = 0;
138 for (auto &MBB : MF)
139 for (auto &MI : MBB)
140 FuncSize += TII->getInstSizeInBytes(MI);
141 return FuncSize;
142}
143
145 if (!MF.getSubtarget<LoongArchSubtarget>().hasBasicF())
146 return false;
147 for (auto &MBB : MF)
148 for (auto &MI : MBB)
149 if (MI.getOpcode() == LoongArch::PseudoST_CFR)
150 return true;
151 return false;
152}
153
155 MachineFunction &MF, RegScavenger *RS) const {
156 const LoongArchRegisterInfo *RI = STI.getRegisterInfo();
157 const TargetRegisterClass &RC = LoongArch::GPRRegClass;
158 const LoongArchInstrInfo *TII = STI.getInstrInfo();
161 MachineFrameInfo &MFI = MF.getFrameInfo();
162
163 unsigned ScavSlotsNum = 0;
164
165 // Far branches beyond 27-bit offset require a spill slot for scratch
166 // register.
167 bool IsLargeFunction = !isInt<27>(estimateFunctionSizeInBytes(TII, MF));
168 if (IsLargeFunction)
169 ScavSlotsNum = 1;
170
171 // estimateStackSize has been observed to under-estimate the final stack
172 // size, so give ourselves wiggle-room by checking for stack size
173 // representable an 11-bit signed field rather than 12-bits.
174 // For [x]vstelm.{b/h/w/d} memory instructions with 8 imm offset, 7-bit
175 // signed field is fine.
176 unsigned EstimateStackSize = MFI.estimateStackSize(MF);
177 if (!isInt<11>(EstimateStackSize) ||
178 (MF.getSubtarget<LoongArchSubtarget>().hasExtLSX() &&
179 !isInt<7>(EstimateStackSize)))
180 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
181
182 // For CFR spill.
183 if (needScavSlotForCFR(MF))
184 ++ScavSlotsNum;
185
186 // Create emergency spill slots.
187 for (unsigned i = 0; i < ScavSlotsNum; ++i) {
188 int FI =
189 MFI.CreateSpillStackObject(RI->getSpillSize(RC), RI->getSpillAlign(RC));
190 RS->addScavengingFrameIndex(FI);
191 if (IsLargeFunction && LAFI->getBranchRelaxationSpillFrameIndex() == -1)
193 LLVM_DEBUG(dbgs() << "Allocated FI(" << FI
194 << ") as the emergency spill slot.\n");
195 }
196}
197
198// Allocate stack space and probe it if necessary.
199void LoongArchFrameLowering::allocateStack(MachineBasicBlock &MBB,
201 MachineFunction &MF, uint64_t Offset,
202 uint64_t RealStackSize, bool EmitCFI,
203 bool NeedProbe, uint64_t ProbeSize,
204 bool DynAllocation,
205 MachineInstr::MIFlag Flag) const {
206 DebugLoc DL;
207 const LoongArchInstrInfo *TII = STI.getInstrInfo();
208 const bool IsLA64 = STI.is64Bit();
209 const Register SPReg = LoongArch::R3;
211
212 // Simply allocate the stack if it's not big enough to require a probe.
213 if (!NeedProbe || Offset <= ProbeSize) {
214 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -Offset, Flag);
215 if (EmitCFI)
216 CFIBuilder.buildDefCFAOffset(RealStackSize);
217
218 if (NeedProbe && DynAllocation) {
219 // st.{w/d} $zero, $sp, 0
220 BuildMI(MBB, MBBI, DL,
221 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
222 .addReg(LoongArch::R0)
223 .addReg(SPReg)
224 .addImm(0)
225 .setMIFlag(Flag);
226 }
227
228 return;
229 }
230
231 // Unroll the probe loop depending on the number of iterations.
232 if (Offset < ProbeSize * 5) {
233 const uint64_t CFAAdjust = RealStackSize - Offset;
234
235 uint64_t CurrentOffset = 0;
236 while (CurrentOffset + ProbeSize <= Offset) {
237 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -ProbeSize, Flag);
238 // st.{w/d} $zero, $sp, 0
239 BuildMI(MBB, MBBI, DL,
240 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
241 .addReg(LoongArch::R0)
242 .addReg(SPReg)
243 .addImm(0)
244 .setMIFlag(Flag);
245
246 CurrentOffset += ProbeSize;
247 if (EmitCFI)
248 CFIBuilder.buildDefCFAOffset(CurrentOffset + CFAAdjust);
249 }
250
251 const uint64_t Residual = Offset - CurrentOffset;
252 if (Residual) {
253 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -Residual, Flag);
254 if (EmitCFI)
255 CFIBuilder.buildDefCFAOffset(RealStackSize);
256
257 if (DynAllocation) {
258 // st.{w/d} $zero, $sp, 0
259 BuildMI(MBB, MBBI, DL,
260 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
261 .addReg(LoongArch::R0)
262 .addReg(SPReg)
263 .addImm(0)
264 .setMIFlag(Flag);
265 }
266 }
267 return;
268 }
269
270 // Emit a variable-length allocation probing loop.
271 const uint64_t RoundedSize = alignDown(Offset, ProbeSize);
272 const uint64_t Residual = Offset - RoundedSize;
273 const uint64_t CFAAdjust = RealStackSize - Offset;
274
275 const Register TargetReg = LoongArch::R13;
276 // SUB TargetReg, $sp, RoundedSize
277 adjustReg(MBB, MBBI, DL, TargetReg, SPReg, -RoundedSize, Flag);
278
279 if (EmitCFI) {
280 // Set the CFA register to TargetReg.
281 CFIBuilder.buildDefCFA(TargetReg, RoundedSize + CFAAdjust);
282 }
283
284 // It will be expanded to a probe loop in inlineStackProbe().
285 BuildMI(MBB, MBBI, DL, TII->get(LoongArch::PROBED_STACKALLOC))
286 .addReg(TargetReg);
287
288 if (EmitCFI) {
289 // Set the CFA register back to SP.
290 CFIBuilder.buildDefCFARegister(SPReg);
291 }
292
293 if (Residual) {
294 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -Residual, Flag);
295 if (DynAllocation) {
296 // st.{w/d} $zero, $sp, 0
297 BuildMI(MBB, MBBI, DL,
298 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
299 .addReg(LoongArch::R0)
300 .addReg(SPReg)
301 .addImm(0)
302 .setMIFlag(Flag);
303 }
304 }
305
306 if (EmitCFI)
307 CFIBuilder.buildDefCFAOffset(RealStackSize);
308}
309
311 MachineBasicBlock &MBB) const {
312 MachineFrameInfo &MFI = MF.getFrameInfo();
313 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
314 const LoongArchRegisterInfo *RI = STI.getRegisterInfo();
315 const LoongArchInstrInfo *TII = STI.getInstrInfo();
317 bool IsLA64 = STI.is64Bit();
318
319 Register SPReg = LoongArch::R3;
320 Register FPReg = LoongArch::R22;
321
322 // Debug location must be unknown since the first debug location is used
323 // to determine the end of the prologue.
324 DebugLoc DL;
325 // All calls are tail calls in GHC calling conv, and functions have no
326 // prologue/epilogue.
328 return;
329 // Determine the correct frame layout
330 determineFrameLayout(MF);
331
332 // First, compute final stack size.
333 uint64_t StackSize = MFI.getStackSize();
334 uint64_t RealStackSize = StackSize;
335
336 // Early exit if there is no need to allocate space in the stack.
337 if (StackSize == 0 && !MFI.adjustsStack())
338 return;
339
340 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
341 // Split the SP adjustment to reduce the offsets of callee saved spill.
342 if (FirstSPAdjustAmount)
343 StackSize = FirstSPAdjustAmount;
344
345 // Adjust stack.
346 const LoongArchTargetLowering *TLI = STI.getTargetLowering();
347 const bool NeedProbe = TLI->hasInlineStackProbe(MF);
348 const uint64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
349 const bool DynAllocation =
350 MF.getInfo<LoongArchMachineFunctionInfo>()->hasDynamicAllocation();
351 if (StackSize != 0)
352 allocateStack(MBB, MBBI, MF, StackSize, StackSize,
353 /*EmitCFI=*/true, NeedProbe, ProbeSize, DynAllocation,
355
356 const auto &CSI = MFI.getCalleeSavedInfo();
357
358 // The frame pointer is callee-saved, and code has been generated for us to
359 // save it to the stack. We need to skip over the storing of callee-saved
360 // registers as the frame pointer must be modified after it has been saved
361 // to the stack, not before.
362 std::advance(MBBI, CSI.size());
363
364 // Iterate over list of callee-saved registers and emit .cfi_offset
365 // directives.
366 for (const auto &Entry : CSI) {
367 int64_t Offset = MFI.getObjectOffset(Entry.getFrameIdx());
368 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
369 nullptr, RI->getDwarfRegNum(Entry.getReg(), true), Offset));
370 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
371 .addCFIIndex(CFIIndex)
373 }
374
375 // Generate new FP.
376 if (hasFP(MF)) {
377 adjustReg(MBB, MBBI, DL, FPReg, SPReg,
378 StackSize - LoongArchFI->getVarArgsSaveSize(),
380
381 // Emit ".cfi_def_cfa $fp, LoongArchFI->getVarArgsSaveSize()"
382 unsigned CFIIndex = MF.addFrameInst(
383 MCCFIInstruction::cfiDefCfa(nullptr, RI->getDwarfRegNum(FPReg, true),
384 LoongArchFI->getVarArgsSaveSize()));
385 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
386 .addCFIIndex(CFIIndex)
388 }
389
390 // Emit the second SP adjustment after saving callee saved registers.
391 if (FirstSPAdjustAmount) {
392 uint64_t SecondSPAdjustAmount = RealStackSize - FirstSPAdjustAmount;
393 assert(SecondSPAdjustAmount > 0 &&
394 "SecondSPAdjustAmount should be greater than zero");
395 allocateStack(MBB, MBBI, MF, SecondSPAdjustAmount, RealStackSize,
396 !hasFP(MF), NeedProbe, ProbeSize, DynAllocation,
398 }
399
400 if (hasFP(MF)) {
401 // Realign stack.
402 if (RI->hasStackRealignment(MF)) {
403 unsigned Align = Log2(MFI.getMaxAlign());
404 assert(Align > 0 && "The stack realignment size is invalid!");
405 BuildMI(MBB, MBBI, DL,
406 TII->get(IsLA64 ? LoongArch::BSTRINS_D : LoongArch::BSTRINS_W),
407 SPReg)
408 .addReg(SPReg)
409 .addReg(LoongArch::R0)
410 .addImm(Align - 1)
411 .addImm(0)
413 // FP will be used to restore the frame in the epilogue, so we need
414 // another base register BP to record SP after re-alignment. SP will
415 // track the current stack after allocating variable sized objects.
416 if (hasBP(MF)) {
417 // move BP, $sp
418 BuildMI(MBB, MBBI, DL, TII->get(LoongArch::OR),
420 .addReg(SPReg)
421 .addReg(LoongArch::R0)
423 }
424 }
425 }
426}
427
429 MachineBasicBlock &MBB) const {
430 const LoongArchRegisterInfo *RI = STI.getRegisterInfo();
431 MachineFrameInfo &MFI = MF.getFrameInfo();
432 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
433 Register SPReg = LoongArch::R3;
434 // All calls are tail calls in GHC calling conv, and functions have no
435 // prologue/epilogue.
437 return;
438 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
439 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
440
441 const auto &CSI = MFI.getCalleeSavedInfo();
442 // Skip to before the restores of callee-saved registers.
443 auto LastFrameDestroy = MBBI;
444 if (!CSI.empty())
445 LastFrameDestroy = std::prev(MBBI, CSI.size());
446
447 // Get the number of bytes from FrameInfo.
448 uint64_t StackSize = MFI.getStackSize();
449
450 // Restore the stack pointer.
451 if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects()) {
452 assert(hasFP(MF) && "frame pointer should not have been eliminated");
453 adjustReg(MBB, LastFrameDestroy, DL, SPReg, LoongArch::R22,
454 -StackSize + LoongArchFI->getVarArgsSaveSize(),
456 }
457
458 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
459 if (FirstSPAdjustAmount) {
460 uint64_t SecondSPAdjustAmount = StackSize - FirstSPAdjustAmount;
461 assert(SecondSPAdjustAmount > 0 &&
462 "SecondSPAdjustAmount should be greater than zero");
463
464 adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
466 StackSize = FirstSPAdjustAmount;
467 }
468
469 // Deallocate stack
470 adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
471}
472
473// Synthesize the probe loop.
475 Register TargetReg) {
476 assert(TargetReg != LoongArch::R3 &&
477 "New top of stack cannot already be in $sp");
478
479 MachineBasicBlock &MBB = *MBBI->getParent();
480 MachineFunction &MF = *MBB.getParent();
481
483 const LoongArchInstrInfo *TII = STI.getInstrInfo();
484 const bool IsLA64 = STI.is64Bit();
485 const Align StackAlign = STI.getFrameLowering()->getStackAlign();
487 const uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
488
489 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
490 MachineBasicBlock *LoopTestMBB =
491 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
492 MF.insert(MBBInsertPoint, LoopTestMBB);
493 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
494 MF.insert(MBBInsertPoint, ExitMBB);
495 const Register SPReg = LoongArch::R3;
496 const Register ScratchReg = LoongArch::R14;
498
499 // ScratchReg = ProbeSize
500 TII->movImm(MBB, MBBI, DL, ScratchReg, ProbeSize, Flags);
501
502 // LoopTest:
503 // sub.{w/d} $sp, $sp, ScratchReg
504 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
505 TII->get(IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W), SPReg)
506 .addReg(SPReg)
507 .addReg(ScratchReg)
508 .setMIFlag(Flags);
509
510 // st.{w/d} $zero, $sp, 0
511 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
512 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
513 .addReg(LoongArch::R0)
514 .addReg(SPReg)
515 .addImm(0)
516 .setMIFlag(Flags);
517
518 // bne $sp, TargetReg, LoopTest
519 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(LoongArch::BNE))
520 .addReg(SPReg)
521 .addReg(TargetReg)
522 .addMBB(LoopTestMBB)
523 .setMIFlag(Flags);
524
525 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
527
528 LoopTestMBB->addSuccessor(ExitMBB);
529 LoopTestMBB->addSuccessor(LoopTestMBB);
530 MBB.addSuccessor(LoopTestMBB);
531 // Update liveins.
532 fullyRecomputeLiveIns({ExitMBB, LoopTestMBB});
533}
534
536 MachineBasicBlock &MBB) const {
537 // Get the instructions that need to be replaced. We emit at most two of
538 // these. Remember them in order to avoid complications coming from the need
539 // to traverse the block while potentially creating more blocks.
541 for (MachineInstr &MI : MBB) {
542 if (MI.getOpcode() == LoongArch::PROBED_STACKALLOC) {
543 ToReplace.push_back(&MI);
544 }
545 }
546
547 for (MachineInstr *MI : ToReplace) {
548 MachineBasicBlock::iterator MBBI = MI->getIterator();
549 DebugLoc DL = MBB.findDebugLoc(MBBI);
550 Register TargetReg = MI->getOperand(0).getReg();
551 emitStackProbeInline(MBBI, DL, TargetReg);
552 MBBI->eraseFromParent();
553 }
554}
555
556// We would like to split the SP adjustment to reduce prologue/epilogue
557// as following instructions. In this way, the offset of the callee saved
558// register could fit in a single store.
559// e.g.
560// addi.d $sp, $sp, -2032
561// st.d $ra, $sp, 2024
562// st.d $fp, $sp, 2016
563// addi.d $sp, $sp, -16
565 const MachineFunction &MF) const {
566 const MachineFrameInfo &MFI = MF.getFrameInfo();
567 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
568
569 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
570 // 12-bit and there exists a callee-saved register needing to be pushed.
571 if (!isInt<12>(MFI.getStackSize()) && (CSI.size() > 0)) {
572 // FirstSPAdjustAmount is chosen as (2048 - StackAlign) because 2048 will
573 // cause sp = sp + 2048 in the epilogue to be split into multiple
574 // instructions. Offsets smaller than 2048 can fit in a single load/store
575 // instruction, and we have to stick with the stack alignment.
576 // So (2048 - StackAlign) will satisfy the stack alignment.
577 return 2048 - getStackAlign().value();
578 }
579 return 0;
580}
581
583 BitVector &SavedRegs,
584 RegScavenger *RS) const {
586 // Unconditionally spill RA and FP only if the function uses a frame
587 // pointer.
588 if (hasFP(MF)) {
589 SavedRegs.set(LoongArch::R1);
590 SavedRegs.set(LoongArch::R22);
591 }
592 // Mark BP as used if function has dedicated base pointer.
593 if (hasBP(MF))
594 SavedRegs.set(LoongArchABI::getBPReg());
595}
596
597// Do not preserve stack space within prologue for outgoing variables if the
598// function contains variable size objects.
599// Let eliminateCallFramePseudoInstr preserve stack space for it.
604
605// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
610 Register SPReg = LoongArch::R3;
611 DebugLoc DL = MI->getDebugLoc();
612
613 if (!hasReservedCallFrame(MF)) {
614 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
615 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
616 // pointer. This is necessary when there is a variable length stack
617 // allocation (e.g. alloca), which means it's not possible to allocate
618 // space for outgoing arguments from within the function prologue.
619 int64_t Amount = MI->getOperand(0).getImm();
620
621 if (Amount != 0) {
622 // Ensure the stack remains aligned after adjustment.
623 Amount = alignSPAdjust(Amount);
624
625 if (MI->getOpcode() == LoongArch::ADJCALLSTACKDOWN)
626 Amount = -Amount;
627
629 MF.getSubtarget<LoongArchSubtarget>().getTargetLowering();
630 const int64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
631 if (TLI->hasInlineStackProbe(MF) && -Amount >= ProbeSize) {
632 // When stack probing is enabled, the decrement of SP may need to be
633 // probed. We can handle both the decrement and the probing in
634 // allocateStack.
635 const bool DynAllocation =
636 MF.getInfo<LoongArchMachineFunctionInfo>()->hasDynamicAllocation();
637 allocateStack(MBB, MI, MF, -Amount, -Amount,
638 MF.needsFrameMoves() && !hasFP(MF),
639 /*NeedProbe=*/true, ProbeSize, DynAllocation,
642 } else {
643 adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
644 }
645 }
646 }
647
648 return MBB.erase(MI);
649}
650
654 if (CSI.empty())
655 return true;
656
657 MachineFunction *MF = MBB.getParent();
659
660 // Insert the spill to the stack frame.
661 for (auto &CS : CSI) {
662 MCRegister Reg = CS.getReg();
663 // If the register is RA and the return address is taken by method
664 // LoongArchTargetLowering::lowerRETURNADDR, don't set kill flag.
665 bool IsKill =
666 !(Reg == LoongArch::R1 && MF->getFrameInfo().isReturnAddressTaken());
667 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
668 TII.storeRegToStackSlot(MBB, MI, Reg, IsKill, CS.getFrameIdx(), RC,
669 Register());
670 }
671
672 return true;
673}
674
676 const MachineFunction &MF, int FI, Register &FrameReg) const {
677 const MachineFrameInfo &MFI = MF.getFrameInfo();
679 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
680 uint64_t StackSize = MFI.getStackSize();
681 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
682
683 // Callee-saved registers should be referenced relative to the stack
684 // pointer (positive offset), otherwise use the frame pointer (negative
685 // offset).
686 const auto &CSI = MFI.getCalleeSavedInfo();
687 int MinCSFI = 0;
688 int MaxCSFI = -1;
691 MFI.getOffsetAdjustment());
692
693 if (CSI.size()) {
694 MinCSFI = CSI[0].getFrameIdx();
695 MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
696 }
697
698 if (FI >= MinCSFI && FI <= MaxCSFI) {
699 FrameReg = LoongArch::R3;
700 if (FirstSPAdjustAmount)
701 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
702 else
703 Offset += StackOffset::getFixed(StackSize);
704 } else if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
705 // If the stack was realigned, the frame pointer is set in order to allow
706 // SP to be restored, so we need another base register to record the stack
707 // after realignment.
708 FrameReg = hasBP(MF) ? LoongArchABI::getBPReg() : LoongArch::R3;
709 Offset += StackOffset::getFixed(StackSize);
710 } else {
711 FrameReg = RI->getFrameRegister(MF);
712 if (hasFP(MF))
713 Offset += StackOffset::getFixed(LoongArchFI->getVarArgsSaveSize());
714 else
715 Offset += StackOffset::getFixed(StackSize);
716 }
717
718 return Offset;
719}
720
722 const MachineFunction &MF) const {
723 // Keep the conventional code flow when not optimizing.
724 if (MF.getFunction().hasOptNone())
725 return false;
726
727 return true;
728}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static uint64_t estimateFunctionSizeInBytes(const LoongArchInstrInfo *TII, const MachineFunction &MF)
static void emitStackProbeInline(MachineBasicBlock::iterator MBBI, DebugLoc DL, Register TargetReg)
static bool needScavSlotForCFR(MachineFunction &MF)
unsigned Opc
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
Helper class for creating CFI instructions and inserting them into MIR.
A debug info location.
Definition DebugLoc.h:126
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
uint64_t getFirstSPAdjustAmount(const MachineFunction &MF) const
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const override
Replace a StackProbe stub (if any) with the actual probe code inline.
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
bool hasFPImpl(const MachineFunction &MF) const override
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
bool hasBP(const MachineFunction &MF) const
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
LoongArchMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private Lo...
const LoongArchTargetLowering * getTargetLowering() const override
const LoongArchInstrInfo * getInstrInfo() const override
const LoongArchFrameLowering * getFrameLowering() const override
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:630
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:672
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
bool isMaxCallFrameSizeComputed() const
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Kill
The last use of a register.
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82