LLVM 23.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, or if the frame address is taken.
37 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
38
39 const MachineFrameInfo &MFI = MF.getFrameInfo();
41 RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
43}
44
46 const MachineFrameInfo &MFI = MF.getFrameInfo();
47 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
48
49 return MFI.hasVarSizedObjects() && TRI->hasStackRealignment(MF);
50}
51
52void LoongArchFrameLowering::adjustReg(MachineBasicBlock &MBB,
54 const DebugLoc &DL, Register DestReg,
55 Register SrcReg, int64_t Val,
56 MachineInstr::MIFlag Flag) const {
57 const LoongArchInstrInfo *TII = STI.getInstrInfo();
58 bool IsLA64 = STI.is64Bit();
59 unsigned Addi = IsLA64 ? LoongArch::ADDI_D : LoongArch::ADDI_W;
60
61 if (DestReg == SrcReg && Val == 0)
62 return;
63
64 if (isInt<12>(Val)) {
65 // addi.w/d $DstReg, $SrcReg, Val
66 BuildMI(MBB, MBBI, DL, TII->get(Addi), DestReg)
67 .addReg(SrcReg)
68 .addImm(Val)
69 .setMIFlag(Flag);
70 return;
71 }
72
73 // Try to split the offset across two ADDIs. We need to keep the stack pointer
74 // aligned after each ADDI. We need to determine the maximum value we can put
75 // in each ADDI. In the negative direction, we can use -2048 which is always
76 // sufficiently aligned. In the positive direction, we need to find the
77 // largest 12-bit immediate that is aligned. Exclude -4096 since it can be
78 // created with LU12I.W.
79 assert(getStackAlign().value() < 2048 && "Stack alignment too large");
80 int64_t MaxPosAdjStep = 2048 - getStackAlign().value();
81 if (Val > -4096 && Val <= (2 * MaxPosAdjStep)) {
82 int64_t FirstAdj = Val < 0 ? -2048 : MaxPosAdjStep;
83 Val -= FirstAdj;
84 BuildMI(MBB, MBBI, DL, TII->get(Addi), DestReg)
85 .addReg(SrcReg)
86 .addImm(FirstAdj)
87 .setMIFlag(Flag);
88 BuildMI(MBB, MBBI, DL, TII->get(Addi), DestReg)
89 .addReg(DestReg, RegState::Kill)
90 .addImm(Val)
91 .setMIFlag(Flag);
92 return;
93 }
94
95 unsigned Opc = IsLA64 ? LoongArch::ADD_D : LoongArch::ADD_W;
96 if (Val < 0) {
97 Val = -Val;
98 Opc = IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W;
99 }
100
101 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
102 Register ScratchReg = MRI.createVirtualRegister(&LoongArch::GPRRegClass);
103 TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
104 BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
105 .addReg(SrcReg)
106 .addReg(ScratchReg, RegState::Kill)
107 .setMIFlag(Flag);
108}
109
110// Determine the size of the frame and maximum call frame size.
111void LoongArchFrameLowering::determineFrameLayout(MachineFunction &MF) const {
112 MachineFrameInfo &MFI = MF.getFrameInfo();
113
114 // Get the number of bytes to allocate from the FrameInfo.
115 uint64_t FrameSize = MFI.getStackSize();
116
117 // Make sure the frame is aligned.
118 FrameSize = alignTo(FrameSize, getStackAlign());
119
120 // Update frame info.
121 MFI.setStackSize(FrameSize);
122}
123
125 const MachineFunction &MF) {
126 uint64_t FuncSize = 0;
127 for (auto &MBB : MF)
128 for (auto &MI : MBB)
129 FuncSize += TII->getInstSizeInBytes(MI);
130 return FuncSize;
131}
132
134 if (!MF.getSubtarget<LoongArchSubtarget>().hasBasicF())
135 return false;
136 for (auto &MBB : MF)
137 for (auto &MI : MBB)
138 if (MI.getOpcode() == LoongArch::PseudoST_CFR)
139 return true;
140 return false;
141}
142
144 MachineFunction &MF, RegScavenger *RS) const {
145 const LoongArchRegisterInfo *RI = STI.getRegisterInfo();
146 const TargetRegisterClass &RC = LoongArch::GPRRegClass;
147 const LoongArchInstrInfo *TII = STI.getInstrInfo();
150 MachineFrameInfo &MFI = MF.getFrameInfo();
151
152 unsigned ScavSlotsNum = 0;
153
154 // Far branches beyond 27-bit offset require a spill slot for scratch
155 // register.
156 bool IsLargeFunction = !isInt<27>(estimateFunctionSizeInBytes(TII, MF));
157 if (IsLargeFunction)
158 ScavSlotsNum = 1;
159
160 // estimateStackSize has been observed to under-estimate the final stack
161 // size, so give ourselves wiggle-room by checking for stack size
162 // representable an 11-bit signed field rather than 12-bits.
163 // For [x]vstelm.{b/h/w/d} memory instructions with 8 imm offset, 7-bit
164 // signed field is fine.
165 unsigned EstimateStackSize = MFI.estimateStackSize(MF);
166 if (!isInt<11>(EstimateStackSize) ||
167 (MF.getSubtarget<LoongArchSubtarget>().hasExtLSX() &&
168 !isInt<7>(EstimateStackSize)))
169 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
170
171 // For CFR spill.
172 if (needScavSlotForCFR(MF))
173 ++ScavSlotsNum;
174
175 // Create emergency spill slots.
176 for (unsigned i = 0; i < ScavSlotsNum; ++i) {
177 int FI =
178 MFI.CreateSpillStackObject(RI->getSpillSize(RC), RI->getSpillAlign(RC));
179 RS->addScavengingFrameIndex(FI);
180 if (IsLargeFunction && LAFI->getBranchRelaxationSpillFrameIndex() == -1)
182 LLVM_DEBUG(dbgs() << "Allocated FI(" << FI
183 << ") as the emergency spill slot.\n");
184 }
185}
186
187// Allocate stack space and probe it if necessary.
188void LoongArchFrameLowering::allocateStack(MachineBasicBlock &MBB,
191 uint64_t RealStackSize, bool EmitCFI,
192 bool NeedProbe, uint64_t ProbeSize,
193 bool DynAllocation,
194 MachineInstr::MIFlag Flag) const {
195 DebugLoc DL;
196 const LoongArchInstrInfo *TII = STI.getInstrInfo();
197 const bool IsLA64 = STI.is64Bit();
198 const Register SPReg = LoongArch::R3;
200
201 // Simply allocate the stack if it's not big enough to require a probe.
202 if (!NeedProbe || Offset <= ProbeSize) {
203 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -Offset, Flag);
204 if (EmitCFI)
205 CFIBuilder.buildDefCFAOffset(RealStackSize);
206
207 if (NeedProbe && DynAllocation) {
208 // st.{w/d} $zero, $sp, 0
209 BuildMI(MBB, MBBI, DL,
210 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
211 .addReg(LoongArch::R0)
212 .addReg(SPReg)
213 .addImm(0)
214 .setMIFlag(Flag);
215 }
216
217 return;
218 }
219
220 // Unroll the probe loop depending on the number of iterations.
221 if (Offset < ProbeSize * 5) {
222 const uint64_t CFAAdjust = RealStackSize - Offset;
223
224 uint64_t CurrentOffset = 0;
225 while (CurrentOffset + ProbeSize <= Offset) {
226 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -ProbeSize, Flag);
227 // st.{w/d} $zero, $sp, 0
228 BuildMI(MBB, MBBI, DL,
229 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
230 .addReg(LoongArch::R0)
231 .addReg(SPReg)
232 .addImm(0)
233 .setMIFlag(Flag);
234
235 CurrentOffset += ProbeSize;
236 if (EmitCFI)
237 CFIBuilder.buildDefCFAOffset(CurrentOffset + CFAAdjust);
238 }
239
240 const uint64_t Residual = Offset - CurrentOffset;
241 if (Residual) {
242 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -Residual, Flag);
243 if (EmitCFI)
244 CFIBuilder.buildDefCFAOffset(RealStackSize);
245
246 if (DynAllocation) {
247 // st.{w/d} $zero, $sp, 0
248 BuildMI(MBB, MBBI, DL,
249 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
250 .addReg(LoongArch::R0)
251 .addReg(SPReg)
252 .addImm(0)
253 .setMIFlag(Flag);
254 }
255 }
256 return;
257 }
258
259 // Emit a variable-length allocation probing loop.
260 const uint64_t RoundedSize = alignDown(Offset, ProbeSize);
261 const uint64_t Residual = Offset - RoundedSize;
262 const uint64_t CFAAdjust = RealStackSize - Offset;
263
264 const Register TargetReg = LoongArch::R13;
265 // SUB TargetReg, $sp, RoundedSize
266 adjustReg(MBB, MBBI, DL, TargetReg, SPReg, -RoundedSize, Flag);
267
268 if (EmitCFI) {
269 // Set the CFA register to TargetReg.
270 CFIBuilder.buildDefCFA(TargetReg, RoundedSize + CFAAdjust);
271 }
272
273 // It will be expanded to a probe loop in inlineStackProbe().
274 BuildMI(MBB, MBBI, DL, TII->get(LoongArch::PROBED_STACKALLOC))
275 .addReg(TargetReg);
276
277 if (EmitCFI) {
278 // Set the CFA register back to SP.
279 CFIBuilder.buildDefCFARegister(SPReg);
280 }
281
282 if (Residual) {
283 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -Residual, Flag);
284 if (DynAllocation) {
285 // st.{w/d} $zero, $sp, 0
286 BuildMI(MBB, MBBI, DL,
287 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
288 .addReg(LoongArch::R0)
289 .addReg(SPReg)
290 .addImm(0)
291 .setMIFlag(Flag);
292 }
293 }
294
295 if (EmitCFI)
296 CFIBuilder.buildDefCFAOffset(RealStackSize);
297}
298
300 MachineBasicBlock &MBB) const {
301 MachineFrameInfo &MFI = MF.getFrameInfo();
302 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
303 const LoongArchRegisterInfo *RI = STI.getRegisterInfo();
304 const LoongArchInstrInfo *TII = STI.getInstrInfo();
306 bool IsLA64 = STI.is64Bit();
307
308 Register SPReg = LoongArch::R3;
309 Register FPReg = LoongArch::R22;
310
311 // Debug location must be unknown since the first debug location is used
312 // to determine the end of the prologue.
313 DebugLoc DL;
314 // All calls are tail calls in GHC calling conv, and functions have no
315 // prologue/epilogue.
317 return;
318 // Determine the correct frame layout
319 determineFrameLayout(MF);
320
321 // First, compute final stack size.
322 uint64_t StackSize = MFI.getStackSize();
323 uint64_t RealStackSize = StackSize;
324
325 // Early exit if there is no need to allocate space in the stack.
326 if (StackSize == 0 && !MFI.adjustsStack())
327 return;
328
329 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
330 // Split the SP adjustment to reduce the offsets of callee saved spill.
331 if (FirstSPAdjustAmount)
332 StackSize = FirstSPAdjustAmount;
333
334 // Adjust stack.
335 const LoongArchTargetLowering *TLI = STI.getTargetLowering();
336 const bool NeedProbe = TLI->hasInlineStackProbe(MF);
337 const uint64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
338 const bool DynAllocation =
339 MF.getInfo<LoongArchMachineFunctionInfo>()->hasDynamicAllocation();
340 if (StackSize != 0)
341 allocateStack(MBB, MBBI, MF, StackSize, StackSize,
342 /*EmitCFI=*/true, NeedProbe, ProbeSize, DynAllocation,
344
345 const auto &CSI = MFI.getCalleeSavedInfo();
346
347 // The frame pointer is callee-saved, and code has been generated for us to
348 // save it to the stack. We need to skip over the storing of callee-saved
349 // registers as the frame pointer must be modified after it has been saved
350 // to the stack, not before.
351 std::advance(MBBI, CSI.size());
352
353 // Iterate over list of callee-saved registers and emit .cfi_offset
354 // directives.
355 for (const auto &Entry : CSI) {
356 int64_t Offset = MFI.getObjectOffset(Entry.getFrameIdx());
357 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
358 nullptr, RI->getDwarfRegNum(Entry.getReg(), true), Offset));
359 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
360 .addCFIIndex(CFIIndex)
362 }
363
364 // Generate new FP.
365 if (hasFP(MF)) {
366 adjustReg(MBB, MBBI, DL, FPReg, SPReg,
367 StackSize - LoongArchFI->getVarArgsSaveSize(),
369
370 // Emit ".cfi_def_cfa $fp, LoongArchFI->getVarArgsSaveSize()"
371 unsigned CFIIndex = MF.addFrameInst(
372 MCCFIInstruction::cfiDefCfa(nullptr, RI->getDwarfRegNum(FPReg, true),
373 LoongArchFI->getVarArgsSaveSize()));
374 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
375 .addCFIIndex(CFIIndex)
377 }
378
379 // Emit the second SP adjustment after saving callee saved registers.
380 if (FirstSPAdjustAmount) {
381 uint64_t SecondSPAdjustAmount = RealStackSize - FirstSPAdjustAmount;
382 assert(SecondSPAdjustAmount > 0 &&
383 "SecondSPAdjustAmount should be greater than zero");
384 allocateStack(MBB, MBBI, MF, SecondSPAdjustAmount, RealStackSize,
385 !hasFP(MF), NeedProbe, ProbeSize, DynAllocation,
387 }
388
389 if (hasFP(MF)) {
390 // Realign stack.
391 if (RI->hasStackRealignment(MF)) {
392 unsigned Align = Log2(MFI.getMaxAlign());
393 assert(Align > 0 && "The stack realignment size is invalid!");
394 BuildMI(MBB, MBBI, DL,
395 TII->get(IsLA64 ? LoongArch::BSTRINS_D : LoongArch::BSTRINS_W),
396 SPReg)
397 .addReg(SPReg)
398 .addReg(LoongArch::R0)
399 .addImm(Align - 1)
400 .addImm(0)
402 // FP will be used to restore the frame in the epilogue, so we need
403 // another base register BP to record SP after re-alignment. SP will
404 // track the current stack after allocating variable sized objects.
405 if (hasBP(MF)) {
406 // move BP, $sp
407 BuildMI(MBB, MBBI, DL, TII->get(LoongArch::OR),
409 .addReg(SPReg)
410 .addReg(LoongArch::R0)
412 }
413 }
414 }
415}
416
418 MachineBasicBlock &MBB) const {
419 const LoongArchRegisterInfo *RI = STI.getRegisterInfo();
420 MachineFrameInfo &MFI = MF.getFrameInfo();
421 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
422 Register SPReg = LoongArch::R3;
423 // All calls are tail calls in GHC calling conv, and functions have no
424 // prologue/epilogue.
426 return;
427 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
428 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
429
430 const auto &CSI = MFI.getCalleeSavedInfo();
431 // Skip to before the restores of callee-saved registers.
432 auto LastFrameDestroy = MBBI;
433 if (!CSI.empty())
434 LastFrameDestroy = std::prev(MBBI, CSI.size());
435
436 // Get the number of bytes from FrameInfo.
437 uint64_t StackSize = MFI.getStackSize();
438
439 // Restore the stack pointer.
440 if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects()) {
441 assert(hasFP(MF) && "frame pointer should not have been eliminated");
442 adjustReg(MBB, LastFrameDestroy, DL, SPReg, LoongArch::R22,
443 -StackSize + LoongArchFI->getVarArgsSaveSize(),
445 }
446
447 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
448 if (FirstSPAdjustAmount) {
449 uint64_t SecondSPAdjustAmount = StackSize - FirstSPAdjustAmount;
450 assert(SecondSPAdjustAmount > 0 &&
451 "SecondSPAdjustAmount should be greater than zero");
452
453 adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
455 StackSize = FirstSPAdjustAmount;
456 }
457
458 // Deallocate stack
459 adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
460}
461
462// Synthesize the probe loop.
464 Register TargetReg) {
465 assert(TargetReg != LoongArch::R3 &&
466 "New top of stack cannot already be in $sp");
467
468 MachineBasicBlock &MBB = *MBBI->getParent();
469 MachineFunction &MF = *MBB.getParent();
470
472 const LoongArchInstrInfo *TII = STI.getInstrInfo();
473 const bool IsLA64 = STI.is64Bit();
474 const Align StackAlign = STI.getFrameLowering()->getStackAlign();
476 const uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
477
478 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
479 MachineBasicBlock *LoopTestMBB =
480 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
481 MF.insert(MBBInsertPoint, LoopTestMBB);
482 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
483 MF.insert(MBBInsertPoint, ExitMBB);
484 const Register SPReg = LoongArch::R3;
485 const Register ScratchReg = LoongArch::R14;
487
488 // ScratchReg = ProbeSize
489 TII->movImm(MBB, MBBI, DL, ScratchReg, ProbeSize, Flags);
490
491 // LoopTest:
492 // sub.{w/d} $sp, $sp, ScratchReg
493 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
494 TII->get(IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W), SPReg)
495 .addReg(SPReg)
496 .addReg(ScratchReg)
497 .setMIFlag(Flags);
498
499 // st.{w/d} $zero, $sp, 0
500 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
501 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
502 .addReg(LoongArch::R0)
503 .addReg(SPReg)
504 .addImm(0)
505 .setMIFlag(Flags);
506
507 // bne $sp, TargetReg, LoopTest
508 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(LoongArch::BNE))
509 .addReg(SPReg)
510 .addReg(TargetReg)
511 .addMBB(LoopTestMBB)
512 .setMIFlag(Flags);
513
514 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
516
517 LoopTestMBB->addSuccessor(ExitMBB);
518 LoopTestMBB->addSuccessor(LoopTestMBB);
519 MBB.addSuccessor(LoopTestMBB);
520 // Update liveins.
521 fullyRecomputeLiveIns({ExitMBB, LoopTestMBB});
522}
523
525 MachineBasicBlock &MBB) const {
526 // Get the instructions that need to be replaced. We emit at most two of
527 // these. Remember them in order to avoid complications coming from the need
528 // to traverse the block while potentially creating more blocks.
530 for (MachineInstr &MI : MBB) {
531 if (MI.getOpcode() == LoongArch::PROBED_STACKALLOC) {
532 ToReplace.push_back(&MI);
533 }
534 }
535
536 for (MachineInstr *MI : ToReplace) {
537 MachineBasicBlock::iterator MBBI = MI->getIterator();
538 DebugLoc DL = MBB.findDebugLoc(MBBI);
539 Register TargetReg = MI->getOperand(0).getReg();
540 emitStackProbeInline(MBBI, DL, TargetReg);
541 MBBI->eraseFromParent();
542 }
543}
544
545// We would like to split the SP adjustment to reduce prologue/epilogue
546// as following instructions. In this way, the offset of the callee saved
547// register could fit in a single store.
548// e.g.
549// addi.d $sp, $sp, -2032
550// st.d $ra, $sp, 2024
551// st.d $fp, $sp, 2016
552// addi.d $sp, $sp, -16
554 const MachineFunction &MF) const {
555 const MachineFrameInfo &MFI = MF.getFrameInfo();
556 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
557
558 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
559 // 12-bit and there exists a callee-saved register needing to be pushed.
560 if (!isInt<12>(MFI.getStackSize()) && (CSI.size() > 0)) {
561 // FirstSPAdjustAmount is chosen as (2048 - StackAlign) because 2048 will
562 // cause sp = sp + 2048 in the epilogue to be split into multiple
563 // instructions. Offsets smaller than 2048 can fit in a single load/store
564 // instruction, and we have to stick with the stack alignment.
565 // So (2048 - StackAlign) will satisfy the stack alignment.
566 return 2048 - getStackAlign().value();
567 }
568 return 0;
569}
570
572 BitVector &SavedRegs,
573 RegScavenger *RS) const {
575 // Unconditionally spill RA and FP only if the function uses a frame
576 // pointer.
577 if (hasFP(MF)) {
578 SavedRegs.set(LoongArch::R1);
579 SavedRegs.set(LoongArch::R22);
580 }
581 // Mark BP as used if function has dedicated base pointer.
582 if (hasBP(MF))
583 SavedRegs.set(LoongArchABI::getBPReg());
584}
585
586// Do not preserve stack space within prologue for outgoing variables if the
587// function contains variable size objects.
588// Let eliminateCallFramePseudoInstr preserve stack space for it.
593
594// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
599 Register SPReg = LoongArch::R3;
600 DebugLoc DL = MI->getDebugLoc();
601
602 if (!hasReservedCallFrame(MF)) {
603 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
604 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
605 // pointer. This is necessary when there is a variable length stack
606 // allocation (e.g. alloca), which means it's not possible to allocate
607 // space for outgoing arguments from within the function prologue.
608 int64_t Amount = MI->getOperand(0).getImm();
609
610 if (Amount != 0) {
611 // Ensure the stack remains aligned after adjustment.
612 Amount = alignSPAdjust(Amount);
613
614 if (MI->getOpcode() == LoongArch::ADJCALLSTACKDOWN)
615 Amount = -Amount;
616
617 const LoongArchTargetLowering *TLI =
618 MF.getSubtarget<LoongArchSubtarget>().getTargetLowering();
619 const int64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
620 if (TLI->hasInlineStackProbe(MF) && -Amount >= ProbeSize) {
621 // When stack probing is enabled, the decrement of SP may need to be
622 // probed. We can handle both the decrement and the probing in
623 // allocateStack.
624 const bool DynAllocation =
625 MF.getInfo<LoongArchMachineFunctionInfo>()->hasDynamicAllocation();
626 allocateStack(MBB, MI, MF, -Amount, -Amount,
627 MF.needsFrameMoves() && !hasFP(MF),
628 /*NeedProbe=*/true, ProbeSize, DynAllocation,
631 } else {
632 adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
633 }
634 }
635 }
636
637 return MBB.erase(MI);
638}
639
643 if (CSI.empty())
644 return true;
645
646 MachineFunction *MF = MBB.getParent();
648
649 // Insert the spill to the stack frame.
650 for (auto &CS : CSI) {
651 MCRegister Reg = CS.getReg();
652 // If the register is RA and the return address is taken by method
653 // LoongArchTargetLowering::lowerRETURNADDR, don't set kill flag.
654 bool IsKill =
655 !(Reg == LoongArch::R1 && MF->getFrameInfo().isReturnAddressTaken());
656 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
657 TII.storeRegToStackSlot(MBB, MI, Reg, IsKill, CS.getFrameIdx(), RC,
658 Register());
659 }
660
661 return true;
662}
663
665 const MachineFunction &MF, int FI, Register &FrameReg) const {
666 const MachineFrameInfo &MFI = MF.getFrameInfo();
668 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
669 uint64_t StackSize = MFI.getStackSize();
670 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
671
672 // Callee-saved registers should be referenced relative to the stack
673 // pointer (positive offset), otherwise use the frame pointer (negative
674 // offset).
675 const auto &CSI = MFI.getCalleeSavedInfo();
676 int MinCSFI = 0;
677 int MaxCSFI = -1;
680 MFI.getOffsetAdjustment());
681
682 if (CSI.size()) {
683 MinCSFI = CSI[0].getFrameIdx();
684 MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
685 }
686
687 if (FI >= MinCSFI && FI <= MaxCSFI) {
688 FrameReg = LoongArch::R3;
689 if (FirstSPAdjustAmount)
690 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
691 else
692 Offset += StackOffset::getFixed(StackSize);
693 } else if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
694 // If the stack was realigned, the frame pointer is set in order to allow
695 // SP to be restored, so we need another base register to record the stack
696 // after realignment.
697 FrameReg = hasBP(MF) ? LoongArchABI::getBPReg() : LoongArch::R3;
698 Offset += StackOffset::getFixed(StackSize);
699 } else {
700 FrameReg = RI->getFrameRegister(MF);
701 if (hasFP(MF))
702 Offset += StackOffset::getFixed(LoongArchFI->getVarArgsSaveSize());
703 else
704 Offset += StackOffset::getFixed(StackSize);
705 }
706
707 return Offset;
708}
709
711 const MachineFunction &MF) const {
712 // Keep the conventional code flow when not optimizing.
713 if (MF.getFunction().hasOptNone())
714 return false;
715
716 return true;
717}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
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:366
Helper class for creating CFI instructions and inserting them into MIR.
A debug info location.
Definition DebugLoc.h:124
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:708
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
bool hasInlineStackProbe(const MachineFunction &MF) const override
True if stack clash protection is enabled for this function.
unsigned getStackProbeSize(const MachineFunction &MF, Align StackAlign) const
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:615
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:657
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
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 the alignment in bytes that this function must be aligned to, which is greater than the defaul...
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
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
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & 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:30
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
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.
TargetOptions Options
LLVM_ABI bool DisableFramePointerElim(const MachineFunction &MF) const
DisableFramePointerElim - This returns true if frame pointer elimination optimization should be disab...
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:558
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:165
@ 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:144
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
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:77