blob: 6ee2e8bef612dfb8eb117fcc8949f3ba5783e733 [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//
9//===----------------------------------------------------------------------===//
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000010
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000011#define DEBUG_TYPE "hexagon-pei"
12
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +000013#include "HexagonBlockRanges.h"
Craig Topperb25fda92012-03-17 18:46:09 +000014#include "HexagonFrameLowering.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000017#include "HexagonRegisterInfo.h"
18#include "HexagonSubtarget.h"
19#include "HexagonTargetMachine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000020#include "llvm/ADT/BitVector.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000021#include "llvm/ADT/PostOrderIterator.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000022#include "llvm/CodeGen/MachineDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000023#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000028#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/Type.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000036#include "llvm/Target/TargetInstrInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000039
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000040// Hexagon stack frame layout as defined by the ABI:
41//
42// Incoming arguments
43// passed via stack
44// |
45// |
46// SP during function's FP during function's |
47// +-- runtime (top of stack) runtime (bottom) --+ |
48// | | |
49// --++---------------------+------------------+-----------------++-+-------
50// | parameter area for | variable-size | fixed-size |LR| arg
51// | called functions | local objects | local objects |FP|
52// --+----------------------+------------------+-----------------+--+-------
53// <- size known -> <- size unknown -> <- size known ->
54//
55// Low address High address
56//
57// <--- stack growth
58//
59//
60// - In any circumstances, the outgoing function arguments are always accessi-
61// ble using the SP, and the incoming arguments are accessible using the FP.
62// - If the local objects are not aligned, they can always be accessed using
63// the FP.
64// - If there are no variable-sized objects, the local objects can always be
65// accessed using the SP, regardless whether they are aligned or not. (The
66// alignment padding will be at the bottom of the stack (highest address),
67// and so the offset with respect to the SP will be known at the compile-
68// -time.)
69//
70// The only complication occurs if there are both, local aligned objects, and
71// dynamically allocated (variable-sized) objects. The alignment pad will be
72// placed between the FP and the local objects, thus preventing the use of the
73// FP to access the local objects. At the same time, the variable-sized objects
74// will be between the SP and the local objects, thus introducing an unknown
75// distance from the SP to the locals.
76//
77// To avoid this problem, a new register is created that holds the aligned
78// address of the bottom of the stack, referred in the sources as AP (aligned
79// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
80// that aligns AP to the required boundary (a maximum of the alignments of
81// all stack objects, fixed- and variable-sized). All local objects[1] will
82// then use AP as the base pointer.
83// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
84// their name from being allocated at fixed locations on the stack, relative
85// to the FP. In the presence of dynamic allocation and local alignment, such
86// objects can only be accessed through the FP.
87//
88// Illustration of the AP:
89// FP --+
90// |
91// ---------------+---------------------+-----+-----------------------++-+--
92// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
93// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
94// ---------------+---------------------+-----+-----------------+-----+--+--
95// |<-- Multiple of the -->|
96// stack alignment +-- AP
97//
98// The AP is set up at the beginning of the function. Since it is not a dedi-
99// cated (reserved) register, it needs to be kept live throughout the function
100// to be available as the base register for local object accesses.
101// Normally, an address of a stack objects is obtained by a pseudo-instruction
102// TFR_FI. To access local objects with the AP register present, a different
103// pseudo-instruction needs to be used: TFR_FIA. The TFR_FIA takes one extra
104// argument compared to TFR_FI: the first input register is the AP register.
105// This keeps the register live between its definition and its uses.
106
107// The AP register is originally set up using pseudo-instruction ALIGNA:
108// AP = ALIGNA A
109// where
110// A - required stack alignment
111// The alignment value must be the maximum of all alignments required by
112// any stack object.
113
114// The dynamic allocation uses a pseudo-instruction ALLOCA:
115// Rd = ALLOCA Rs, A
116// where
117// Rd - address of the allocated space
118// Rs - minimum size (the actual allocated can be larger to accommodate
119// alignment)
120// A - required alignment
121
122
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000123using namespace llvm;
124
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000125static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
126 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000127
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000128static cl::opt<int> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000129 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
130 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000131
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000132static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000133 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
134 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000135
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000136static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000137 cl::Hidden, cl::desc("Specify Os spill func threshold"),
138 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000139
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000140static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
141 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
142 cl::init(false), cl::ZeroOrMore);
143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000144static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
145 cl::init(true), cl::Hidden, cl::ZeroOrMore,
146 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000148static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
149 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
150 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000151
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000152static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
153 cl::Hidden, cl::desc("Use allocframe more conservatively"));
154
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000155static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
156 cl::init(true), cl::desc("Optimize spill slots"));
157
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000158
159namespace llvm {
160 void initializeHexagonCallFrameInformationPass(PassRegistry&);
161 FunctionPass *createHexagonCallFrameInformation();
162}
163
164namespace {
165 class HexagonCallFrameInformation : public MachineFunctionPass {
166 public:
167 static char ID;
168 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
169 PassRegistry &PR = *PassRegistry::getPassRegistry();
170 initializeHexagonCallFrameInformationPass(PR);
171 }
172 bool runOnMachineFunction(MachineFunction &MF) override;
173 };
174
175 char HexagonCallFrameInformation::ID = 0;
176}
177
178bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
179 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
180 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
181 MF.getFunction()->needsUnwindTableEntry();
182
183 if (!NeedCFI)
184 return false;
185 HFI.insertCFIInstructions(MF);
186 return true;
187}
188
189INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
190 "Hexagon call frame information", false, false)
191
192FunctionPass *llvm::createHexagonCallFrameInformation() {
193 return new HexagonCallFrameInformation();
194}
195
196
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000197namespace {
198 /// Map a register pair Reg to the subregister that has the greater "number",
199 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
200 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
201 bool hireg = true) {
202 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
203 return Reg;
204
205 unsigned RegNo = 0;
206 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
207 if (hireg) {
208 if (*SubRegs > RegNo)
209 RegNo = *SubRegs;
210 } else {
211 if (!RegNo || *SubRegs < RegNo)
212 RegNo = *SubRegs;
213 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000214 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000215 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000216 }
217
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000218 /// Returns the callee saved register with the largest id in the vector.
219 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
220 const TargetRegisterInfo &TRI) {
221 assert(Hexagon::R1 > 0 &&
222 "Assume physical registers are encoded as positive integers");
223 if (CSI.empty())
224 return 0;
225
226 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
227 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
228 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
229 if (Reg > Max)
230 Max = Reg;
231 }
232 return Max;
233 }
234
235 /// Checks if the basic block contains any instruction that needs a stack
236 /// frame to be already in place.
237 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR) {
238 for (auto &I : MBB) {
239 const MachineInstr *MI = &I;
240 if (MI->isCall())
241 return true;
242 unsigned Opc = MI->getOpcode();
243 switch (Opc) {
244 case Hexagon::ALLOCA:
245 case Hexagon::ALIGNA:
246 return true;
247 default:
248 break;
249 }
250 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000251 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000252 // While the presence of a frame index does not prove that a stack
253 // frame will be required, all frame indexes should be within alloc-
254 // frame/deallocframe. Otherwise, the code that translates a frame
255 // index into an offset would have to be aware of the placement of
256 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000257 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000258 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000259 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000260 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000261 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000262 // Virtual registers will need scavenging, which then may require
263 // a stack slot.
264 if (TargetRegisterInfo::isVirtualRegister(R))
265 return true;
266 if (CSR[R])
267 return true;
268 }
269 }
270 return false;
271 }
272
273 /// Returns true if MBB has a machine instructions that indicates a tail call
274 /// in the block.
275 bool hasTailCall(const MachineBasicBlock &MBB) {
276 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
277 unsigned RetOpc = I->getOpcode();
278 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
279 }
280
281 /// Returns true if MBB contains an instruction that returns.
282 bool hasReturn(const MachineBasicBlock &MBB) {
283 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
284 if (I->isReturn())
285 return true;
286 return false;
287 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000288}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000289
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000290
291/// Implements shrink-wrapping of the stack frame. By default, stack frame
292/// is created in the function entry block, and is cleaned up in every block
293/// that returns. This function finds alternate blocks: one for the frame
294/// setup (prolog) and one for the cleanup (epilog).
295void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
296 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
297 static unsigned ShrinkCounter = 0;
298
299 if (ShrinkLimit.getPosition()) {
300 if (ShrinkCounter >= ShrinkLimit)
301 return;
302 ShrinkCounter++;
303 }
304
305 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
306 auto &HRI = *HST.getRegisterInfo();
307
308 MachineDominatorTree MDT;
309 MDT.runOnMachineFunction(MF);
310 MachinePostDominatorTree MPT;
311 MPT.runOnMachineFunction(MF);
312
313 typedef DenseMap<unsigned,unsigned> UnsignedMap;
314 UnsignedMap RPO;
315 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
316 RPOTType RPOT(&MF);
317 unsigned RPON = 0;
318 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
319 RPO[(*I)->getNumber()] = RPON++;
320
321 // Don't process functions that have loops, at least for now. Placement
322 // of prolog and epilog must take loop structure into account. For simpli-
323 // city don't do it right now.
324 for (auto &I : MF) {
325 unsigned BN = RPO[I.getNumber()];
326 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
327 // If found a back-edge, return.
328 if (RPO[(*SI)->getNumber()] <= BN)
329 return;
330 }
331 }
332
333 // Collect the set of blocks that need a stack frame to execute. Scan
334 // each block for uses/defs of callee-saved registers, calls, etc.
335 SmallVector<MachineBasicBlock*,16> SFBlocks;
336 BitVector CSR(Hexagon::NUM_TARGET_REGS);
337 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
338 CSR[*P] = true;
339
340 for (auto &I : MF)
341 if (needsStackFrame(I, CSR))
342 SFBlocks.push_back(&I);
343
344 DEBUG({
345 dbgs() << "Blocks needing SF: {";
346 for (auto &B : SFBlocks)
347 dbgs() << " BB#" << B->getNumber();
348 dbgs() << " }\n";
349 });
350 // No frame needed?
351 if (SFBlocks.empty())
352 return;
353
354 // Pick a common dominator and a common post-dominator.
355 MachineBasicBlock *DomB = SFBlocks[0];
356 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
357 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
358 if (!DomB)
359 break;
360 }
361 MachineBasicBlock *PDomB = SFBlocks[0];
362 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
363 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
364 if (!PDomB)
365 break;
366 }
367 DEBUG({
368 dbgs() << "Computed dom block: BB#";
369 if (DomB) dbgs() << DomB->getNumber();
370 else dbgs() << "<null>";
371 dbgs() << ", computed pdom block: BB#";
372 if (PDomB) dbgs() << PDomB->getNumber();
373 else dbgs() << "<null>";
374 dbgs() << "\n";
375 });
376 if (!DomB || !PDomB)
377 return;
378
379 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
380 if (!MDT.dominates(DomB, PDomB)) {
381 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
382 return;
383 }
384 if (!MPT.dominates(PDomB, DomB)) {
385 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
386 return;
387 }
388
389 // Finally, everything seems right.
390 PrologB = DomB;
391 EpilogB = PDomB;
392}
393
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000394
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000395/// Perform most of the PEI work here:
396/// - saving/restoring of the callee-saved registers,
397/// - stack frame creation and destruction.
398/// Normally, this work is distributed among various functions, but doing it
399/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000400void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
401 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000402 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
403 auto &HRI = *HST.getRegisterInfo();
404
405 MachineFrameInfo *MFI = MF.getFrameInfo();
406 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
407
408 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
409 if (EnableShrinkWrapping)
410 findShrunkPrologEpilog(MF, PrologB, EpilogB);
411
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000412 bool PrologueStubs = false;
413 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
414 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000415
416 if (EpilogB) {
417 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
418 insertEpilogueInBlock(*EpilogB);
419 } else {
420 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000421 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000422 insertCSRRestoresInBlock(B, CSI, HRI);
423
424 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000425 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000426 insertEpilogueInBlock(B);
427 }
428}
429
430
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000431void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
432 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000433 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000434 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000435 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000436 auto &HII = *HST.getInstrInfo();
437 auto &HRI = *HST.getRegisterInfo();
438 DebugLoc dl;
439
440 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
441
442 // Calculate the total stack frame size.
443 // Get the number of bytes to allocate from the FrameInfo.
444 unsigned FrameSize = MFI->getStackSize();
445 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000446 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000447 MFI->setMaxCallFrameSize(MaxCFA);
448
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000449 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000450 MFI->setStackSize(FrameSize);
451
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000452 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000453
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000454 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000455 unsigned NumBytes = MFI->getStackSize();
456 unsigned SP = HRI.getStackRegister();
457 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000458 MachineBasicBlock::iterator InsertPt = MBB.begin();
459
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000460 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
461 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000462
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000463 for (auto MI : AdjustRegs) {
464 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
465 expandAlloca(MI, HII, SP, MaxCF);
466 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000467 }
468
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000469 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000470 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000471
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000472 // Check for overflow.
473 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
474 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000475
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000476 // Create a dummy memory operand to avoid allocframe from being treated as
477 // a volatile memory reference.
478 MachineMemOperand *MMO =
479 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
480 4, 4);
481
482 if (NumBytes >= ALLOCFRAME_MAX) {
483 // Emit allocframe(#0).
484 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
485 .addImm(0)
486 .addMemOperand(MMO);
487
488 // Subtract offset from frame pointer.
489 // We use a caller-saved non-parameter register for that.
490 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
491 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
492 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000493 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
494 .addReg(SP)
495 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000496 } else {
497 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
498 .addImm(NumBytes)
499 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000500 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000501
502 if (AlignStack) {
503 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
504 .addReg(SP)
505 .addImm(-int64_t(MaxAlign));
506 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000507
508 // If the stack-checking is enabled, and we spilled the callee-saved
509 // registers inline (i.e. did not use a spill function), then call
510 // the stack checker directly.
511 if (EnableStackOVFSanitizer && !PrologueStubs)
512 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
513 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000514}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000515
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000516void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
517 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000518 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000519 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000520
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000521 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
522 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000523 auto &HRI = *HST.getRegisterInfo();
524 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000525
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000526 MachineInstr *RetI = nullptr;
527 for (auto &I : MBB) {
528 if (!I.isReturn())
529 continue;
530 RetI = &I;
531 break;
532 }
533 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
534
535 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
536 DebugLoc DL;
537 if (InsertPt != MBB.end())
538 DL = InsertPt->getDebugLoc();
539 else if (!MBB.empty())
540 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000541
542 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000543 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000544 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
545 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
546 .addReg(SP)
547 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000548 return;
549 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000550
551 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
552 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000553 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
554 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000555 MachineBasicBlock::iterator It = RetI;
556 ++It;
557 // Delete all instructions after the RESTORE (except labels).
558 while (It != MBB.end()) {
559 if (!It->isLabel())
560 It = MBB.erase(It);
561 else
562 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000563 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000564 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000565 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000566
567 // It is possible that the restoring code is a call to a library function.
568 // All of the restore* functions include "deallocframe", so we need to make
569 // sure that we don't add an extra one.
570 bool NeedsDeallocframe = true;
571 if (!MBB.empty() && InsertPt != MBB.begin()) {
572 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
573 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000574 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
575 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000576 NeedsDeallocframe = false;
577 }
578
579 if (!NeedsDeallocframe)
580 return;
581 // If the returning instruction is JMPret, replace it with dealloc_return,
582 // otherwise just add deallocframe. The function could be returning via a
583 // tail call.
584 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
585 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
586 return;
587 }
588 unsigned NewOpc = Hexagon::L4_return;
589 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
590 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000591 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000592 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000593}
594
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000595
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000596namespace {
597 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
598 if (!It->isBundle())
599 return It->getOpcode() == Hexagon::S2_allocframe;
600 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000601 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000602 while (++I != End && I->isBundled())
603 if (I->getOpcode() == Hexagon::S2_allocframe)
604 return true;
605 return false;
606 }
607
608 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
609 for (auto &I : B)
610 if (IsAllocFrame(I))
611 return I;
612 return B.end();
613 }
614}
615
616
617void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
618 for (auto &B : MF) {
619 auto AF = FindAllocFrame(B);
620 if (AF == B.end())
621 continue;
622 insertCFIInstructionsAt(B, ++AF);
623 }
624}
625
626
627void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
628 MachineBasicBlock::iterator At) const {
629 MachineFunction &MF = *MBB.getParent();
630 MachineFrameInfo *MFI = MF.getFrameInfo();
631 MachineModuleInfo &MMI = MF.getMMI();
632 auto &HST = MF.getSubtarget<HexagonSubtarget>();
633 auto &HII = *HST.getInstrInfo();
634 auto &HRI = *HST.getRegisterInfo();
635
636 // If CFI instructions have debug information attached, something goes
637 // wrong with the final assembly generation: the prolog_end is placed
638 // in a wrong location.
639 DebugLoc DL;
640 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
641
642 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
643
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000644 if (hasFP(MF)) {
645 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
646 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000647
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000648 // Define CFA via an offset from the value of FP.
649 //
650 // -8 -4 0 (SP)
651 // --+----+----+---------------------
652 // | FP | LR | increasing addresses -->
653 // --+----+----+---------------------
654 // | +-- Old SP (before allocframe)
655 // +-- New FP (after allocframe)
656 //
657 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
658 // MCCFIInstruction::createOffset takes the offset without sign change.
659 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
660 BuildMI(MBB, At, DL, CFID)
661 .addCFIIndex(MMI.addFrameInst(DefCfa));
662 // R31 (return addr) = CFA - 4
663 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
664 BuildMI(MBB, At, DL, CFID)
665 .addCFIIndex(MMI.addFrameInst(OffR31));
666 // R30 (frame ptr) = CFA - 8
667 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
668 BuildMI(MBB, At, DL, CFID)
669 .addCFIIndex(MMI.addFrameInst(OffR30));
670 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000671
672 static unsigned int RegsToMove[] = {
673 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
674 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
675 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
676 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
677 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
678 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
679 Hexagon::NoRegister
680 };
681
682 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
683
684 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
685 unsigned Reg = RegsToMove[i];
686 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
687 return C.getReg() == Reg;
688 };
689 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
690 if (F == CSI.end())
691 continue;
692
693 // Subtract 8 to make room for R30 and R31, which are added above.
694 unsigned FrameReg;
695 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
696
697 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
698 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
699 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
700 Offset);
701 BuildMI(MBB, At, DL, CFID)
702 .addCFIIndex(MMI.addFrameInst(OffReg));
703 } else {
704 // Split the double regs into subregs, and generate appropriate
705 // cfi_offsets.
706 // The only reason, we are split double regs is, llvm-mc does not
707 // understand paired registers for cfi_offset.
708 // Eg .cfi_offset r1:0, -64
709
710 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
711 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
712 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
713 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
714 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
715 Offset+4);
716 BuildMI(MBB, At, DL, CFID)
717 .addCFIIndex(MMI.addFrameInst(OffHi));
718 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
719 Offset);
720 BuildMI(MBB, At, DL, CFID)
721 .addCFIIndex(MMI.addFrameInst(OffLo));
722 }
723 }
724}
725
726
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000727bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000728 auto &MFI = *MF.getFrameInfo();
729 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
730
731 bool HasFixed = MFI.getNumFixedObjects();
732 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
733 .getLocalFrameObjectCount();
734 bool HasExtraAlign = HRI.needsStackRealignment(MF);
735 bool HasAlloca = MFI.hasVarSizedObjects();
736
737 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
738 // that this shouldn't be required, but doing so now because gcc does and
739 // gdb can't break at the start of the function without it. Will remove if
740 // this turns out to be a gdb bug.
741 //
742 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
743 return true;
744
745 // By default we want to use SP (since it's always there). FP requires
746 // some setup (i.e. ALLOCFRAME).
747 // Fixed and preallocated objects need FP if the distance from them to
748 // the SP is unknown (as is with alloca or aligna).
749 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
750 return true;
751
752 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000753 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000754 return true;
755 }
756
757 if (MFI.hasCalls() ||
758 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
759 return true;
760
761 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000762}
763
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000764
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000765enum SpillKind {
766 SK_ToMem,
767 SK_FromMem,
768 SK_FromMemTailcall
769};
770
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000771static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
772 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000773 const char * V4SpillToMemoryFunctions[] = {
774 "__save_r16_through_r17",
775 "__save_r16_through_r19",
776 "__save_r16_through_r21",
777 "__save_r16_through_r23",
778 "__save_r16_through_r25",
779 "__save_r16_through_r27" };
780
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000781 const char * V4SpillToMemoryStkchkFunctions[] = {
782 "__save_r16_through_r17_stkchk",
783 "__save_r16_through_r19_stkchk",
784 "__save_r16_through_r21_stkchk",
785 "__save_r16_through_r23_stkchk",
786 "__save_r16_through_r25_stkchk",
787 "__save_r16_through_r27_stkchk" };
788
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000789 const char * V4SpillFromMemoryFunctions[] = {
790 "__restore_r16_through_r17_and_deallocframe",
791 "__restore_r16_through_r19_and_deallocframe",
792 "__restore_r16_through_r21_and_deallocframe",
793 "__restore_r16_through_r23_and_deallocframe",
794 "__restore_r16_through_r25_and_deallocframe",
795 "__restore_r16_through_r27_and_deallocframe" };
796
797 const char * V4SpillFromMemoryTailcallFunctions[] = {
798 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
799 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
800 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
801 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
802 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
803 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
804 };
805
806 const char **SpillFunc = nullptr;
807
808 switch(SpillType) {
809 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000810 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
811 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000812 break;
813 case SK_FromMem:
814 SpillFunc = V4SpillFromMemoryFunctions;
815 break;
816 case SK_FromMemTailcall:
817 SpillFunc = V4SpillFromMemoryTailcallFunctions;
818 break;
819 }
820 assert(SpillFunc && "Unknown spill kind");
821
822 // Spill all callee-saved registers up to the highest register used.
823 switch (MaxReg) {
824 case Hexagon::R17:
825 return SpillFunc[0];
826 case Hexagon::R19:
827 return SpillFunc[1];
828 case Hexagon::R21:
829 return SpillFunc[2];
830 case Hexagon::R23:
831 return SpillFunc[3];
832 case Hexagon::R25:
833 return SpillFunc[4];
834 case Hexagon::R27:
835 return SpillFunc[5];
836 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000837 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000838 }
839 return 0;
840}
841
842/// Adds all callee-saved registers up to MaxReg to the instruction.
843static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
844 unsigned MaxReg, bool IsDef) {
845 // Add the callee-saved registers as implicit uses.
846 for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
847 MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
848 Inst->addOperand(ImpUse);
849 }
850}
851
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000852
James Y Knight5567baf2015-08-15 02:32:35 +0000853int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000854 int FI, unsigned &FrameReg) const {
855 auto &MFI = *MF.getFrameInfo();
856 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000857
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000858 int Offset = MFI.getObjectOffset(FI);
859 bool HasAlloca = MFI.hasVarSizedObjects();
860 bool HasExtraAlign = HRI.needsStackRealignment(MF);
861 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000862
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000863 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
864 unsigned AP = 0;
865 if (const MachineInstr *AI = getAlignaInstr(MF))
866 AP = AI->getOperand(0).getReg();
867 unsigned FrameSize = MFI.getStackSize();
868
869 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
870 // Use FP at -O0, except when there are objects with extra alignment.
871 // That additional alignment requirement may cause a pad to be inserted,
872 // which will make it impossible to use FP to access objects located
873 // past the pad.
874 if (NoOpt && !HasExtraAlign)
875 UseFP = true;
876 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
877 // Fixed and preallocated objects will be located before any padding
878 // so FP must be used to access them.
879 UseFP |= (HasAlloca || HasExtraAlign);
880 } else {
881 if (HasAlloca) {
882 if (HasExtraAlign)
883 UseAP = true;
884 else
885 UseFP = true;
886 }
887 }
888
889 // If FP was picked, then there had better be FP.
890 bool HasFP = hasFP(MF);
891 assert((HasFP || !UseFP) && "This function must have frame pointer");
892
893 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
894 // FP/LR. If the base register is used to access an object across these
895 // 8 bytes, then the offset will need to be adjusted by 8.
896 //
897 // After allocframe:
898 // HexagonISelLowering adds 8 to ---+
899 // the offsets of all stack-based |
900 // arguments (*) |
901 // |
902 // getObjectOffset < 0 0 8 getObjectOffset >= 8
903 // ------------------------+-----+------------------------> increasing
904 // <local objects> |FP/LR| <input arguments> addresses
905 // -----------------+------+-----+------------------------>
906 // | |
907 // SP/AP point --+ +-- FP points here (**)
908 // somewhere on
909 // this side of FP/LR
910 //
911 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
912 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
913
914 // The lowering assumes that FP/LR is present, and so the offsets of
915 // the formal arguments start at 8. If FP/LR is not there we need to
916 // reduce the offset by 8.
917 if (Offset > 0 && !HasFP)
918 Offset -= 8;
919
920 if (UseFP)
921 FrameReg = FP;
922 else if (UseAP)
923 FrameReg = AP;
924 else
925 FrameReg = SP;
926
927 // Calculate the actual offset in the instruction. If there is no FP
928 // (in other words, no allocframe), then SP will not be adjusted (i.e.
929 // there will be no SP -= FrameSize), so the frame size should not be
930 // added to the calculated offset.
931 int RealOffset = Offset;
932 if (!UseFP && !UseAP && HasFP)
933 RealOffset = FrameSize+Offset;
934 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000935}
936
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000937
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000938bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000939 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
940 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000941 if (CSI.empty())
942 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000943
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000944 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000945 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000946 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000947 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000948
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000949 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000950 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000951 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000952 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
953 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
954 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000955 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
956 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
957
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000958 // Call spill function.
959 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000960 unsigned SpillOpc;
961 if (StkOvrFlowEnabled)
962 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
963 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
964 else
965 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
966 : Hexagon::SAVE_REGISTERS_CALL_V4;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000967
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000968 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000969 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000970 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000971 // Add callee-saved registers as use.
972 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
973 // Add live in registers.
974 for (unsigned I = 0; I < CSI.size(); ++I)
975 MBB.addLiveIn(CSI[I].getReg());
976 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000977 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000978
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000979 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000980 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000981 // Add live in registers. We treat eh_return callee saved register r0 - r3
982 // specially. They are not really callee saved registers as they are not
983 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000984 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
985 int FI = CSI[i].getFrameIdx();
986 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000987 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000988 if (IsKill)
989 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000990 }
991 return true;
992}
993
994
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000995bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
996 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
997 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000998 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000999
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001000 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1001 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001002 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001003
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001004 if (useRestoreFunction(MF, CSI)) {
1005 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1006 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1007 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1008 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001009 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1010 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001011
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001012 // Call spill function.
1013 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1014 : MBB.getLastNonDebugInstr()->getDebugLoc();
1015 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001016
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001017 if (HasTC) {
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001018 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1019 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001020 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001021 .addExternalSymbol(RestoreFn);
1022 } else {
1023 // The block has a return.
1024 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1025 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001026 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1027 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001028 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001029 .addExternalSymbol(RestoreFn);
1030 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001031 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001032 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001033 addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
1034 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001035 }
1036
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001037 for (unsigned i = 0; i < CSI.size(); ++i) {
1038 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001039 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1040 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001041 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001042 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001043
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001044 return true;
1045}
1046
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001047
1048void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1049 MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001050 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001051 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001052 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001053 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1054 "Cannot handle this call frame pseudo instruction");
Eli Bendersky8da87162013-02-21 20:05:00 +00001055 MBB.erase(I);
1056}
1057
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001058
1059void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1060 MachineFunction &MF, RegScavenger *RS) const {
1061 // If this function has uses aligned stack and also has variable sized stack
1062 // objects, then we need to map all spill slots to fixed positions, so that
1063 // they can be accessed through FP. Otherwise they would have to be accessed
1064 // via AP, which may not be available at the particular place in the program.
1065 MachineFrameInfo *MFI = MF.getFrameInfo();
1066 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001067 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001068
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001069 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001070 return;
1071
1072 unsigned LFS = MFI->getLocalFrameSize();
1073 int Offset = -LFS;
1074 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1075 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1076 continue;
1077 int S = MFI->getObjectSize(i);
1078 LFS += S;
1079 Offset -= S;
1080 MFI->mapLocalFrameObject(i, Offset);
1081 }
1082
1083 MFI->setLocalFrameSize(LFS);
1084 unsigned A = MFI->getLocalFrameMaxAlign();
1085 assert(A <= 8 && "Unexpected local frame alignment");
1086 if (A == 0)
1087 MFI->setLocalFrameMaxAlign(8);
1088 MFI->setUseLocalStackAllocationBlock(true);
1089}
1090
1091/// Returns true if there is no caller saved registers available.
1092static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1093 const HexagonRegisterInfo &HRI) {
1094 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001095 BitVector Reserved = HRI.getReservedRegs(MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001096
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001097 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1098 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1099 if (MRI.isPhysRegUsed(*AI))
1100 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001101 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001102 };
1103
1104 // Check for an unused caller-saved register.
1105 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF); *P; ++P)
1106 if (!IsUsed(*P))
1107 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001108 // All caller-saved registers are used.
1109 return true;
1110}
1111
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001112
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001113#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001114static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001115 dbgs() << '{';
1116 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1117 unsigned R = x;
1118 dbgs() << ' ' << PrintReg(R, &TRI);
1119 }
1120 dbgs() << " }";
1121}
1122#endif
1123
1124
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001125bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1126 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001127 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001128 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001129 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001130 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001131
1132 // Generate a set of unique, callee-saved registers (SRegs), where each
1133 // register in the set is maximal in terms of sub-/super-register relation,
1134 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1135
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001136 // (1) For each callee-saved register, add that register and all of its
1137 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001138 DEBUG(dbgs() << "Initial CS registers: {");
1139 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1140 unsigned R = CSI[i].getReg();
1141 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1142 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1143 SRegs[*SR] = true;
1144 }
1145 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001146 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001147
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001148 // (2) For each reserved register, remove that register and all of its
1149 // sub- and super-registers from SRegs.
1150 BitVector Reserved = TRI->getReservedRegs(MF);
1151 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1152 unsigned R = x;
1153 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1154 SRegs[*SR] = false;
1155 }
1156 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1157 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1158
1159 // (3) Collect all registers that have at least one sub-register in SRegs,
1160 // and also have no sub-registers that are reserved. These will be the can-
1161 // didates for saving as a whole instead of their individual sub-registers.
1162 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1163 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001164 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1165 unsigned R = x;
1166 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1167 TmpSup[*SR] = true;
1168 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001169 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1170 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001171 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1172 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001173 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001174 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001175 break;
1176 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001177 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001178 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001179
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001180 // (4) Include all super-registers found in (3) into SRegs.
1181 SRegs |= TmpSup;
1182 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001183
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001184 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001185 // remove R from SRegs.
1186 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1187 unsigned R = x;
1188 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1189 if (!SRegs[*SR])
1190 continue;
1191 SRegs[R] = false;
1192 break;
1193 }
1194 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001195 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001196
1197 // Now, for each register that has a fixed stack slot, create the stack
1198 // object for it.
1199 CSI.clear();
1200
1201 typedef TargetFrameLowering::SpillSlot SpillSlot;
1202 unsigned NumFixed;
1203 int MinOffset = 0; // CS offsets are negative.
1204 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1205 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1206 if (!SRegs[S->Reg])
1207 continue;
1208 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1209 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1210 MinOffset = std::min(MinOffset, S->Offset);
1211 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1212 SRegs[S->Reg] = false;
1213 }
1214
1215 // There can be some registers that don't have fixed slots. For example,
1216 // we need to store R0-R3 in functions with exception handling. For each
1217 // such register, create a non-fixed stack object.
1218 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1219 unsigned R = x;
1220 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1221 int Off = MinOffset - RC->getSize();
1222 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1223 assert(isPowerOf2_32(Align));
1224 Off &= -Align;
1225 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1226 MinOffset = std::min(MinOffset, Off);
1227 CSI.push_back(CalleeSavedInfo(R, FI));
1228 SRegs[R] = false;
1229 }
1230
1231 DEBUG({
1232 dbgs() << "CS information: {";
1233 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1234 int FI = CSI[i].getFrameIdx();
1235 int Off = MFI->getObjectOffset(FI);
1236 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1237 if (Off >= 0)
1238 dbgs() << '+';
1239 dbgs() << Off;
1240 }
1241 dbgs() << " }\n";
1242 });
1243
1244#ifndef NDEBUG
1245 // Verify that all registers were handled.
1246 bool MissedReg = false;
1247 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1248 unsigned R = x;
1249 dbgs() << PrintReg(R, TRI) << ' ';
1250 MissedReg = true;
1251 }
1252 if (MissedReg)
1253 llvm_unreachable("...there are unhandled callee-saved registers!");
1254#endif
1255
1256 return true;
1257}
1258
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001259
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001260bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1261 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1262 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1263 MachineInstr *MI = &*It;
1264 DebugLoc DL = MI->getDebugLoc();
1265 unsigned DstR = MI->getOperand(0).getReg();
1266 unsigned SrcR = MI->getOperand(1).getReg();
1267 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1268 !Hexagon::ModRegsRegClass.contains(SrcR))
1269 return false;
1270
1271 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1272 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1273 .addOperand(MI->getOperand(1));
1274 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1275 .addReg(TmpR, RegState::Kill);
1276
1277 NewRegs.push_back(TmpR);
1278 B.erase(It);
1279 return true;
1280}
1281
1282bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1283 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1284 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1285 MachineInstr *MI = &*It;
1286 DebugLoc DL = MI->getDebugLoc();
1287 unsigned Opc = MI->getOpcode();
1288 unsigned SrcR = MI->getOperand(2).getReg();
1289 bool IsKill = MI->getOperand(2).isKill();
1290
1291 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1292 int FI = MI->getOperand(0).getIndex();
1293
1294 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1295 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1296 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1297 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1298 : Hexagon::A2_tfrcrr;
1299 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1300 .addReg(SrcR, getKillRegState(IsKill));
1301
1302 // S2_storeri_io FI, 0, TmpR
1303 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1304 .addFrameIndex(FI)
1305 .addImm(0)
1306 .addReg(TmpR, RegState::Kill)
1307 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1308
1309 NewRegs.push_back(TmpR);
1310 B.erase(It);
1311 return true;
1312}
1313
1314bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1315 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1316 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1317 MachineInstr *MI = &*It;
1318 DebugLoc DL = MI->getDebugLoc();
1319 unsigned Opc = MI->getOpcode();
1320 unsigned DstR = MI->getOperand(0).getReg();
1321
1322 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1323 int FI = MI->getOperand(1).getIndex();
1324
1325 // TmpR = L2_loadri_io FI, 0
1326 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1327 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1328 .addFrameIndex(FI)
1329 .addImm(0)
1330 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1331
1332 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1333 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1334 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1335 : Hexagon::A2_tfrrcr;
1336 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1337 .addReg(TmpR, RegState::Kill);
1338
1339 NewRegs.push_back(TmpR);
1340 B.erase(It);
1341 return true;
1342}
1343
1344
1345bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1346 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1347 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1348 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1349 MachineInstr *MI = &*It;
1350 DebugLoc DL = MI->getDebugLoc();
1351 unsigned SrcR = MI->getOperand(2).getReg();
1352 bool IsKill = MI->getOperand(2).isKill();
1353
1354 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1355 int FI = MI->getOperand(0).getIndex();
1356
1357 bool Is128B = HST.useHVXDblOps();
1358 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1359 : &Hexagon::VectorRegs128BRegClass;
1360
1361 // Insert transfer to general vector register.
1362 // TmpR0 = A2_tfrsi 0x01010101
1363 // TmpR1 = V6_vandqrt Qx, TmpR0
1364 // store FI, 0, TmpR1
1365 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1366 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1367
1368 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1369 .addImm(0x01010101);
1370
1371 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1372 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1373 .addReg(SrcR, getKillRegState(IsKill))
1374 .addReg(TmpR0, RegState::Kill);
1375
1376 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1377 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1378 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1379
1380 NewRegs.push_back(TmpR0);
1381 NewRegs.push_back(TmpR1);
1382 B.erase(It);
1383 return true;
1384}
1385
1386bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1387 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1388 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1389 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1390 MachineInstr *MI = &*It;
1391 DebugLoc DL = MI->getDebugLoc();
1392 unsigned DstR = MI->getOperand(0).getReg();
1393
1394 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1395 int FI = MI->getOperand(1).getIndex();
1396
1397 bool Is128B = HST.useHVXDblOps();
1398 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1399 : &Hexagon::VectorRegs128BRegClass;
1400
1401 // TmpR0 = A2_tfrsi 0x01010101
1402 // TmpR1 = load FI, 0
1403 // DstR = V6_vandvrt TmpR1, TmpR0
1404 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1405 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1406
1407 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1408 .addImm(0x01010101);
1409 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1410 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1411 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1412
1413 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1414 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1415 .addReg(TmpR1, RegState::Kill)
1416 .addReg(TmpR0, RegState::Kill);
1417
1418 NewRegs.push_back(TmpR0);
1419 NewRegs.push_back(TmpR1);
1420 B.erase(It);
1421 return true;
1422}
1423
1424bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1425 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1426 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1427 MachineFunction &MF = *B.getParent();
1428 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1429 auto &MFI = *MF.getFrameInfo();
1430 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1431 MachineInstr *MI = &*It;
1432 DebugLoc DL = MI->getDebugLoc();
1433
1434 unsigned SrcR = MI->getOperand(2).getReg();
1435 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1436 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1437 bool IsKill = MI->getOperand(2).isKill();
1438
1439 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1440 int FI = MI->getOperand(0).getIndex();
1441
1442 bool Is128B = HST.useHVXDblOps();
1443 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1444 : &Hexagon::VectorRegs128BRegClass;
1445 unsigned Size = RC->getSize();
1446 unsigned NeedAlign = RC->getAlignment();
1447 unsigned HasAlign = MFI.getObjectAlignment(FI);
1448 unsigned StoreOpc;
1449
1450 // Store low part.
1451 if (NeedAlign <= HasAlign)
1452 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1453 else
1454 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1455
1456 BuildMI(B, It, DL, HII.get(StoreOpc))
1457 .addFrameIndex(FI)
1458 .addImm(0)
1459 .addReg(SrcLo, getKillRegState(IsKill))
1460 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1461
1462 // Load high part.
1463 if (NeedAlign <= MinAlign(HasAlign, Size))
1464 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1465 else
1466 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1467
1468 BuildMI(B, It, DL, HII.get(StoreOpc))
1469 .addFrameIndex(FI)
1470 .addImm(Size)
1471 .addReg(SrcHi, getKillRegState(IsKill))
1472 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1473
1474 B.erase(It);
1475 return true;
1476}
1477
1478bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1479 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1480 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1481 MachineFunction &MF = *B.getParent();
1482 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1483 auto &MFI = *MF.getFrameInfo();
1484 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1485 MachineInstr *MI = &*It;
1486 DebugLoc DL = MI->getDebugLoc();
1487
1488 unsigned DstR = MI->getOperand(0).getReg();
1489 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1490 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1491
1492 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1493 int FI = MI->getOperand(1).getIndex();
1494
1495 bool Is128B = HST.useHVXDblOps();
1496 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1497 : &Hexagon::VectorRegs128BRegClass;
1498 unsigned Size = RC->getSize();
1499 unsigned NeedAlign = RC->getAlignment();
1500 unsigned HasAlign = MFI.getObjectAlignment(FI);
1501 unsigned LoadOpc;
1502
1503 // Load low part.
1504 if (NeedAlign <= HasAlign)
1505 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1506 else
1507 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1508
1509 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1510 .addFrameIndex(FI)
1511 .addImm(0)
1512 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1513
1514 // Load high part.
1515 if (NeedAlign <= MinAlign(HasAlign, Size))
1516 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1517 else
1518 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1519
1520 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1521 .addFrameIndex(FI)
1522 .addImm(Size)
1523 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1524
1525 B.erase(It);
1526 return true;
1527}
1528
1529bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1530 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1531 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1532 MachineFunction &MF = *B.getParent();
1533 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1534 auto &MFI = *MF.getFrameInfo();
1535 MachineInstr *MI = &*It;
1536 DebugLoc DL = MI->getDebugLoc();
1537
1538 unsigned SrcR = MI->getOperand(2).getReg();
1539 bool IsKill = MI->getOperand(2).isKill();
1540
1541 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1542 int FI = MI->getOperand(0).getIndex();
1543
1544 bool Is128B = HST.useHVXDblOps();
1545 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1546 : &Hexagon::VectorRegs128BRegClass;
1547
1548 unsigned NeedAlign = RC->getAlignment();
1549 unsigned HasAlign = MFI.getObjectAlignment(FI);
1550 unsigned StoreOpc;
1551
1552 if (NeedAlign <= HasAlign)
1553 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1554 else
1555 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1556
1557 BuildMI(B, It, DL, HII.get(StoreOpc))
1558 .addFrameIndex(FI)
1559 .addImm(0)
1560 .addReg(SrcR, getKillRegState(IsKill))
1561 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1562
1563 B.erase(It);
1564 return true;
1565}
1566
1567bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1568 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1569 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1570 MachineFunction &MF = *B.getParent();
1571 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1572 auto &MFI = *MF.getFrameInfo();
1573 MachineInstr *MI = &*It;
1574 DebugLoc DL = MI->getDebugLoc();
1575
1576 unsigned DstR = MI->getOperand(0).getReg();
1577
1578 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1579 int FI = MI->getOperand(1).getIndex();
1580
1581 bool Is128B = HST.useHVXDblOps();
1582 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1583 : &Hexagon::VectorRegs128BRegClass;
1584
1585 unsigned NeedAlign = RC->getAlignment();
1586 unsigned HasAlign = MFI.getObjectAlignment(FI);
1587 unsigned LoadOpc;
1588
1589 if (NeedAlign <= HasAlign)
1590 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1591 else
1592 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1593
1594 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1595 .addFrameIndex(FI)
1596 .addImm(0)
1597 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1598
1599 B.erase(It);
1600 return true;
1601}
1602
1603
1604bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1605 SmallVectorImpl<unsigned> &NewRegs) const {
1606 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001607 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001608 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001609 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001610
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001611 for (auto &B : MF) {
1612 // Traverse the basic block.
1613 MachineBasicBlock::iterator NextI;
1614 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1615 MachineInstr *MI = &*I;
1616 NextI = std::next(I);
1617 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001618
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001619 switch (Opc) {
1620 case TargetOpcode::COPY:
1621 Changed = expandCopy(B, I, MRI, HII, NewRegs);
1622 break;
1623 case Hexagon::STriw_pred:
1624 case Hexagon::STriw_mod:
1625 Changed = expandStoreInt(B, I, MRI, HII, NewRegs);
1626 break;
1627 case Hexagon::LDriw_pred:
1628 case Hexagon::LDriw_mod:
1629 Changed = expandLoadInt(B, I, MRI, HII, NewRegs);
1630 break;
1631 case Hexagon::STriq_pred_V6:
1632 case Hexagon::STriq_pred_V6_128B:
1633 Changed = expandStoreVecPred(B, I, MRI, HII, NewRegs);
1634 break;
1635 case Hexagon::LDriq_pred_V6:
1636 case Hexagon::LDriq_pred_V6_128B:
1637 Changed = expandLoadVecPred(B, I, MRI, HII, NewRegs);
1638 break;
1639 case Hexagon::LDrivv_pseudo_V6:
1640 case Hexagon::LDrivv_pseudo_V6_128B:
1641 Changed = expandLoadVec2(B, I, MRI, HII, NewRegs);
1642 break;
1643 case Hexagon::STrivv_pseudo_V6:
1644 case Hexagon::STrivv_pseudo_V6_128B:
1645 Changed = expandStoreVec2(B, I, MRI, HII, NewRegs);
1646 break;
1647 case Hexagon::STriv_pseudo_V6:
1648 case Hexagon::STriv_pseudo_V6_128B:
1649 Changed = expandStoreVec(B, I, MRI, HII, NewRegs);
1650 break;
1651 case Hexagon::LDriv_pseudo_V6:
1652 case Hexagon::LDriv_pseudo_V6_128B:
1653 Changed = expandLoadVec(B, I, MRI, HII, NewRegs);
1654 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001655 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001656 }
1657 }
1658
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001659 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001660}
1661
1662
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001663void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1664 BitVector &SavedRegs,
1665 RegScavenger *RS) const {
1666 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1667 auto &HRI = *HST.getRegisterInfo();
1668
1669 SavedRegs.resize(HRI.getNumRegs());
1670
1671 // If we have a function containing __builtin_eh_return we want to spill and
1672 // restore all callee saved registers. Pretend that they are used.
1673 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1674 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1675 SavedRegs.set(*R);
1676
1677 // Replace predicate register pseudo spill code.
1678 SmallVector<unsigned,8> NewRegs;
1679 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001680 if (OptimizeSpillSlots)
1681 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001682
1683 // We need to reserve a a spill slot if scavenging could potentially require
1684 // spilling a scavenged register.
1685 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1686 MachineRegisterInfo &MRI = MF.getRegInfo();
1687 SetVector<const TargetRegisterClass*> SpillRCs;
1688 for (unsigned VR : NewRegs)
1689 SpillRCs.insert(MRI.getRegClass(VR));
1690
1691 MachineFrameInfo &MFI = *MF.getFrameInfo();
1692 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1693 if (SpillRCs.count(&IntRC)) {
1694 for (int i = 0; i < NumberScavengerSlots; i++) {
1695 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1696 IntRC.getAlignment());
1697 RS->addScavengingFrameIndex(NewFI);
1698 }
1699 }
1700 for (auto *RC : SpillRCs) {
1701 if (RC == &IntRC)
1702 continue;
1703 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1704 RS->addScavengingFrameIndex(NewFI);
1705 }
1706 }
1707
1708 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1709}
1710
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001711
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001712unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1713 HexagonBlockRanges::IndexRange &FIR,
1714 HexagonBlockRanges::InstrIndexMap &IndexMap,
1715 HexagonBlockRanges::RegToRangeMap &DeadMap,
1716 const TargetRegisterClass *RC) const {
1717 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1718 auto &MRI = MF.getRegInfo();
1719
1720 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1721 auto F = DeadMap.find({Reg,0});
1722 if (F == DeadMap.end())
1723 return false;
1724 for (auto &DR : F->second)
1725 if (DR.contains(FIR))
1726 return true;
1727 return false;
1728 };
1729
1730 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1731 bool Dead = true;
1732 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1733 if (isDead(R.Reg))
1734 continue;
1735 Dead = false;
1736 break;
1737 }
1738 if (Dead)
1739 return Reg;
1740 }
1741 return 0;
1742}
1743
1744void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1745 SmallVectorImpl<unsigned> &VRegs) const {
1746 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1747 auto &HII = *HST.getInstrInfo();
1748 auto &HRI = *HST.getRegisterInfo();
1749 auto &MRI = MF.getRegInfo();
1750 HexagonBlockRanges HBR(MF);
1751
1752 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1753 BlockIndexMap;
1754 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1755 BlockRangeMap;
1756 typedef HexagonBlockRanges::IndexType IndexType;
1757
1758 struct SlotInfo {
1759 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001760 unsigned Size;
1761 const TargetRegisterClass *RC;
1762
1763 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001764 };
1765
1766 BlockIndexMap BlockIndexes;
1767 SmallSet<int,4> BadFIs;
1768 std::map<int,SlotInfo> FIRangeMap;
1769
1770 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1771 -> const TargetRegisterClass* {
1772 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1773 assert(R.Sub == 0);
1774 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1775 auto *RCR = MRI.getRegClass(R.Reg);
1776 if (R.Sub == 0)
1777 return RCR;
1778 unsigned PR = *RCR->begin();
1779 R.Reg = HRI.getSubReg(PR, R.Sub);
1780 }
1781 return HRI.getMinimalPhysRegClass(R.Reg);
1782 };
1783 // Accumulate register classes: get a common class for a pre-existing
1784 // class HaveRC and a new class NewRC. Return nullptr if a common class
1785 // cannot be found, otherwise return the resulting class. If HaveRC is
1786 // nullptr, assume that it is still unset.
1787 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1788 const TargetRegisterClass *NewRC)
1789 -> const TargetRegisterClass* {
1790 if (HaveRC == nullptr || HaveRC == NewRC)
1791 return NewRC;
1792 // Different classes, both non-null. Pick the more general one.
1793 if (HaveRC->hasSubClassEq(NewRC))
1794 return HaveRC;
1795 if (NewRC->hasSubClassEq(HaveRC))
1796 return NewRC;
1797 return nullptr;
1798 };
1799
1800 // Scan all blocks in the function. Check all occurrences of frame indexes,
1801 // and collect relevant information.
1802 for (auto &B : MF) {
1803 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001804 // Emplace appears not to be supported in gcc 4.7.2-4.
1805 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001806 auto P = BlockIndexes.insert(
1807 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001808 auto &IndexMap = P.first->second;
1809 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1810 << IndexMap << '\n');
1811
1812 for (auto &In : B) {
1813 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001814 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1815 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001816 if (Load && Store) {
1817 // If it's both a load and a store, then we won't handle it.
1818 BadFIs.insert(LFI);
1819 BadFIs.insert(SFI);
1820 continue;
1821 }
1822 // Check for register classes of the register used as the source for
1823 // the store, and the register used as the destination for the load.
1824 // Also, only accept base+imm_offset addressing modes. Other addressing
1825 // modes can have side-effects (post-increments, etc.). For stack
1826 // slots they are very unlikely, so there is not much loss due to
1827 // this restriction.
1828 if (Load || Store) {
1829 int TFI = Load ? LFI : SFI;
1830 unsigned AM = HII.getAddrMode(&In);
1831 SlotInfo &SI = FIRangeMap[TFI];
1832 bool Bad = (AM != HexagonII::BaseImmOffset);
1833 if (!Bad) {
1834 // If the addressing mode is ok, check the register class.
1835 const TargetRegisterClass *RC = nullptr;
1836 if (Load) {
1837 MachineOperand &DataOp = In.getOperand(0);
1838 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1839 } else {
1840 MachineOperand &DataOp = In.getOperand(2);
1841 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1842 }
1843 RC = getCommonRC(SI.RC, RC);
1844 if (RC == nullptr)
1845 Bad = true;
1846 else
1847 SI.RC = RC;
1848 }
1849 if (!Bad) {
1850 // Check sizes.
1851 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1852 if (SI.Size != 0 && SI.Size != S)
1853 Bad = true;
1854 else
1855 SI.Size = S;
1856 }
1857 if (Bad)
1858 BadFIs.insert(TFI);
1859 }
1860
1861 // Locate uses of frame indices.
1862 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1863 const MachineOperand &Op = In.getOperand(i);
1864 if (!Op.isFI())
1865 continue;
1866 int FI = Op.getIndex();
1867 // Make sure that the following operand is an immediate and that
1868 // it is 0. This is the offset in the stack object.
1869 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1870 In.getOperand(i+1).getImm() != 0)
1871 BadFIs.insert(FI);
1872 if (BadFIs.count(FI))
1873 continue;
1874
1875 IndexType Index = IndexMap.getIndex(&In);
1876 if (Load) {
1877 if (LastStore[FI] == IndexType::None)
1878 LastStore[FI] = IndexType::Entry;
1879 LastLoad[FI] = Index;
1880 } else if (Store) {
1881 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1882 if (LastStore[FI] != IndexType::None)
1883 RL.add(LastStore[FI], LastLoad[FI], false, false);
1884 else if (LastLoad[FI] != IndexType::None)
1885 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1886 LastLoad[FI] = IndexType::None;
1887 LastStore[FI] = Index;
1888 } else {
1889 BadFIs.insert(FI);
1890 }
1891 }
1892 }
1893
1894 for (auto &I : LastLoad) {
1895 IndexType LL = I.second;
1896 if (LL == IndexType::None)
1897 continue;
1898 auto &RL = FIRangeMap[I.first].Map[&B];
1899 IndexType &LS = LastStore[I.first];
1900 if (LS != IndexType::None)
1901 RL.add(LS, LL, false, false);
1902 else
1903 RL.add(IndexType::Entry, LL, false, false);
1904 LS = IndexType::None;
1905 }
1906 for (auto &I : LastStore) {
1907 IndexType LS = I.second;
1908 if (LS == IndexType::None)
1909 continue;
1910 auto &RL = FIRangeMap[I.first].Map[&B];
1911 RL.add(LS, IndexType::None, false, false);
1912 }
1913 }
1914
1915 DEBUG({
1916 for (auto &P : FIRangeMap) {
1917 dbgs() << "fi#" << P.first;
1918 if (BadFIs.count(P.first))
1919 dbgs() << " (bad)";
1920 dbgs() << " RC: ";
1921 if (P.second.RC != nullptr)
1922 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1923 else
1924 dbgs() << "<null>\n";
1925 for (auto &R : P.second.Map)
1926 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1927 }
1928 });
1929
1930 // When a slot is loaded from in a block without being stored to in the
1931 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1932 // consider this slot to be live-on-exit from all blocks.
1933 SmallSet<int,4> LoxFIs;
1934
1935 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1936
1937 for (auto &P : FIRangeMap) {
1938 // P = pair(FI, map: BB->RangeList)
1939 if (BadFIs.count(P.first))
1940 continue;
1941 for (auto &B : MF) {
1942 auto F = P.second.Map.find(&B);
1943 // F = pair(BB, RangeList)
1944 if (F == P.second.Map.end() || F->second.empty())
1945 continue;
1946 HexagonBlockRanges::IndexRange &IR = F->second.front();
1947 if (IR.start() == IndexType::Entry)
1948 LoxFIs.insert(P.first);
1949 BlockFIMap[&B].push_back(P.first);
1950 }
1951 }
1952
1953 DEBUG({
1954 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1955 for (auto &P : BlockFIMap) {
1956 auto &FIs = P.second;
1957 if (FIs.empty())
1958 continue;
1959 dbgs() << " BB#" << P.first->getNumber() << ": {";
1960 for (auto I : FIs) {
1961 dbgs() << " fi#" << I;
1962 if (LoxFIs.count(I))
1963 dbgs() << '*';
1964 }
1965 dbgs() << " }\n";
1966 }
1967 });
1968
1969 // eliminate loads, when all loads eliminated, eliminate all stores.
1970 for (auto &B : MF) {
1971 auto F = BlockIndexes.find(&B);
1972 assert(F != BlockIndexes.end());
1973 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1974 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
1975 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
1976 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
1977 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
1978
1979 for (auto FI : BlockFIMap[&B]) {
1980 if (BadFIs.count(FI))
1981 continue;
1982 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
1983 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1984 for (auto &Range : RL) {
1985 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
1986 if (!IndexType::isInstr(Range.start()) ||
1987 !IndexType::isInstr(Range.end()))
1988 continue;
1989 MachineInstr *SI = IM.getInstr(Range.start());
1990 MachineInstr *EI = IM.getInstr(Range.end());
1991 assert(SI->mayStore() && "Unexpected start instruction");
1992 assert(EI->mayLoad() && "Unexpected end instruction");
1993 MachineOperand &SrcOp = SI->getOperand(2);
1994
1995 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
1996 SrcOp.getSubReg() };
1997 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
1998 // The this-> is needed to unconfuse MSVC.
1999 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2000 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2001 if (FoundR == 0)
2002 continue;
2003
2004 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2005 MachineBasicBlock::iterator StartIt = SI, NextIt;
2006 MachineInstr *CopyIn = nullptr;
2007 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2008 DebugLoc DL = SI->getDebugLoc();
2009 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2010 .addOperand(SrcOp);
2011 }
2012
2013 ++StartIt;
2014 // Check if this is a last store and the FI is live-on-exit.
2015 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2016 // Update store's source register.
2017 if (unsigned SR = SrcOp.getSubReg())
2018 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2019 else
2020 SrcOp.setReg(FoundR);
2021 SrcOp.setSubReg(0);
2022 // We are keeping this register live.
2023 SrcOp.setIsKill(false);
2024 } else {
2025 B.erase(SI);
2026 IM.replaceInstr(SI, CopyIn);
2027 }
2028
2029 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2030 for (auto It = StartIt; It != EndIt; It = NextIt) {
2031 MachineInstr *MI = &*It;
2032 NextIt = std::next(It);
2033 int TFI;
2034 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2035 continue;
2036 unsigned DstR = MI->getOperand(0).getReg();
2037 assert(MI->getOperand(0).getSubReg() == 0);
2038 MachineInstr *CopyOut = nullptr;
2039 if (DstR != FoundR) {
2040 DebugLoc DL = MI->getDebugLoc();
2041 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2042 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2043 unsigned CopyOpc = TargetOpcode::COPY;
2044 if (HII.isSignExtendingLoad(MI))
2045 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2046 else if (HII.isZeroExtendingLoad(MI))
2047 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2048 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2049 .addReg(FoundR, getKillRegState(MI == EI));
2050 }
2051 IM.replaceInstr(MI, CopyOut);
2052 B.erase(It);
2053 }
2054
2055 // Update the dead map.
2056 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2057 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2058 DM[RR].subtract(Range);
2059 } // for Range in range list
2060 }
2061 }
2062}
2063
2064
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002065void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002066 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002067 MachineBasicBlock &MB = *AI->getParent();
2068 DebugLoc DL = AI->getDebugLoc();
2069 unsigned A = AI->getOperand(2).getImm();
2070
2071 // Have
2072 // Rd = alloca Rs, #A
2073 //
2074 // If Rs and Rd are different registers, use this sequence:
2075 // Rd = sub(r29, Rs)
2076 // r29 = sub(r29, Rs)
2077 // Rd = and(Rd, #-A) ; if necessary
2078 // r29 = and(r29, #-A) ; if necessary
2079 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2080 // otherwise, do
2081 // Rd = sub(r29, Rs)
2082 // Rd = and(Rd, #-A) ; if necessary
2083 // r29 = Rd
2084 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2085
2086 MachineOperand &RdOp = AI->getOperand(0);
2087 MachineOperand &RsOp = AI->getOperand(1);
2088 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2089
2090 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002091 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002092 .addReg(SP)
2093 .addReg(Rs);
2094 if (Rs != Rd) {
2095 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002096 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002097 .addReg(SP)
2098 .addReg(Rs);
2099 }
2100 if (A > 8) {
2101 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002102 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002103 .addReg(Rd)
2104 .addImm(-int64_t(A));
2105 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002106 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002107 .addReg(SP)
2108 .addImm(-int64_t(A));
2109 }
2110 if (Rs == Rd) {
2111 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002112 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002113 .addReg(Rd);
2114 }
2115 if (CF > 0) {
2116 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002117 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002118 .addReg(Rd)
2119 .addImm(CF);
2120 }
2121}
2122
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002123
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002124bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2125 const MachineFrameInfo *MFI = MF.getFrameInfo();
2126 if (!MFI->hasVarSizedObjects())
2127 return false;
2128 unsigned MaxA = MFI->getMaxAlignment();
2129 if (MaxA <= getStackAlignment())
2130 return false;
2131 return true;
2132}
2133
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002134
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002135const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2136 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002137 for (auto &B : MF)
2138 for (auto &I : B)
2139 if (I.getOpcode() == Hexagon::ALIGNA)
2140 return &I;
2141 return nullptr;
2142}
2143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002144
Sanjay Patel924879a2015-08-04 15:49:57 +00002145// FIXME: Use Function::optForSize().
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002146inline static bool isOptSize(const MachineFunction &MF) {
2147 AttributeSet AF = MF.getFunction()->getAttributes();
2148 return AF.hasAttribute(AttributeSet::FunctionIndex,
2149 Attribute::OptimizeForSize);
2150}
2151
2152inline static bool isMinSize(const MachineFunction &MF) {
Sanjay Patel924879a2015-08-04 15:49:57 +00002153 return MF.getFunction()->optForMinSize();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002154}
2155
2156
2157/// Determine whether the callee-saved register saves and restores should
2158/// be generated via inline code. If this function returns "true", inline
2159/// code will be generated. If this function returns "false", additional
2160/// checks are performed, which may still lead to the inline code.
2161bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2162 const CSIVect &CSI) const {
2163 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2164 return true;
2165 if (!isOptSize(MF) && !isMinSize(MF))
2166 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2167 return true;
2168
2169 // Check if CSI only has double registers, and if the registers form
2170 // a contiguous block starting from D8.
2171 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2172 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2173 unsigned R = CSI[i].getReg();
2174 if (!Hexagon::DoubleRegsRegClass.contains(R))
2175 return true;
2176 Regs[R] = true;
2177 }
2178 int F = Regs.find_first();
2179 if (F != Hexagon::D8)
2180 return true;
2181 while (F >= 0) {
2182 int N = Regs.find_next(F);
2183 if (N >= 0 && N != F+1)
2184 return true;
2185 F = N;
2186 }
2187
2188 return false;
2189}
2190
2191
2192bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2193 const CSIVect &CSI) const {
2194 if (shouldInlineCSR(MF, CSI))
2195 return false;
2196 unsigned NumCSI = CSI.size();
2197 if (NumCSI <= 1)
2198 return false;
2199
2200 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2201 : SpillFuncThreshold;
2202 return Threshold < NumCSI;
2203}
2204
2205
2206bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2207 const CSIVect &CSI) const {
2208 if (shouldInlineCSR(MF, CSI))
2209 return false;
2210 unsigned NumCSI = CSI.size();
2211 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2212 : SpillFuncThreshold;
2213 return Threshold < NumCSI;
2214}