blob: ac91169a7b5021fb5c4fc9637570ee32fb79447b [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.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000237 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
238 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000239 for (auto &I : MBB) {
240 const MachineInstr *MI = &I;
241 if (MI->isCall())
242 return true;
243 unsigned Opc = MI->getOpcode();
244 switch (Opc) {
245 case Hexagon::ALLOCA:
246 case Hexagon::ALIGNA:
247 return true;
248 default:
249 break;
250 }
251 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000252 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000253 // While the presence of a frame index does not prove that a stack
254 // frame will be required, all frame indexes should be within alloc-
255 // frame/deallocframe. Otherwise, the code that translates a frame
256 // index into an offset would have to be aware of the placement of
257 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000258 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000259 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000260 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000261 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000262 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000263 // Virtual registers will need scavenging, which then may require
264 // a stack slot.
265 if (TargetRegisterInfo::isVirtualRegister(R))
266 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000267 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
268 if (CSR[*S])
269 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000270 }
271 }
272 return false;
273 }
274
275 /// Returns true if MBB has a machine instructions that indicates a tail call
276 /// in the block.
277 bool hasTailCall(const MachineBasicBlock &MBB) {
278 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
279 unsigned RetOpc = I->getOpcode();
280 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
281 }
282
283 /// Returns true if MBB contains an instruction that returns.
284 bool hasReturn(const MachineBasicBlock &MBB) {
285 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
286 if (I->isReturn())
287 return true;
288 return false;
289 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000290
291 inline bool isOptNone(const MachineFunction &MF) {
292 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
293 MF.getTarget().getOptLevel() == CodeGenOpt::None;
294 }
295
296 inline bool isOptSize(const MachineFunction &MF) {
297 const Function &F = *MF.getFunction();
298 return F.optForSize() && !F.optForMinSize();
299 }
300
301 inline bool isMinSize(const MachineFunction &MF) {
302 return MF.getFunction()->optForMinSize();
303 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000304}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000305
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000306
307/// Implements shrink-wrapping of the stack frame. By default, stack frame
308/// is created in the function entry block, and is cleaned up in every block
309/// that returns. This function finds alternate blocks: one for the frame
310/// setup (prolog) and one for the cleanup (epilog).
311void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
312 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
313 static unsigned ShrinkCounter = 0;
314
315 if (ShrinkLimit.getPosition()) {
316 if (ShrinkCounter >= ShrinkLimit)
317 return;
318 ShrinkCounter++;
319 }
320
321 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
322 auto &HRI = *HST.getRegisterInfo();
323
324 MachineDominatorTree MDT;
325 MDT.runOnMachineFunction(MF);
326 MachinePostDominatorTree MPT;
327 MPT.runOnMachineFunction(MF);
328
329 typedef DenseMap<unsigned,unsigned> UnsignedMap;
330 UnsignedMap RPO;
331 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
332 RPOTType RPOT(&MF);
333 unsigned RPON = 0;
334 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
335 RPO[(*I)->getNumber()] = RPON++;
336
337 // Don't process functions that have loops, at least for now. Placement
338 // of prolog and epilog must take loop structure into account. For simpli-
339 // city don't do it right now.
340 for (auto &I : MF) {
341 unsigned BN = RPO[I.getNumber()];
342 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
343 // If found a back-edge, return.
344 if (RPO[(*SI)->getNumber()] <= BN)
345 return;
346 }
347 }
348
349 // Collect the set of blocks that need a stack frame to execute. Scan
350 // each block for uses/defs of callee-saved registers, calls, etc.
351 SmallVector<MachineBasicBlock*,16> SFBlocks;
352 BitVector CSR(Hexagon::NUM_TARGET_REGS);
353 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000354 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
355 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000356
357 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000358 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000359 SFBlocks.push_back(&I);
360
361 DEBUG({
362 dbgs() << "Blocks needing SF: {";
363 for (auto &B : SFBlocks)
364 dbgs() << " BB#" << B->getNumber();
365 dbgs() << " }\n";
366 });
367 // No frame needed?
368 if (SFBlocks.empty())
369 return;
370
371 // Pick a common dominator and a common post-dominator.
372 MachineBasicBlock *DomB = SFBlocks[0];
373 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
374 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
375 if (!DomB)
376 break;
377 }
378 MachineBasicBlock *PDomB = SFBlocks[0];
379 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
380 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
381 if (!PDomB)
382 break;
383 }
384 DEBUG({
385 dbgs() << "Computed dom block: BB#";
386 if (DomB) dbgs() << DomB->getNumber();
387 else dbgs() << "<null>";
388 dbgs() << ", computed pdom block: BB#";
389 if (PDomB) dbgs() << PDomB->getNumber();
390 else dbgs() << "<null>";
391 dbgs() << "\n";
392 });
393 if (!DomB || !PDomB)
394 return;
395
396 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
397 if (!MDT.dominates(DomB, PDomB)) {
398 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
399 return;
400 }
401 if (!MPT.dominates(PDomB, DomB)) {
402 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
403 return;
404 }
405
406 // Finally, everything seems right.
407 PrologB = DomB;
408 EpilogB = PDomB;
409}
410
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000411
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000412/// Perform most of the PEI work here:
413/// - saving/restoring of the callee-saved registers,
414/// - stack frame creation and destruction.
415/// Normally, this work is distributed among various functions, but doing it
416/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000417void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
418 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000419 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
420 auto &HRI = *HST.getRegisterInfo();
421
422 MachineFrameInfo *MFI = MF.getFrameInfo();
423 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
424
425 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
426 if (EnableShrinkWrapping)
427 findShrunkPrologEpilog(MF, PrologB, EpilogB);
428
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000429 bool PrologueStubs = false;
430 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
431 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000432
433 if (EpilogB) {
434 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
435 insertEpilogueInBlock(*EpilogB);
436 } else {
437 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000438 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000439 insertCSRRestoresInBlock(B, CSI, HRI);
440
441 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000442 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000443 insertEpilogueInBlock(B);
444 }
445}
446
447
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000448void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
449 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000450 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000451 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000452 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000453 auto &HII = *HST.getInstrInfo();
454 auto &HRI = *HST.getRegisterInfo();
455 DebugLoc dl;
456
457 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
458
459 // Calculate the total stack frame size.
460 // Get the number of bytes to allocate from the FrameInfo.
461 unsigned FrameSize = MFI->getStackSize();
462 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000463 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000464 MFI->setMaxCallFrameSize(MaxCFA);
465
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000466 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000467 MFI->setStackSize(FrameSize);
468
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000469 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000470
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000471 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000472 unsigned NumBytes = MFI->getStackSize();
473 unsigned SP = HRI.getStackRegister();
474 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000475 MachineBasicBlock::iterator InsertPt = MBB.begin();
476
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000477 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
478 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000479
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000480 for (auto MI : AdjustRegs) {
481 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
482 expandAlloca(MI, HII, SP, MaxCF);
483 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000484 }
485
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000486 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000487 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000488
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000489 // Check for overflow.
490 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
491 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000492
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000493 // Create a dummy memory operand to avoid allocframe from being treated as
494 // a volatile memory reference.
495 MachineMemOperand *MMO =
496 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
497 4, 4);
498
499 if (NumBytes >= ALLOCFRAME_MAX) {
500 // Emit allocframe(#0).
501 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
502 .addImm(0)
503 .addMemOperand(MMO);
504
505 // Subtract offset from frame pointer.
506 // We use a caller-saved non-parameter register for that.
507 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
508 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
509 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000510 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
511 .addReg(SP)
512 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000513 } else {
514 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
515 .addImm(NumBytes)
516 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000517 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000518
519 if (AlignStack) {
520 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
521 .addReg(SP)
522 .addImm(-int64_t(MaxAlign));
523 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000524
525 // If the stack-checking is enabled, and we spilled the callee-saved
526 // registers inline (i.e. did not use a spill function), then call
527 // the stack checker directly.
528 if (EnableStackOVFSanitizer && !PrologueStubs)
529 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
530 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000531}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000532
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000533void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
534 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000535 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000536 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000537
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000538 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
539 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000540 auto &HRI = *HST.getRegisterInfo();
541 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000542
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000543 MachineInstr *RetI = nullptr;
544 for (auto &I : MBB) {
545 if (!I.isReturn())
546 continue;
547 RetI = &I;
548 break;
549 }
550 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
551
552 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
553 DebugLoc DL;
554 if (InsertPt != MBB.end())
555 DL = InsertPt->getDebugLoc();
556 else if (!MBB.empty())
557 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000558
559 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000560 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000561 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
562 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
563 .addReg(SP)
564 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000565 return;
566 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000567
568 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
569 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000570 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
571 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000572 MachineBasicBlock::iterator It = RetI;
573 ++It;
574 // Delete all instructions after the RESTORE (except labels).
575 while (It != MBB.end()) {
576 if (!It->isLabel())
577 It = MBB.erase(It);
578 else
579 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000580 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000581 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000582 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000583
584 // It is possible that the restoring code is a call to a library function.
585 // All of the restore* functions include "deallocframe", so we need to make
586 // sure that we don't add an extra one.
587 bool NeedsDeallocframe = true;
588 if (!MBB.empty() && InsertPt != MBB.begin()) {
589 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
590 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000591 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
592 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000593 NeedsDeallocframe = false;
594 }
595
596 if (!NeedsDeallocframe)
597 return;
598 // If the returning instruction is JMPret, replace it with dealloc_return,
599 // otherwise just add deallocframe. The function could be returning via a
600 // tail call.
601 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
602 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
603 return;
604 }
605 unsigned NewOpc = Hexagon::L4_return;
606 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
607 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000608 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000609 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000610}
611
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000612
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000613namespace {
614 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
615 if (!It->isBundle())
616 return It->getOpcode() == Hexagon::S2_allocframe;
617 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000618 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000619 while (++I != End && I->isBundled())
620 if (I->getOpcode() == Hexagon::S2_allocframe)
621 return true;
622 return false;
623 }
624
625 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
626 for (auto &I : B)
627 if (IsAllocFrame(I))
628 return I;
629 return B.end();
630 }
631}
632
633
634void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
635 for (auto &B : MF) {
636 auto AF = FindAllocFrame(B);
637 if (AF == B.end())
638 continue;
639 insertCFIInstructionsAt(B, ++AF);
640 }
641}
642
643
644void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
645 MachineBasicBlock::iterator At) const {
646 MachineFunction &MF = *MBB.getParent();
647 MachineFrameInfo *MFI = MF.getFrameInfo();
648 MachineModuleInfo &MMI = MF.getMMI();
649 auto &HST = MF.getSubtarget<HexagonSubtarget>();
650 auto &HII = *HST.getInstrInfo();
651 auto &HRI = *HST.getRegisterInfo();
652
653 // If CFI instructions have debug information attached, something goes
654 // wrong with the final assembly generation: the prolog_end is placed
655 // in a wrong location.
656 DebugLoc DL;
657 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
658
659 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
660
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000661 if (hasFP(MF)) {
662 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
663 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000664
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000665 // Define CFA via an offset from the value of FP.
666 //
667 // -8 -4 0 (SP)
668 // --+----+----+---------------------
669 // | FP | LR | increasing addresses -->
670 // --+----+----+---------------------
671 // | +-- Old SP (before allocframe)
672 // +-- New FP (after allocframe)
673 //
674 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
675 // MCCFIInstruction::createOffset takes the offset without sign change.
676 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
677 BuildMI(MBB, At, DL, CFID)
678 .addCFIIndex(MMI.addFrameInst(DefCfa));
679 // R31 (return addr) = CFA - 4
680 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
681 BuildMI(MBB, At, DL, CFID)
682 .addCFIIndex(MMI.addFrameInst(OffR31));
683 // R30 (frame ptr) = CFA - 8
684 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
685 BuildMI(MBB, At, DL, CFID)
686 .addCFIIndex(MMI.addFrameInst(OffR30));
687 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000688
689 static unsigned int RegsToMove[] = {
690 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
691 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
692 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
693 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
694 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
695 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
696 Hexagon::NoRegister
697 };
698
699 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
700
701 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
702 unsigned Reg = RegsToMove[i];
703 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
704 return C.getReg() == Reg;
705 };
706 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
707 if (F == CSI.end())
708 continue;
709
710 // Subtract 8 to make room for R30 and R31, which are added above.
711 unsigned FrameReg;
712 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
713
714 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
715 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
716 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
717 Offset);
718 BuildMI(MBB, At, DL, CFID)
719 .addCFIIndex(MMI.addFrameInst(OffReg));
720 } else {
721 // Split the double regs into subregs, and generate appropriate
722 // cfi_offsets.
723 // The only reason, we are split double regs is, llvm-mc does not
724 // understand paired registers for cfi_offset.
725 // Eg .cfi_offset r1:0, -64
726
727 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
728 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
729 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
730 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
731 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
732 Offset+4);
733 BuildMI(MBB, At, DL, CFID)
734 .addCFIIndex(MMI.addFrameInst(OffHi));
735 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
736 Offset);
737 BuildMI(MBB, At, DL, CFID)
738 .addCFIIndex(MMI.addFrameInst(OffLo));
739 }
740 }
741}
742
743
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000744bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000745 auto &MFI = *MF.getFrameInfo();
746 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
747
748 bool HasFixed = MFI.getNumFixedObjects();
749 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
750 .getLocalFrameObjectCount();
751 bool HasExtraAlign = HRI.needsStackRealignment(MF);
752 bool HasAlloca = MFI.hasVarSizedObjects();
753
754 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
755 // that this shouldn't be required, but doing so now because gcc does and
756 // gdb can't break at the start of the function without it. Will remove if
757 // this turns out to be a gdb bug.
758 //
759 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
760 return true;
761
762 // By default we want to use SP (since it's always there). FP requires
763 // some setup (i.e. ALLOCFRAME).
764 // Fixed and preallocated objects need FP if the distance from them to
765 // the SP is unknown (as is with alloca or aligna).
766 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
767 return true;
768
769 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000770 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000771 return true;
772 }
773
774 if (MFI.hasCalls() ||
775 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
776 return true;
777
778 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000779}
780
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000781
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000782enum SpillKind {
783 SK_ToMem,
784 SK_FromMem,
785 SK_FromMemTailcall
786};
787
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000788static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
789 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000790 const char * V4SpillToMemoryFunctions[] = {
791 "__save_r16_through_r17",
792 "__save_r16_through_r19",
793 "__save_r16_through_r21",
794 "__save_r16_through_r23",
795 "__save_r16_through_r25",
796 "__save_r16_through_r27" };
797
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000798 const char * V4SpillToMemoryStkchkFunctions[] = {
799 "__save_r16_through_r17_stkchk",
800 "__save_r16_through_r19_stkchk",
801 "__save_r16_through_r21_stkchk",
802 "__save_r16_through_r23_stkchk",
803 "__save_r16_through_r25_stkchk",
804 "__save_r16_through_r27_stkchk" };
805
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000806 const char * V4SpillFromMemoryFunctions[] = {
807 "__restore_r16_through_r17_and_deallocframe",
808 "__restore_r16_through_r19_and_deallocframe",
809 "__restore_r16_through_r21_and_deallocframe",
810 "__restore_r16_through_r23_and_deallocframe",
811 "__restore_r16_through_r25_and_deallocframe",
812 "__restore_r16_through_r27_and_deallocframe" };
813
814 const char * V4SpillFromMemoryTailcallFunctions[] = {
815 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
816 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
817 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
818 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
819 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
820 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
821 };
822
823 const char **SpillFunc = nullptr;
824
825 switch(SpillType) {
826 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000827 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
828 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000829 break;
830 case SK_FromMem:
831 SpillFunc = V4SpillFromMemoryFunctions;
832 break;
833 case SK_FromMemTailcall:
834 SpillFunc = V4SpillFromMemoryTailcallFunctions;
835 break;
836 }
837 assert(SpillFunc && "Unknown spill kind");
838
839 // Spill all callee-saved registers up to the highest register used.
840 switch (MaxReg) {
841 case Hexagon::R17:
842 return SpillFunc[0];
843 case Hexagon::R19:
844 return SpillFunc[1];
845 case Hexagon::R21:
846 return SpillFunc[2];
847 case Hexagon::R23:
848 return SpillFunc[3];
849 case Hexagon::R25:
850 return SpillFunc[4];
851 case Hexagon::R27:
852 return SpillFunc[5];
853 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000854 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000855 }
856 return 0;
857}
858
859/// Adds all callee-saved registers up to MaxReg to the instruction.
860static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
861 unsigned MaxReg, bool IsDef) {
862 // Add the callee-saved registers as implicit uses.
863 for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
864 MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
865 Inst->addOperand(ImpUse);
866 }
867}
868
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000869
James Y Knight5567baf2015-08-15 02:32:35 +0000870int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000871 int FI, unsigned &FrameReg) const {
872 auto &MFI = *MF.getFrameInfo();
873 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000874
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000875 int Offset = MFI.getObjectOffset(FI);
876 bool HasAlloca = MFI.hasVarSizedObjects();
877 bool HasExtraAlign = HRI.needsStackRealignment(MF);
878 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000879
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000880 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000881 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
882 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000883 unsigned FrameSize = MFI.getStackSize();
884
885 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
886 // Use FP at -O0, except when there are objects with extra alignment.
887 // That additional alignment requirement may cause a pad to be inserted,
888 // which will make it impossible to use FP to access objects located
889 // past the pad.
890 if (NoOpt && !HasExtraAlign)
891 UseFP = true;
892 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
893 // Fixed and preallocated objects will be located before any padding
894 // so FP must be used to access them.
895 UseFP |= (HasAlloca || HasExtraAlign);
896 } else {
897 if (HasAlloca) {
898 if (HasExtraAlign)
899 UseAP = true;
900 else
901 UseFP = true;
902 }
903 }
904
905 // If FP was picked, then there had better be FP.
906 bool HasFP = hasFP(MF);
907 assert((HasFP || !UseFP) && "This function must have frame pointer");
908
909 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
910 // FP/LR. If the base register is used to access an object across these
911 // 8 bytes, then the offset will need to be adjusted by 8.
912 //
913 // After allocframe:
914 // HexagonISelLowering adds 8 to ---+
915 // the offsets of all stack-based |
916 // arguments (*) |
917 // |
918 // getObjectOffset < 0 0 8 getObjectOffset >= 8
919 // ------------------------+-----+------------------------> increasing
920 // <local objects> |FP/LR| <input arguments> addresses
921 // -----------------+------+-----+------------------------>
922 // | |
923 // SP/AP point --+ +-- FP points here (**)
924 // somewhere on
925 // this side of FP/LR
926 //
927 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
928 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
929
930 // The lowering assumes that FP/LR is present, and so the offsets of
931 // the formal arguments start at 8. If FP/LR is not there we need to
932 // reduce the offset by 8.
933 if (Offset > 0 && !HasFP)
934 Offset -= 8;
935
936 if (UseFP)
937 FrameReg = FP;
938 else if (UseAP)
939 FrameReg = AP;
940 else
941 FrameReg = SP;
942
943 // Calculate the actual offset in the instruction. If there is no FP
944 // (in other words, no allocframe), then SP will not be adjusted (i.e.
945 // there will be no SP -= FrameSize), so the frame size should not be
946 // added to the calculated offset.
947 int RealOffset = Offset;
948 if (!UseFP && !UseAP && HasFP)
949 RealOffset = FrameSize+Offset;
950 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000951}
952
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000953
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000954bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000955 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
956 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000957 if (CSI.empty())
958 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000959
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000960 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000961 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000962 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000963 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000964
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000965 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000966 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000967 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000968 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
969 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
970 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000971 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
972 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
973
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000974 // Call spill function.
975 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000976 unsigned SpillOpc;
977 if (StkOvrFlowEnabled)
978 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
979 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
980 else
981 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
982 : Hexagon::SAVE_REGISTERS_CALL_V4;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000983
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000984 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000985 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000986 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000987 // Add callee-saved registers as use.
988 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
989 // Add live in registers.
990 for (unsigned I = 0; I < CSI.size(); ++I)
991 MBB.addLiveIn(CSI[I].getReg());
992 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000993 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000994
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000995 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000996 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000997 // Add live in registers. We treat eh_return callee saved register r0 - r3
998 // specially. They are not really callee saved registers as they are not
999 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001000 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1001 int FI = CSI[i].getFrameIdx();
1002 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001003 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001004 if (IsKill)
1005 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001006 }
1007 return true;
1008}
1009
1010
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001011bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1012 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1013 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001014 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001015
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001016 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1017 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001018 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001019
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001020 if (useRestoreFunction(MF, CSI)) {
1021 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1022 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1023 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1024 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001025 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1026 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001027
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001028 // Call spill function.
1029 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1030 : MBB.getLastNonDebugInstr()->getDebugLoc();
1031 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001032
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001033 if (HasTC) {
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001034 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1035 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001036 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001037 .addExternalSymbol(RestoreFn);
1038 } else {
1039 // The block has a return.
1040 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1041 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001042 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1043 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001044 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001045 .addExternalSymbol(RestoreFn);
1046 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001047 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001048 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001049 addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
1050 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001051 }
1052
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001053 for (unsigned i = 0; i < CSI.size(); ++i) {
1054 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001055 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1056 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001057 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001058 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001059
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001060 return true;
1061}
1062
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001063
1064void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1065 MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001066 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001067 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001068 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001069 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1070 "Cannot handle this call frame pseudo instruction");
Eli Bendersky8da87162013-02-21 20:05:00 +00001071 MBB.erase(I);
1072}
1073
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001074
1075void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1076 MachineFunction &MF, RegScavenger *RS) const {
1077 // If this function has uses aligned stack and also has variable sized stack
1078 // objects, then we need to map all spill slots to fixed positions, so that
1079 // they can be accessed through FP. Otherwise they would have to be accessed
1080 // via AP, which may not be available at the particular place in the program.
1081 MachineFrameInfo *MFI = MF.getFrameInfo();
1082 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001083 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001084
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001085 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001086 return;
1087
1088 unsigned LFS = MFI->getLocalFrameSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001089 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1090 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1091 continue;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001092 unsigned S = MFI->getObjectSize(i);
1093 // Reduce the alignment to at most 8. This will require unaligned vector
1094 // stores if they happen here.
1095 unsigned A = std::max(MFI->getObjectAlignment(i), 8U);
1096 MFI->setObjectAlignment(i, 8);
1097 LFS = alignTo(LFS+S, A);
1098 MFI->mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001099 }
1100
1101 MFI->setLocalFrameSize(LFS);
1102 unsigned A = MFI->getLocalFrameMaxAlign();
1103 assert(A <= 8 && "Unexpected local frame alignment");
1104 if (A == 0)
1105 MFI->setLocalFrameMaxAlign(8);
1106 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001107
1108 // Set the physical aligned-stack base address register.
1109 unsigned AP = 0;
1110 if (const MachineInstr *AI = getAlignaInstr(MF))
1111 AP = AI->getOperand(0).getReg();
1112 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1113 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001114}
1115
1116/// Returns true if there is no caller saved registers available.
1117static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1118 const HexagonRegisterInfo &HRI) {
1119 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001120 BitVector Reserved = HRI.getReservedRegs(MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001121
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001122 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1123 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1124 if (MRI.isPhysRegUsed(*AI))
1125 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001126 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001127 };
1128
1129 // Check for an unused caller-saved register.
1130 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF); *P; ++P)
1131 if (!IsUsed(*P))
1132 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001133 // All caller-saved registers are used.
1134 return true;
1135}
1136
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001137
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001138#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001139static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001140 dbgs() << '{';
1141 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1142 unsigned R = x;
1143 dbgs() << ' ' << PrintReg(R, &TRI);
1144 }
1145 dbgs() << " }";
1146}
1147#endif
1148
1149
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001150bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1151 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001152 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001153 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001154 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001155 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001156
1157 // Generate a set of unique, callee-saved registers (SRegs), where each
1158 // register in the set is maximal in terms of sub-/super-register relation,
1159 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1160
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001161 // (1) For each callee-saved register, add that register and all of its
1162 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001163 DEBUG(dbgs() << "Initial CS registers: {");
1164 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1165 unsigned R = CSI[i].getReg();
1166 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1167 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1168 SRegs[*SR] = true;
1169 }
1170 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001171 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001172
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001173 // (2) For each reserved register, remove that register and all of its
1174 // sub- and super-registers from SRegs.
1175 BitVector Reserved = TRI->getReservedRegs(MF);
1176 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1177 unsigned R = x;
1178 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1179 SRegs[*SR] = false;
1180 }
1181 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1182 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1183
1184 // (3) Collect all registers that have at least one sub-register in SRegs,
1185 // and also have no sub-registers that are reserved. These will be the can-
1186 // didates for saving as a whole instead of their individual sub-registers.
1187 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1188 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001189 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1190 unsigned R = x;
1191 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1192 TmpSup[*SR] = true;
1193 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001194 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1195 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001196 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1197 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001198 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001199 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001200 break;
1201 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001202 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001203 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001204
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001205 // (4) Include all super-registers found in (3) into SRegs.
1206 SRegs |= TmpSup;
1207 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001208
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001209 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001210 // remove R from SRegs.
1211 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1212 unsigned R = x;
1213 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1214 if (!SRegs[*SR])
1215 continue;
1216 SRegs[R] = false;
1217 break;
1218 }
1219 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001220 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001221
1222 // Now, for each register that has a fixed stack slot, create the stack
1223 // object for it.
1224 CSI.clear();
1225
1226 typedef TargetFrameLowering::SpillSlot SpillSlot;
1227 unsigned NumFixed;
1228 int MinOffset = 0; // CS offsets are negative.
1229 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1230 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1231 if (!SRegs[S->Reg])
1232 continue;
1233 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1234 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1235 MinOffset = std::min(MinOffset, S->Offset);
1236 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1237 SRegs[S->Reg] = false;
1238 }
1239
1240 // There can be some registers that don't have fixed slots. For example,
1241 // we need to store R0-R3 in functions with exception handling. For each
1242 // such register, create a non-fixed stack object.
1243 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1244 unsigned R = x;
1245 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1246 int Off = MinOffset - RC->getSize();
1247 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1248 assert(isPowerOf2_32(Align));
1249 Off &= -Align;
1250 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1251 MinOffset = std::min(MinOffset, Off);
1252 CSI.push_back(CalleeSavedInfo(R, FI));
1253 SRegs[R] = false;
1254 }
1255
1256 DEBUG({
1257 dbgs() << "CS information: {";
1258 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1259 int FI = CSI[i].getFrameIdx();
1260 int Off = MFI->getObjectOffset(FI);
1261 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1262 if (Off >= 0)
1263 dbgs() << '+';
1264 dbgs() << Off;
1265 }
1266 dbgs() << " }\n";
1267 });
1268
1269#ifndef NDEBUG
1270 // Verify that all registers were handled.
1271 bool MissedReg = false;
1272 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1273 unsigned R = x;
1274 dbgs() << PrintReg(R, TRI) << ' ';
1275 MissedReg = true;
1276 }
1277 if (MissedReg)
1278 llvm_unreachable("...there are unhandled callee-saved registers!");
1279#endif
1280
1281 return true;
1282}
1283
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001284
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001285bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1286 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1287 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1288 MachineInstr *MI = &*It;
1289 DebugLoc DL = MI->getDebugLoc();
1290 unsigned DstR = MI->getOperand(0).getReg();
1291 unsigned SrcR = MI->getOperand(1).getReg();
1292 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1293 !Hexagon::ModRegsRegClass.contains(SrcR))
1294 return false;
1295
1296 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1297 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1298 .addOperand(MI->getOperand(1));
1299 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1300 .addReg(TmpR, RegState::Kill);
1301
1302 NewRegs.push_back(TmpR);
1303 B.erase(It);
1304 return true;
1305}
1306
1307bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1308 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1309 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1310 MachineInstr *MI = &*It;
1311 DebugLoc DL = MI->getDebugLoc();
1312 unsigned Opc = MI->getOpcode();
1313 unsigned SrcR = MI->getOperand(2).getReg();
1314 bool IsKill = MI->getOperand(2).isKill();
1315
1316 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1317 int FI = MI->getOperand(0).getIndex();
1318
1319 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1320 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1321 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1322 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1323 : Hexagon::A2_tfrcrr;
1324 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1325 .addReg(SrcR, getKillRegState(IsKill));
1326
1327 // S2_storeri_io FI, 0, TmpR
1328 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1329 .addFrameIndex(FI)
1330 .addImm(0)
1331 .addReg(TmpR, RegState::Kill)
1332 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1333
1334 NewRegs.push_back(TmpR);
1335 B.erase(It);
1336 return true;
1337}
1338
1339bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1340 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1341 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1342 MachineInstr *MI = &*It;
1343 DebugLoc DL = MI->getDebugLoc();
1344 unsigned Opc = MI->getOpcode();
1345 unsigned DstR = MI->getOperand(0).getReg();
1346
1347 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1348 int FI = MI->getOperand(1).getIndex();
1349
1350 // TmpR = L2_loadri_io FI, 0
1351 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1352 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1353 .addFrameIndex(FI)
1354 .addImm(0)
1355 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1356
1357 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1358 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1359 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1360 : Hexagon::A2_tfrrcr;
1361 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1362 .addReg(TmpR, RegState::Kill);
1363
1364 NewRegs.push_back(TmpR);
1365 B.erase(It);
1366 return true;
1367}
1368
1369
1370bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1371 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1372 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1373 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1374 MachineInstr *MI = &*It;
1375 DebugLoc DL = MI->getDebugLoc();
1376 unsigned SrcR = MI->getOperand(2).getReg();
1377 bool IsKill = MI->getOperand(2).isKill();
1378
1379 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1380 int FI = MI->getOperand(0).getIndex();
1381
1382 bool Is128B = HST.useHVXDblOps();
1383 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1384 : &Hexagon::VectorRegs128BRegClass;
1385
1386 // Insert transfer to general vector register.
1387 // TmpR0 = A2_tfrsi 0x01010101
1388 // TmpR1 = V6_vandqrt Qx, TmpR0
1389 // store FI, 0, TmpR1
1390 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1391 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1392
1393 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1394 .addImm(0x01010101);
1395
1396 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1397 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1398 .addReg(SrcR, getKillRegState(IsKill))
1399 .addReg(TmpR0, RegState::Kill);
1400
1401 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1402 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1403 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1404
1405 NewRegs.push_back(TmpR0);
1406 NewRegs.push_back(TmpR1);
1407 B.erase(It);
1408 return true;
1409}
1410
1411bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1412 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1413 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1414 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1415 MachineInstr *MI = &*It;
1416 DebugLoc DL = MI->getDebugLoc();
1417 unsigned DstR = MI->getOperand(0).getReg();
1418
1419 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1420 int FI = MI->getOperand(1).getIndex();
1421
1422 bool Is128B = HST.useHVXDblOps();
1423 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1424 : &Hexagon::VectorRegs128BRegClass;
1425
1426 // TmpR0 = A2_tfrsi 0x01010101
1427 // TmpR1 = load FI, 0
1428 // DstR = V6_vandvrt TmpR1, TmpR0
1429 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1430 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1431
1432 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1433 .addImm(0x01010101);
1434 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1435 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1436 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1437
1438 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1439 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1440 .addReg(TmpR1, RegState::Kill)
1441 .addReg(TmpR0, RegState::Kill);
1442
1443 NewRegs.push_back(TmpR0);
1444 NewRegs.push_back(TmpR1);
1445 B.erase(It);
1446 return true;
1447}
1448
1449bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1450 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1451 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1452 MachineFunction &MF = *B.getParent();
1453 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1454 auto &MFI = *MF.getFrameInfo();
1455 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1456 MachineInstr *MI = &*It;
1457 DebugLoc DL = MI->getDebugLoc();
1458
1459 unsigned SrcR = MI->getOperand(2).getReg();
1460 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1461 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1462 bool IsKill = MI->getOperand(2).isKill();
1463
1464 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1465 int FI = MI->getOperand(0).getIndex();
1466
1467 bool Is128B = HST.useHVXDblOps();
1468 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1469 : &Hexagon::VectorRegs128BRegClass;
1470 unsigned Size = RC->getSize();
1471 unsigned NeedAlign = RC->getAlignment();
1472 unsigned HasAlign = MFI.getObjectAlignment(FI);
1473 unsigned StoreOpc;
1474
1475 // Store low part.
1476 if (NeedAlign <= HasAlign)
1477 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1478 else
1479 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1480
1481 BuildMI(B, It, DL, HII.get(StoreOpc))
1482 .addFrameIndex(FI)
1483 .addImm(0)
1484 .addReg(SrcLo, getKillRegState(IsKill))
1485 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1486
1487 // Load high part.
1488 if (NeedAlign <= MinAlign(HasAlign, Size))
1489 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1490 else
1491 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1492
1493 BuildMI(B, It, DL, HII.get(StoreOpc))
1494 .addFrameIndex(FI)
1495 .addImm(Size)
1496 .addReg(SrcHi, getKillRegState(IsKill))
1497 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1498
1499 B.erase(It);
1500 return true;
1501}
1502
1503bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1504 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1505 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1506 MachineFunction &MF = *B.getParent();
1507 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1508 auto &MFI = *MF.getFrameInfo();
1509 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1510 MachineInstr *MI = &*It;
1511 DebugLoc DL = MI->getDebugLoc();
1512
1513 unsigned DstR = MI->getOperand(0).getReg();
1514 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1515 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1516
1517 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1518 int FI = MI->getOperand(1).getIndex();
1519
1520 bool Is128B = HST.useHVXDblOps();
1521 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1522 : &Hexagon::VectorRegs128BRegClass;
1523 unsigned Size = RC->getSize();
1524 unsigned NeedAlign = RC->getAlignment();
1525 unsigned HasAlign = MFI.getObjectAlignment(FI);
1526 unsigned LoadOpc;
1527
1528 // Load low part.
1529 if (NeedAlign <= HasAlign)
1530 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1531 else
1532 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1533
1534 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1535 .addFrameIndex(FI)
1536 .addImm(0)
1537 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1538
1539 // Load high part.
1540 if (NeedAlign <= MinAlign(HasAlign, Size))
1541 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1542 else
1543 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1544
1545 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1546 .addFrameIndex(FI)
1547 .addImm(Size)
1548 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1549
1550 B.erase(It);
1551 return true;
1552}
1553
1554bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1555 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1556 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1557 MachineFunction &MF = *B.getParent();
1558 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1559 auto &MFI = *MF.getFrameInfo();
1560 MachineInstr *MI = &*It;
1561 DebugLoc DL = MI->getDebugLoc();
1562
1563 unsigned SrcR = MI->getOperand(2).getReg();
1564 bool IsKill = MI->getOperand(2).isKill();
1565
1566 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1567 int FI = MI->getOperand(0).getIndex();
1568
1569 bool Is128B = HST.useHVXDblOps();
1570 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1571 : &Hexagon::VectorRegs128BRegClass;
1572
1573 unsigned NeedAlign = RC->getAlignment();
1574 unsigned HasAlign = MFI.getObjectAlignment(FI);
1575 unsigned StoreOpc;
1576
1577 if (NeedAlign <= HasAlign)
1578 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1579 else
1580 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1581
1582 BuildMI(B, It, DL, HII.get(StoreOpc))
1583 .addFrameIndex(FI)
1584 .addImm(0)
1585 .addReg(SrcR, getKillRegState(IsKill))
1586 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1587
1588 B.erase(It);
1589 return true;
1590}
1591
1592bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1593 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1594 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1595 MachineFunction &MF = *B.getParent();
1596 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1597 auto &MFI = *MF.getFrameInfo();
1598 MachineInstr *MI = &*It;
1599 DebugLoc DL = MI->getDebugLoc();
1600
1601 unsigned DstR = MI->getOperand(0).getReg();
1602
1603 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1604 int FI = MI->getOperand(1).getIndex();
1605
1606 bool Is128B = HST.useHVXDblOps();
1607 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1608 : &Hexagon::VectorRegs128BRegClass;
1609
1610 unsigned NeedAlign = RC->getAlignment();
1611 unsigned HasAlign = MFI.getObjectAlignment(FI);
1612 unsigned LoadOpc;
1613
1614 if (NeedAlign <= HasAlign)
1615 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1616 else
1617 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1618
1619 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1620 .addFrameIndex(FI)
1621 .addImm(0)
1622 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1623
1624 B.erase(It);
1625 return true;
1626}
1627
1628
1629bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1630 SmallVectorImpl<unsigned> &NewRegs) const {
1631 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001632 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001633 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001634 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001635
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001636 for (auto &B : MF) {
1637 // Traverse the basic block.
1638 MachineBasicBlock::iterator NextI;
1639 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1640 MachineInstr *MI = &*I;
1641 NextI = std::next(I);
1642 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001643
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001644 switch (Opc) {
1645 case TargetOpcode::COPY:
1646 Changed = expandCopy(B, I, MRI, HII, NewRegs);
1647 break;
1648 case Hexagon::STriw_pred:
1649 case Hexagon::STriw_mod:
1650 Changed = expandStoreInt(B, I, MRI, HII, NewRegs);
1651 break;
1652 case Hexagon::LDriw_pred:
1653 case Hexagon::LDriw_mod:
1654 Changed = expandLoadInt(B, I, MRI, HII, NewRegs);
1655 break;
1656 case Hexagon::STriq_pred_V6:
1657 case Hexagon::STriq_pred_V6_128B:
1658 Changed = expandStoreVecPred(B, I, MRI, HII, NewRegs);
1659 break;
1660 case Hexagon::LDriq_pred_V6:
1661 case Hexagon::LDriq_pred_V6_128B:
1662 Changed = expandLoadVecPred(B, I, MRI, HII, NewRegs);
1663 break;
1664 case Hexagon::LDrivv_pseudo_V6:
1665 case Hexagon::LDrivv_pseudo_V6_128B:
1666 Changed = expandLoadVec2(B, I, MRI, HII, NewRegs);
1667 break;
1668 case Hexagon::STrivv_pseudo_V6:
1669 case Hexagon::STrivv_pseudo_V6_128B:
1670 Changed = expandStoreVec2(B, I, MRI, HII, NewRegs);
1671 break;
1672 case Hexagon::STriv_pseudo_V6:
1673 case Hexagon::STriv_pseudo_V6_128B:
1674 Changed = expandStoreVec(B, I, MRI, HII, NewRegs);
1675 break;
1676 case Hexagon::LDriv_pseudo_V6:
1677 case Hexagon::LDriv_pseudo_V6_128B:
1678 Changed = expandLoadVec(B, I, MRI, HII, NewRegs);
1679 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001680 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001681 }
1682 }
1683
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001684 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001685}
1686
1687
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001688void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1689 BitVector &SavedRegs,
1690 RegScavenger *RS) const {
1691 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1692 auto &HRI = *HST.getRegisterInfo();
1693
1694 SavedRegs.resize(HRI.getNumRegs());
1695
1696 // If we have a function containing __builtin_eh_return we want to spill and
1697 // restore all callee saved registers. Pretend that they are used.
1698 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1699 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1700 SavedRegs.set(*R);
1701
1702 // Replace predicate register pseudo spill code.
1703 SmallVector<unsigned,8> NewRegs;
1704 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001705 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001706 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001707
1708 // We need to reserve a a spill slot if scavenging could potentially require
1709 // spilling a scavenged register.
1710 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1711 MachineRegisterInfo &MRI = MF.getRegInfo();
1712 SetVector<const TargetRegisterClass*> SpillRCs;
1713 for (unsigned VR : NewRegs)
1714 SpillRCs.insert(MRI.getRegClass(VR));
1715
1716 MachineFrameInfo &MFI = *MF.getFrameInfo();
1717 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1718 if (SpillRCs.count(&IntRC)) {
1719 for (int i = 0; i < NumberScavengerSlots; i++) {
1720 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1721 IntRC.getAlignment());
1722 RS->addScavengingFrameIndex(NewFI);
1723 }
1724 }
1725 for (auto *RC : SpillRCs) {
1726 if (RC == &IntRC)
1727 continue;
1728 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1729 RS->addScavengingFrameIndex(NewFI);
1730 }
1731 }
1732
1733 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1734}
1735
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001736
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001737unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1738 HexagonBlockRanges::IndexRange &FIR,
1739 HexagonBlockRanges::InstrIndexMap &IndexMap,
1740 HexagonBlockRanges::RegToRangeMap &DeadMap,
1741 const TargetRegisterClass *RC) const {
1742 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1743 auto &MRI = MF.getRegInfo();
1744
1745 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1746 auto F = DeadMap.find({Reg,0});
1747 if (F == DeadMap.end())
1748 return false;
1749 for (auto &DR : F->second)
1750 if (DR.contains(FIR))
1751 return true;
1752 return false;
1753 };
1754
1755 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1756 bool Dead = true;
1757 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1758 if (isDead(R.Reg))
1759 continue;
1760 Dead = false;
1761 break;
1762 }
1763 if (Dead)
1764 return Reg;
1765 }
1766 return 0;
1767}
1768
1769void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1770 SmallVectorImpl<unsigned> &VRegs) const {
1771 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1772 auto &HII = *HST.getInstrInfo();
1773 auto &HRI = *HST.getRegisterInfo();
1774 auto &MRI = MF.getRegInfo();
1775 HexagonBlockRanges HBR(MF);
1776
1777 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1778 BlockIndexMap;
1779 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1780 BlockRangeMap;
1781 typedef HexagonBlockRanges::IndexType IndexType;
1782
1783 struct SlotInfo {
1784 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001785 unsigned Size;
1786 const TargetRegisterClass *RC;
1787
1788 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001789 };
1790
1791 BlockIndexMap BlockIndexes;
1792 SmallSet<int,4> BadFIs;
1793 std::map<int,SlotInfo> FIRangeMap;
1794
1795 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1796 -> const TargetRegisterClass* {
1797 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1798 assert(R.Sub == 0);
1799 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1800 auto *RCR = MRI.getRegClass(R.Reg);
1801 if (R.Sub == 0)
1802 return RCR;
1803 unsigned PR = *RCR->begin();
1804 R.Reg = HRI.getSubReg(PR, R.Sub);
1805 }
1806 return HRI.getMinimalPhysRegClass(R.Reg);
1807 };
1808 // Accumulate register classes: get a common class for a pre-existing
1809 // class HaveRC and a new class NewRC. Return nullptr if a common class
1810 // cannot be found, otherwise return the resulting class. If HaveRC is
1811 // nullptr, assume that it is still unset.
1812 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1813 const TargetRegisterClass *NewRC)
1814 -> const TargetRegisterClass* {
1815 if (HaveRC == nullptr || HaveRC == NewRC)
1816 return NewRC;
1817 // Different classes, both non-null. Pick the more general one.
1818 if (HaveRC->hasSubClassEq(NewRC))
1819 return HaveRC;
1820 if (NewRC->hasSubClassEq(HaveRC))
1821 return NewRC;
1822 return nullptr;
1823 };
1824
1825 // Scan all blocks in the function. Check all occurrences of frame indexes,
1826 // and collect relevant information.
1827 for (auto &B : MF) {
1828 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001829 // Emplace appears not to be supported in gcc 4.7.2-4.
1830 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001831 auto P = BlockIndexes.insert(
1832 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001833 auto &IndexMap = P.first->second;
1834 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1835 << IndexMap << '\n');
1836
1837 for (auto &In : B) {
1838 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001839 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1840 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001841 if (Load && Store) {
1842 // If it's both a load and a store, then we won't handle it.
1843 BadFIs.insert(LFI);
1844 BadFIs.insert(SFI);
1845 continue;
1846 }
1847 // Check for register classes of the register used as the source for
1848 // the store, and the register used as the destination for the load.
1849 // Also, only accept base+imm_offset addressing modes. Other addressing
1850 // modes can have side-effects (post-increments, etc.). For stack
1851 // slots they are very unlikely, so there is not much loss due to
1852 // this restriction.
1853 if (Load || Store) {
1854 int TFI = Load ? LFI : SFI;
1855 unsigned AM = HII.getAddrMode(&In);
1856 SlotInfo &SI = FIRangeMap[TFI];
1857 bool Bad = (AM != HexagonII::BaseImmOffset);
1858 if (!Bad) {
1859 // If the addressing mode is ok, check the register class.
1860 const TargetRegisterClass *RC = nullptr;
1861 if (Load) {
1862 MachineOperand &DataOp = In.getOperand(0);
1863 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1864 } else {
1865 MachineOperand &DataOp = In.getOperand(2);
1866 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1867 }
1868 RC = getCommonRC(SI.RC, RC);
1869 if (RC == nullptr)
1870 Bad = true;
1871 else
1872 SI.RC = RC;
1873 }
1874 if (!Bad) {
1875 // Check sizes.
1876 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1877 if (SI.Size != 0 && SI.Size != S)
1878 Bad = true;
1879 else
1880 SI.Size = S;
1881 }
1882 if (Bad)
1883 BadFIs.insert(TFI);
1884 }
1885
1886 // Locate uses of frame indices.
1887 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1888 const MachineOperand &Op = In.getOperand(i);
1889 if (!Op.isFI())
1890 continue;
1891 int FI = Op.getIndex();
1892 // Make sure that the following operand is an immediate and that
1893 // it is 0. This is the offset in the stack object.
1894 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1895 In.getOperand(i+1).getImm() != 0)
1896 BadFIs.insert(FI);
1897 if (BadFIs.count(FI))
1898 continue;
1899
1900 IndexType Index = IndexMap.getIndex(&In);
1901 if (Load) {
1902 if (LastStore[FI] == IndexType::None)
1903 LastStore[FI] = IndexType::Entry;
1904 LastLoad[FI] = Index;
1905 } else if (Store) {
1906 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1907 if (LastStore[FI] != IndexType::None)
1908 RL.add(LastStore[FI], LastLoad[FI], false, false);
1909 else if (LastLoad[FI] != IndexType::None)
1910 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1911 LastLoad[FI] = IndexType::None;
1912 LastStore[FI] = Index;
1913 } else {
1914 BadFIs.insert(FI);
1915 }
1916 }
1917 }
1918
1919 for (auto &I : LastLoad) {
1920 IndexType LL = I.second;
1921 if (LL == IndexType::None)
1922 continue;
1923 auto &RL = FIRangeMap[I.first].Map[&B];
1924 IndexType &LS = LastStore[I.first];
1925 if (LS != IndexType::None)
1926 RL.add(LS, LL, false, false);
1927 else
1928 RL.add(IndexType::Entry, LL, false, false);
1929 LS = IndexType::None;
1930 }
1931 for (auto &I : LastStore) {
1932 IndexType LS = I.second;
1933 if (LS == IndexType::None)
1934 continue;
1935 auto &RL = FIRangeMap[I.first].Map[&B];
1936 RL.add(LS, IndexType::None, false, false);
1937 }
1938 }
1939
1940 DEBUG({
1941 for (auto &P : FIRangeMap) {
1942 dbgs() << "fi#" << P.first;
1943 if (BadFIs.count(P.first))
1944 dbgs() << " (bad)";
1945 dbgs() << " RC: ";
1946 if (P.second.RC != nullptr)
1947 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1948 else
1949 dbgs() << "<null>\n";
1950 for (auto &R : P.second.Map)
1951 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1952 }
1953 });
1954
1955 // When a slot is loaded from in a block without being stored to in the
1956 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1957 // consider this slot to be live-on-exit from all blocks.
1958 SmallSet<int,4> LoxFIs;
1959
1960 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1961
1962 for (auto &P : FIRangeMap) {
1963 // P = pair(FI, map: BB->RangeList)
1964 if (BadFIs.count(P.first))
1965 continue;
1966 for (auto &B : MF) {
1967 auto F = P.second.Map.find(&B);
1968 // F = pair(BB, RangeList)
1969 if (F == P.second.Map.end() || F->second.empty())
1970 continue;
1971 HexagonBlockRanges::IndexRange &IR = F->second.front();
1972 if (IR.start() == IndexType::Entry)
1973 LoxFIs.insert(P.first);
1974 BlockFIMap[&B].push_back(P.first);
1975 }
1976 }
1977
1978 DEBUG({
1979 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1980 for (auto &P : BlockFIMap) {
1981 auto &FIs = P.second;
1982 if (FIs.empty())
1983 continue;
1984 dbgs() << " BB#" << P.first->getNumber() << ": {";
1985 for (auto I : FIs) {
1986 dbgs() << " fi#" << I;
1987 if (LoxFIs.count(I))
1988 dbgs() << '*';
1989 }
1990 dbgs() << " }\n";
1991 }
1992 });
1993
1994 // eliminate loads, when all loads eliminated, eliminate all stores.
1995 for (auto &B : MF) {
1996 auto F = BlockIndexes.find(&B);
1997 assert(F != BlockIndexes.end());
1998 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1999 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2000 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2001 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2002 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2003
2004 for (auto FI : BlockFIMap[&B]) {
2005 if (BadFIs.count(FI))
2006 continue;
2007 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2008 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2009 for (auto &Range : RL) {
2010 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2011 if (!IndexType::isInstr(Range.start()) ||
2012 !IndexType::isInstr(Range.end()))
2013 continue;
2014 MachineInstr *SI = IM.getInstr(Range.start());
2015 MachineInstr *EI = IM.getInstr(Range.end());
2016 assert(SI->mayStore() && "Unexpected start instruction");
2017 assert(EI->mayLoad() && "Unexpected end instruction");
2018 MachineOperand &SrcOp = SI->getOperand(2);
2019
2020 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2021 SrcOp.getSubReg() };
2022 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
2023 // The this-> is needed to unconfuse MSVC.
2024 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2025 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2026 if (FoundR == 0)
2027 continue;
2028
2029 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2030 MachineBasicBlock::iterator StartIt = SI, NextIt;
2031 MachineInstr *CopyIn = nullptr;
2032 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2033 DebugLoc DL = SI->getDebugLoc();
2034 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2035 .addOperand(SrcOp);
2036 }
2037
2038 ++StartIt;
2039 // Check if this is a last store and the FI is live-on-exit.
2040 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2041 // Update store's source register.
2042 if (unsigned SR = SrcOp.getSubReg())
2043 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2044 else
2045 SrcOp.setReg(FoundR);
2046 SrcOp.setSubReg(0);
2047 // We are keeping this register live.
2048 SrcOp.setIsKill(false);
2049 } else {
2050 B.erase(SI);
2051 IM.replaceInstr(SI, CopyIn);
2052 }
2053
2054 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2055 for (auto It = StartIt; It != EndIt; It = NextIt) {
2056 MachineInstr *MI = &*It;
2057 NextIt = std::next(It);
2058 int TFI;
2059 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2060 continue;
2061 unsigned DstR = MI->getOperand(0).getReg();
2062 assert(MI->getOperand(0).getSubReg() == 0);
2063 MachineInstr *CopyOut = nullptr;
2064 if (DstR != FoundR) {
2065 DebugLoc DL = MI->getDebugLoc();
2066 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2067 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2068 unsigned CopyOpc = TargetOpcode::COPY;
2069 if (HII.isSignExtendingLoad(MI))
2070 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2071 else if (HII.isZeroExtendingLoad(MI))
2072 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2073 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2074 .addReg(FoundR, getKillRegState(MI == EI));
2075 }
2076 IM.replaceInstr(MI, CopyOut);
2077 B.erase(It);
2078 }
2079
2080 // Update the dead map.
2081 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2082 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2083 DM[RR].subtract(Range);
2084 } // for Range in range list
2085 }
2086 }
2087}
2088
2089
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002090void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002091 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002092 MachineBasicBlock &MB = *AI->getParent();
2093 DebugLoc DL = AI->getDebugLoc();
2094 unsigned A = AI->getOperand(2).getImm();
2095
2096 // Have
2097 // Rd = alloca Rs, #A
2098 //
2099 // If Rs and Rd are different registers, use this sequence:
2100 // Rd = sub(r29, Rs)
2101 // r29 = sub(r29, Rs)
2102 // Rd = and(Rd, #-A) ; if necessary
2103 // r29 = and(r29, #-A) ; if necessary
2104 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2105 // otherwise, do
2106 // Rd = sub(r29, Rs)
2107 // Rd = and(Rd, #-A) ; if necessary
2108 // r29 = Rd
2109 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2110
2111 MachineOperand &RdOp = AI->getOperand(0);
2112 MachineOperand &RsOp = AI->getOperand(1);
2113 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2114
2115 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002116 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002117 .addReg(SP)
2118 .addReg(Rs);
2119 if (Rs != Rd) {
2120 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002121 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002122 .addReg(SP)
2123 .addReg(Rs);
2124 }
2125 if (A > 8) {
2126 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002127 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002128 .addReg(Rd)
2129 .addImm(-int64_t(A));
2130 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002131 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002132 .addReg(SP)
2133 .addImm(-int64_t(A));
2134 }
2135 if (Rs == Rd) {
2136 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002137 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002138 .addReg(Rd);
2139 }
2140 if (CF > 0) {
2141 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002142 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002143 .addReg(Rd)
2144 .addImm(CF);
2145 }
2146}
2147
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002148
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002149bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2150 const MachineFrameInfo *MFI = MF.getFrameInfo();
2151 if (!MFI->hasVarSizedObjects())
2152 return false;
2153 unsigned MaxA = MFI->getMaxAlignment();
2154 if (MaxA <= getStackAlignment())
2155 return false;
2156 return true;
2157}
2158
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002159
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002160const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2161 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002162 for (auto &B : MF)
2163 for (auto &I : B)
2164 if (I.getOpcode() == Hexagon::ALIGNA)
2165 return &I;
2166 return nullptr;
2167}
2168
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002169
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002170/// Determine whether the callee-saved register saves and restores should
2171/// be generated via inline code. If this function returns "true", inline
2172/// code will be generated. If this function returns "false", additional
2173/// checks are performed, which may still lead to the inline code.
2174bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2175 const CSIVect &CSI) const {
2176 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2177 return true;
2178 if (!isOptSize(MF) && !isMinSize(MF))
2179 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2180 return true;
2181
2182 // Check if CSI only has double registers, and if the registers form
2183 // a contiguous block starting from D8.
2184 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2185 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2186 unsigned R = CSI[i].getReg();
2187 if (!Hexagon::DoubleRegsRegClass.contains(R))
2188 return true;
2189 Regs[R] = true;
2190 }
2191 int F = Regs.find_first();
2192 if (F != Hexagon::D8)
2193 return true;
2194 while (F >= 0) {
2195 int N = Regs.find_next(F);
2196 if (N >= 0 && N != F+1)
2197 return true;
2198 F = N;
2199 }
2200
2201 return false;
2202}
2203
2204
2205bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2206 const CSIVect &CSI) const {
2207 if (shouldInlineCSR(MF, CSI))
2208 return false;
2209 unsigned NumCSI = CSI.size();
2210 if (NumCSI <= 1)
2211 return false;
2212
2213 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2214 : SpillFuncThreshold;
2215 return Threshold < NumCSI;
2216}
2217
2218
2219bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2220 const CSIVect &CSI) const {
2221 if (shouldInlineCSR(MF, CSI))
2222 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002223 // The restore functions do a bit more than just restoring registers.
2224 // The non-returning versions will go back directly to the caller's
2225 // caller, others will clean up the stack frame in preparation for
2226 // a tail call. Using them can still save code size even if only one
2227 // register is getting restores. Make the decision based on -Oz:
2228 // using -Os will use inline restore for a single register.
2229 if (isMinSize(MF))
2230 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002231 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002232 if (NumCSI <= 1)
2233 return false;
2234
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002235 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2236 : SpillFuncThreshold;
2237 return Threshold < NumCSI;
2238}