blob: 6ad82e8c21fe229e3fb660631f4ded8cfd31bf16 [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 Parzyszek876a19d2015-04-23 16:05:39 +0000140static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
141 cl::init(true), cl::Hidden, cl::ZeroOrMore,
142 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000144static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
145 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
146 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000148static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
149 cl::Hidden, cl::desc("Use allocframe more conservatively"));
150
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000151static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
152 cl::init(true), cl::desc("Optimize spill slots"));
153
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000154
155namespace llvm {
156 void initializeHexagonCallFrameInformationPass(PassRegistry&);
157 FunctionPass *createHexagonCallFrameInformation();
158}
159
160namespace {
161 class HexagonCallFrameInformation : public MachineFunctionPass {
162 public:
163 static char ID;
164 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
165 PassRegistry &PR = *PassRegistry::getPassRegistry();
166 initializeHexagonCallFrameInformationPass(PR);
167 }
168 bool runOnMachineFunction(MachineFunction &MF) override;
169 };
170
171 char HexagonCallFrameInformation::ID = 0;
172}
173
174bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
175 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
176 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
177 MF.getFunction()->needsUnwindTableEntry();
178
179 if (!NeedCFI)
180 return false;
181 HFI.insertCFIInstructions(MF);
182 return true;
183}
184
185INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
186 "Hexagon call frame information", false, false)
187
188FunctionPass *llvm::createHexagonCallFrameInformation() {
189 return new HexagonCallFrameInformation();
190}
191
192
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000193namespace {
194 /// Map a register pair Reg to the subregister that has the greater "number",
195 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
196 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
197 bool hireg = true) {
198 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
199 return Reg;
200
201 unsigned RegNo = 0;
202 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
203 if (hireg) {
204 if (*SubRegs > RegNo)
205 RegNo = *SubRegs;
206 } else {
207 if (!RegNo || *SubRegs < RegNo)
208 RegNo = *SubRegs;
209 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000210 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000211 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000212 }
213
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000214 /// Returns the callee saved register with the largest id in the vector.
215 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
216 const TargetRegisterInfo &TRI) {
217 assert(Hexagon::R1 > 0 &&
218 "Assume physical registers are encoded as positive integers");
219 if (CSI.empty())
220 return 0;
221
222 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
223 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
224 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
225 if (Reg > Max)
226 Max = Reg;
227 }
228 return Max;
229 }
230
231 /// Checks if the basic block contains any instruction that needs a stack
232 /// frame to be already in place.
233 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR) {
234 for (auto &I : MBB) {
235 const MachineInstr *MI = &I;
236 if (MI->isCall())
237 return true;
238 unsigned Opc = MI->getOpcode();
239 switch (Opc) {
240 case Hexagon::ALLOCA:
241 case Hexagon::ALIGNA:
242 return true;
243 default:
244 break;
245 }
246 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000247 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000248 // While the presence of a frame index does not prove that a stack
249 // frame will be required, all frame indexes should be within alloc-
250 // frame/deallocframe. Otherwise, the code that translates a frame
251 // index into an offset would have to be aware of the placement of
252 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000253 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000254 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000255 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000256 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000257 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000258 // Virtual registers will need scavenging, which then may require
259 // a stack slot.
260 if (TargetRegisterInfo::isVirtualRegister(R))
261 return true;
262 if (CSR[R])
263 return true;
264 }
265 }
266 return false;
267 }
268
269 /// Returns true if MBB has a machine instructions that indicates a tail call
270 /// in the block.
271 bool hasTailCall(const MachineBasicBlock &MBB) {
272 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
273 unsigned RetOpc = I->getOpcode();
274 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
275 }
276
277 /// Returns true if MBB contains an instruction that returns.
278 bool hasReturn(const MachineBasicBlock &MBB) {
279 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
280 if (I->isReturn())
281 return true;
282 return false;
283 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000284}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000285
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000286
287/// Implements shrink-wrapping of the stack frame. By default, stack frame
288/// is created in the function entry block, and is cleaned up in every block
289/// that returns. This function finds alternate blocks: one for the frame
290/// setup (prolog) and one for the cleanup (epilog).
291void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
292 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
293 static unsigned ShrinkCounter = 0;
294
295 if (ShrinkLimit.getPosition()) {
296 if (ShrinkCounter >= ShrinkLimit)
297 return;
298 ShrinkCounter++;
299 }
300
301 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
302 auto &HRI = *HST.getRegisterInfo();
303
304 MachineDominatorTree MDT;
305 MDT.runOnMachineFunction(MF);
306 MachinePostDominatorTree MPT;
307 MPT.runOnMachineFunction(MF);
308
309 typedef DenseMap<unsigned,unsigned> UnsignedMap;
310 UnsignedMap RPO;
311 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
312 RPOTType RPOT(&MF);
313 unsigned RPON = 0;
314 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
315 RPO[(*I)->getNumber()] = RPON++;
316
317 // Don't process functions that have loops, at least for now. Placement
318 // of prolog and epilog must take loop structure into account. For simpli-
319 // city don't do it right now.
320 for (auto &I : MF) {
321 unsigned BN = RPO[I.getNumber()];
322 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
323 // If found a back-edge, return.
324 if (RPO[(*SI)->getNumber()] <= BN)
325 return;
326 }
327 }
328
329 // Collect the set of blocks that need a stack frame to execute. Scan
330 // each block for uses/defs of callee-saved registers, calls, etc.
331 SmallVector<MachineBasicBlock*,16> SFBlocks;
332 BitVector CSR(Hexagon::NUM_TARGET_REGS);
333 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
334 CSR[*P] = true;
335
336 for (auto &I : MF)
337 if (needsStackFrame(I, CSR))
338 SFBlocks.push_back(&I);
339
340 DEBUG({
341 dbgs() << "Blocks needing SF: {";
342 for (auto &B : SFBlocks)
343 dbgs() << " BB#" << B->getNumber();
344 dbgs() << " }\n";
345 });
346 // No frame needed?
347 if (SFBlocks.empty())
348 return;
349
350 // Pick a common dominator and a common post-dominator.
351 MachineBasicBlock *DomB = SFBlocks[0];
352 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
353 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
354 if (!DomB)
355 break;
356 }
357 MachineBasicBlock *PDomB = SFBlocks[0];
358 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
359 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
360 if (!PDomB)
361 break;
362 }
363 DEBUG({
364 dbgs() << "Computed dom block: BB#";
365 if (DomB) dbgs() << DomB->getNumber();
366 else dbgs() << "<null>";
367 dbgs() << ", computed pdom block: BB#";
368 if (PDomB) dbgs() << PDomB->getNumber();
369 else dbgs() << "<null>";
370 dbgs() << "\n";
371 });
372 if (!DomB || !PDomB)
373 return;
374
375 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
376 if (!MDT.dominates(DomB, PDomB)) {
377 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
378 return;
379 }
380 if (!MPT.dominates(PDomB, DomB)) {
381 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
382 return;
383 }
384
385 // Finally, everything seems right.
386 PrologB = DomB;
387 EpilogB = PDomB;
388}
389
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000390/// Perform most of the PEI work here:
391/// - saving/restoring of the callee-saved registers,
392/// - stack frame creation and destruction.
393/// Normally, this work is distributed among various functions, but doing it
394/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000395void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
396 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000397 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
398 auto &HRI = *HST.getRegisterInfo();
399
400 MachineFrameInfo *MFI = MF.getFrameInfo();
401 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
402
403 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
404 if (EnableShrinkWrapping)
405 findShrunkPrologEpilog(MF, PrologB, EpilogB);
406
407 insertCSRSpillsInBlock(*PrologB, CSI, HRI);
408 insertPrologueInBlock(*PrologB);
409
410 if (EpilogB) {
411 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
412 insertEpilogueInBlock(*EpilogB);
413 } else {
414 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000415 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000416 insertCSRRestoresInBlock(B, CSI, HRI);
417
418 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000419 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000420 insertEpilogueInBlock(B);
421 }
422}
423
424
425void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB) const {
426 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000427 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000428 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000429 auto &HII = *HST.getInstrInfo();
430 auto &HRI = *HST.getRegisterInfo();
431 DebugLoc dl;
432
433 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
434
435 // Calculate the total stack frame size.
436 // Get the number of bytes to allocate from the FrameInfo.
437 unsigned FrameSize = MFI->getStackSize();
438 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000439 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000440 MFI->setMaxCallFrameSize(MaxCFA);
441
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000442 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000443 MFI->setStackSize(FrameSize);
444
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000445 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000446
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000447 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000448 unsigned NumBytes = MFI->getStackSize();
449 unsigned SP = HRI.getStackRegister();
450 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000451 MachineBasicBlock::iterator InsertPt = MBB.begin();
452
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000453 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
454 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000455
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000456 for (auto MI : AdjustRegs) {
457 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
458 expandAlloca(MI, HII, SP, MaxCF);
459 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000460 }
461
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000462 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000463 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000464
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000465 // Check for overflow.
466 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
467 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000468
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000469 // Create a dummy memory operand to avoid allocframe from being treated as
470 // a volatile memory reference.
471 MachineMemOperand *MMO =
472 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
473 4, 4);
474
475 if (NumBytes >= ALLOCFRAME_MAX) {
476 // Emit allocframe(#0).
477 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
478 .addImm(0)
479 .addMemOperand(MMO);
480
481 // Subtract offset from frame pointer.
482 // We use a caller-saved non-parameter register for that.
483 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
484 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
485 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000486 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
487 .addReg(SP)
488 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000489 } else {
490 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
491 .addImm(NumBytes)
492 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000493 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000494
495 if (AlignStack) {
496 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
497 .addReg(SP)
498 .addImm(-int64_t(MaxAlign));
499 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000500}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000501
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000502void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
503 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000504 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000505 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000506
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000507 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
508 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000509 auto &HRI = *HST.getRegisterInfo();
510 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000511
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000512 MachineInstr *RetI = nullptr;
513 for (auto &I : MBB) {
514 if (!I.isReturn())
515 continue;
516 RetI = &I;
517 break;
518 }
519 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
520
521 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
522 DebugLoc DL;
523 if (InsertPt != MBB.end())
524 DL = InsertPt->getDebugLoc();
525 else if (!MBB.empty())
526 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000527
528 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000529 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000530 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
531 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
532 .addReg(SP)
533 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000534 return;
535 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000536
537 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
538 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000539 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
540 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000541 MachineBasicBlock::iterator It = RetI;
542 ++It;
543 // Delete all instructions after the RESTORE (except labels).
544 while (It != MBB.end()) {
545 if (!It->isLabel())
546 It = MBB.erase(It);
547 else
548 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000549 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000550 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000551 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000552
553 // It is possible that the restoring code is a call to a library function.
554 // All of the restore* functions include "deallocframe", so we need to make
555 // sure that we don't add an extra one.
556 bool NeedsDeallocframe = true;
557 if (!MBB.empty() && InsertPt != MBB.begin()) {
558 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
559 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000560 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
561 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000562 NeedsDeallocframe = false;
563 }
564
565 if (!NeedsDeallocframe)
566 return;
567 // If the returning instruction is JMPret, replace it with dealloc_return,
568 // otherwise just add deallocframe. The function could be returning via a
569 // tail call.
570 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
571 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
572 return;
573 }
574 unsigned NewOpc = Hexagon::L4_return;
575 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
576 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000577 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000578 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000579}
580
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000581
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000582namespace {
583 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
584 if (!It->isBundle())
585 return It->getOpcode() == Hexagon::S2_allocframe;
586 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000587 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000588 while (++I != End && I->isBundled())
589 if (I->getOpcode() == Hexagon::S2_allocframe)
590 return true;
591 return false;
592 }
593
594 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
595 for (auto &I : B)
596 if (IsAllocFrame(I))
597 return I;
598 return B.end();
599 }
600}
601
602
603void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
604 for (auto &B : MF) {
605 auto AF = FindAllocFrame(B);
606 if (AF == B.end())
607 continue;
608 insertCFIInstructionsAt(B, ++AF);
609 }
610}
611
612
613void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
614 MachineBasicBlock::iterator At) const {
615 MachineFunction &MF = *MBB.getParent();
616 MachineFrameInfo *MFI = MF.getFrameInfo();
617 MachineModuleInfo &MMI = MF.getMMI();
618 auto &HST = MF.getSubtarget<HexagonSubtarget>();
619 auto &HII = *HST.getInstrInfo();
620 auto &HRI = *HST.getRegisterInfo();
621
622 // If CFI instructions have debug information attached, something goes
623 // wrong with the final assembly generation: the prolog_end is placed
624 // in a wrong location.
625 DebugLoc DL;
626 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
627
628 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
629
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000630 if (hasFP(MF)) {
631 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
632 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000633
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000634 // Define CFA via an offset from the value of FP.
635 //
636 // -8 -4 0 (SP)
637 // --+----+----+---------------------
638 // | FP | LR | increasing addresses -->
639 // --+----+----+---------------------
640 // | +-- Old SP (before allocframe)
641 // +-- New FP (after allocframe)
642 //
643 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
644 // MCCFIInstruction::createOffset takes the offset without sign change.
645 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
646 BuildMI(MBB, At, DL, CFID)
647 .addCFIIndex(MMI.addFrameInst(DefCfa));
648 // R31 (return addr) = CFA - 4
649 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
650 BuildMI(MBB, At, DL, CFID)
651 .addCFIIndex(MMI.addFrameInst(OffR31));
652 // R30 (frame ptr) = CFA - 8
653 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
654 BuildMI(MBB, At, DL, CFID)
655 .addCFIIndex(MMI.addFrameInst(OffR30));
656 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000657
658 static unsigned int RegsToMove[] = {
659 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
660 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
661 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
662 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
663 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
664 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
665 Hexagon::NoRegister
666 };
667
668 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
669
670 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
671 unsigned Reg = RegsToMove[i];
672 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
673 return C.getReg() == Reg;
674 };
675 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
676 if (F == CSI.end())
677 continue;
678
679 // Subtract 8 to make room for R30 and R31, which are added above.
680 unsigned FrameReg;
681 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
682
683 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
684 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
685 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
686 Offset);
687 BuildMI(MBB, At, DL, CFID)
688 .addCFIIndex(MMI.addFrameInst(OffReg));
689 } else {
690 // Split the double regs into subregs, and generate appropriate
691 // cfi_offsets.
692 // The only reason, we are split double regs is, llvm-mc does not
693 // understand paired registers for cfi_offset.
694 // Eg .cfi_offset r1:0, -64
695
696 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
697 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
698 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
699 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
700 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
701 Offset+4);
702 BuildMI(MBB, At, DL, CFID)
703 .addCFIIndex(MMI.addFrameInst(OffHi));
704 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
705 Offset);
706 BuildMI(MBB, At, DL, CFID)
707 .addCFIIndex(MMI.addFrameInst(OffLo));
708 }
709 }
710}
711
712
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000713bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000714 auto &MFI = *MF.getFrameInfo();
715 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
716
717 bool HasFixed = MFI.getNumFixedObjects();
718 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
719 .getLocalFrameObjectCount();
720 bool HasExtraAlign = HRI.needsStackRealignment(MF);
721 bool HasAlloca = MFI.hasVarSizedObjects();
722
723 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
724 // that this shouldn't be required, but doing so now because gcc does and
725 // gdb can't break at the start of the function without it. Will remove if
726 // this turns out to be a gdb bug.
727 //
728 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
729 return true;
730
731 // By default we want to use SP (since it's always there). FP requires
732 // some setup (i.e. ALLOCFRAME).
733 // Fixed and preallocated objects need FP if the distance from them to
734 // the SP is unknown (as is with alloca or aligna).
735 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
736 return true;
737
738 if (MFI.getStackSize() > 0) {
739 if (UseAllocframe)
740 return true;
741 }
742
743 if (MFI.hasCalls() ||
744 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
745 return true;
746
747 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000748}
749
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000750
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000751enum SpillKind {
752 SK_ToMem,
753 SK_FromMem,
754 SK_FromMemTailcall
755};
756
757static const char *
758getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType) {
759 const char * V4SpillToMemoryFunctions[] = {
760 "__save_r16_through_r17",
761 "__save_r16_through_r19",
762 "__save_r16_through_r21",
763 "__save_r16_through_r23",
764 "__save_r16_through_r25",
765 "__save_r16_through_r27" };
766
767 const char * V4SpillFromMemoryFunctions[] = {
768 "__restore_r16_through_r17_and_deallocframe",
769 "__restore_r16_through_r19_and_deallocframe",
770 "__restore_r16_through_r21_and_deallocframe",
771 "__restore_r16_through_r23_and_deallocframe",
772 "__restore_r16_through_r25_and_deallocframe",
773 "__restore_r16_through_r27_and_deallocframe" };
774
775 const char * V4SpillFromMemoryTailcallFunctions[] = {
776 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
777 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
778 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
779 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
780 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
781 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
782 };
783
784 const char **SpillFunc = nullptr;
785
786 switch(SpillType) {
787 case SK_ToMem:
788 SpillFunc = V4SpillToMemoryFunctions;
789 break;
790 case SK_FromMem:
791 SpillFunc = V4SpillFromMemoryFunctions;
792 break;
793 case SK_FromMemTailcall:
794 SpillFunc = V4SpillFromMemoryTailcallFunctions;
795 break;
796 }
797 assert(SpillFunc && "Unknown spill kind");
798
799 // Spill all callee-saved registers up to the highest register used.
800 switch (MaxReg) {
801 case Hexagon::R17:
802 return SpillFunc[0];
803 case Hexagon::R19:
804 return SpillFunc[1];
805 case Hexagon::R21:
806 return SpillFunc[2];
807 case Hexagon::R23:
808 return SpillFunc[3];
809 case Hexagon::R25:
810 return SpillFunc[4];
811 case Hexagon::R27:
812 return SpillFunc[5];
813 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000814 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000815 }
816 return 0;
817}
818
819/// Adds all callee-saved registers up to MaxReg to the instruction.
820static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
821 unsigned MaxReg, bool IsDef) {
822 // Add the callee-saved registers as implicit uses.
823 for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
824 MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
825 Inst->addOperand(ImpUse);
826 }
827}
828
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000829
James Y Knight5567baf2015-08-15 02:32:35 +0000830int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000831 int FI, unsigned &FrameReg) const {
832 auto &MFI = *MF.getFrameInfo();
833 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000834
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000835 int Offset = MFI.getObjectOffset(FI);
836 bool HasAlloca = MFI.hasVarSizedObjects();
837 bool HasExtraAlign = HRI.needsStackRealignment(MF);
838 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000839
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000840 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
841 unsigned AP = 0;
842 if (const MachineInstr *AI = getAlignaInstr(MF))
843 AP = AI->getOperand(0).getReg();
844 unsigned FrameSize = MFI.getStackSize();
845
846 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
847 // Use FP at -O0, except when there are objects with extra alignment.
848 // That additional alignment requirement may cause a pad to be inserted,
849 // which will make it impossible to use FP to access objects located
850 // past the pad.
851 if (NoOpt && !HasExtraAlign)
852 UseFP = true;
853 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
854 // Fixed and preallocated objects will be located before any padding
855 // so FP must be used to access them.
856 UseFP |= (HasAlloca || HasExtraAlign);
857 } else {
858 if (HasAlloca) {
859 if (HasExtraAlign)
860 UseAP = true;
861 else
862 UseFP = true;
863 }
864 }
865
866 // If FP was picked, then there had better be FP.
867 bool HasFP = hasFP(MF);
868 assert((HasFP || !UseFP) && "This function must have frame pointer");
869
870 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
871 // FP/LR. If the base register is used to access an object across these
872 // 8 bytes, then the offset will need to be adjusted by 8.
873 //
874 // After allocframe:
875 // HexagonISelLowering adds 8 to ---+
876 // the offsets of all stack-based |
877 // arguments (*) |
878 // |
879 // getObjectOffset < 0 0 8 getObjectOffset >= 8
880 // ------------------------+-----+------------------------> increasing
881 // <local objects> |FP/LR| <input arguments> addresses
882 // -----------------+------+-----+------------------------>
883 // | |
884 // SP/AP point --+ +-- FP points here (**)
885 // somewhere on
886 // this side of FP/LR
887 //
888 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
889 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
890
891 // The lowering assumes that FP/LR is present, and so the offsets of
892 // the formal arguments start at 8. If FP/LR is not there we need to
893 // reduce the offset by 8.
894 if (Offset > 0 && !HasFP)
895 Offset -= 8;
896
897 if (UseFP)
898 FrameReg = FP;
899 else if (UseAP)
900 FrameReg = AP;
901 else
902 FrameReg = SP;
903
904 // Calculate the actual offset in the instruction. If there is no FP
905 // (in other words, no allocframe), then SP will not be adjusted (i.e.
906 // there will be no SP -= FrameSize), so the frame size should not be
907 // added to the calculated offset.
908 int RealOffset = Offset;
909 if (!UseFP && !UseAP && HasFP)
910 RealOffset = FrameSize+Offset;
911 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000912}
913
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000914
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000915bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
916 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
917 if (CSI.empty())
918 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000919
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000920 MachineBasicBlock::iterator MI = MBB.begin();
921 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000922 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000923
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000924 if (useSpillFunction(MF, CSI)) {
925 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
926 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000927 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
928 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
929
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000930 // Call spill function.
931 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000932 unsigned SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
933 : Hexagon::SAVE_REGISTERS_CALL_V4;
934
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000935 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000936 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000937 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000938 // Add callee-saved registers as use.
939 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
940 // Add live in registers.
941 for (unsigned I = 0; I < CSI.size(); ++I)
942 MBB.addLiveIn(CSI[I].getReg());
943 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000944 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000945
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000946 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000947 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000948 // Add live in registers. We treat eh_return callee saved register r0 - r3
949 // specially. They are not really callee saved registers as they are not
950 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000951 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
952 int FI = CSI[i].getFrameIdx();
953 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000954 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000955 if (IsKill)
956 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000957 }
958 return true;
959}
960
961
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000962bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
963 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
964 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000965 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000966
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000967 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
968 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000969 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000970
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000971 if (useRestoreFunction(MF, CSI)) {
972 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
973 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
974 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
975 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000976 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
977 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000978
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000979 // Call spill function.
980 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
981 : MBB.getLastNonDebugInstr()->getDebugLoc();
982 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000983
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000984 if (HasTC) {
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000985 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
986 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000987 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000988 .addExternalSymbol(RestoreFn);
989 } else {
990 // The block has a return.
991 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
992 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000993 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
994 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000995 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000996 .addExternalSymbol(RestoreFn);
997 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000998 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000999 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001000 addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
1001 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001002 }
1003
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001004 for (unsigned i = 0; i < CSI.size(); ++i) {
1005 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001006 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1007 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001008 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001009 }
1010 return true;
1011}
1012
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001013
1014void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1015 MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001016 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001017 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001018 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001019 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1020 "Cannot handle this call frame pseudo instruction");
Eli Bendersky8da87162013-02-21 20:05:00 +00001021 MBB.erase(I);
1022}
1023
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001024
1025void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1026 MachineFunction &MF, RegScavenger *RS) const {
1027 // If this function has uses aligned stack and also has variable sized stack
1028 // objects, then we need to map all spill slots to fixed positions, so that
1029 // they can be accessed through FP. Otherwise they would have to be accessed
1030 // via AP, which may not be available at the particular place in the program.
1031 MachineFrameInfo *MFI = MF.getFrameInfo();
1032 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001033 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001034
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001035 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001036 return;
1037
1038 unsigned LFS = MFI->getLocalFrameSize();
1039 int Offset = -LFS;
1040 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1041 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1042 continue;
1043 int S = MFI->getObjectSize(i);
1044 LFS += S;
1045 Offset -= S;
1046 MFI->mapLocalFrameObject(i, Offset);
1047 }
1048
1049 MFI->setLocalFrameSize(LFS);
1050 unsigned A = MFI->getLocalFrameMaxAlign();
1051 assert(A <= 8 && "Unexpected local frame alignment");
1052 if (A == 0)
1053 MFI->setLocalFrameMaxAlign(8);
1054 MFI->setUseLocalStackAllocationBlock(true);
1055}
1056
1057/// Returns true if there is no caller saved registers available.
1058static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1059 const HexagonRegisterInfo &HRI) {
1060 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001061 BitVector Reserved = HRI.getReservedRegs(MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001062
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001063 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1064 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1065 if (MRI.isPhysRegUsed(*AI))
1066 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001067 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001068 };
1069
1070 // Check for an unused caller-saved register.
1071 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF); *P; ++P)
1072 if (!IsUsed(*P))
1073 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001074 // All caller-saved registers are used.
1075 return true;
1076}
1077
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001078
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001079#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001080static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001081 dbgs() << '{';
1082 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1083 unsigned R = x;
1084 dbgs() << ' ' << PrintReg(R, &TRI);
1085 }
1086 dbgs() << " }";
1087}
1088#endif
1089
1090
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001091bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1092 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001093 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001094 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001095 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001096 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001097
1098 // Generate a set of unique, callee-saved registers (SRegs), where each
1099 // register in the set is maximal in terms of sub-/super-register relation,
1100 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1101
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001102 // (1) For each callee-saved register, add that register and all of its
1103 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001104 DEBUG(dbgs() << "Initial CS registers: {");
1105 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1106 unsigned R = CSI[i].getReg();
1107 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1108 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1109 SRegs[*SR] = true;
1110 }
1111 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001112 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001113
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001114 // (2) For each reserved register, remove that register and all of its
1115 // sub- and super-registers from SRegs.
1116 BitVector Reserved = TRI->getReservedRegs(MF);
1117 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1118 unsigned R = x;
1119 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1120 SRegs[*SR] = false;
1121 }
1122 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1123 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1124
1125 // (3) Collect all registers that have at least one sub-register in SRegs,
1126 // and also have no sub-registers that are reserved. These will be the can-
1127 // didates for saving as a whole instead of their individual sub-registers.
1128 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1129 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001130 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1131 unsigned R = x;
1132 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1133 TmpSup[*SR] = true;
1134 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001135 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1136 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001137 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1138 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001139 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001140 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001141 break;
1142 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001143 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001144 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001145
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001146 // (4) Include all super-registers found in (3) into SRegs.
1147 SRegs |= TmpSup;
1148 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001149
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001150 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001151 // remove R from SRegs.
1152 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1153 unsigned R = x;
1154 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1155 if (!SRegs[*SR])
1156 continue;
1157 SRegs[R] = false;
1158 break;
1159 }
1160 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001161 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001162
1163 // Now, for each register that has a fixed stack slot, create the stack
1164 // object for it.
1165 CSI.clear();
1166
1167 typedef TargetFrameLowering::SpillSlot SpillSlot;
1168 unsigned NumFixed;
1169 int MinOffset = 0; // CS offsets are negative.
1170 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1171 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1172 if (!SRegs[S->Reg])
1173 continue;
1174 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1175 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1176 MinOffset = std::min(MinOffset, S->Offset);
1177 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1178 SRegs[S->Reg] = false;
1179 }
1180
1181 // There can be some registers that don't have fixed slots. For example,
1182 // we need to store R0-R3 in functions with exception handling. For each
1183 // such register, create a non-fixed stack object.
1184 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1185 unsigned R = x;
1186 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1187 int Off = MinOffset - RC->getSize();
1188 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1189 assert(isPowerOf2_32(Align));
1190 Off &= -Align;
1191 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1192 MinOffset = std::min(MinOffset, Off);
1193 CSI.push_back(CalleeSavedInfo(R, FI));
1194 SRegs[R] = false;
1195 }
1196
1197 DEBUG({
1198 dbgs() << "CS information: {";
1199 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1200 int FI = CSI[i].getFrameIdx();
1201 int Off = MFI->getObjectOffset(FI);
1202 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1203 if (Off >= 0)
1204 dbgs() << '+';
1205 dbgs() << Off;
1206 }
1207 dbgs() << " }\n";
1208 });
1209
1210#ifndef NDEBUG
1211 // Verify that all registers were handled.
1212 bool MissedReg = false;
1213 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1214 unsigned R = x;
1215 dbgs() << PrintReg(R, TRI) << ' ';
1216 MissedReg = true;
1217 }
1218 if (MissedReg)
1219 llvm_unreachable("...there are unhandled callee-saved registers!");
1220#endif
1221
1222 return true;
1223}
1224
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001225
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001226bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1227 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1228 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1229 MachineInstr *MI = &*It;
1230 DebugLoc DL = MI->getDebugLoc();
1231 unsigned DstR = MI->getOperand(0).getReg();
1232 unsigned SrcR = MI->getOperand(1).getReg();
1233 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1234 !Hexagon::ModRegsRegClass.contains(SrcR))
1235 return false;
1236
1237 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1238 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1239 .addOperand(MI->getOperand(1));
1240 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1241 .addReg(TmpR, RegState::Kill);
1242
1243 NewRegs.push_back(TmpR);
1244 B.erase(It);
1245 return true;
1246}
1247
1248bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1249 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1250 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1251 MachineInstr *MI = &*It;
1252 DebugLoc DL = MI->getDebugLoc();
1253 unsigned Opc = MI->getOpcode();
1254 unsigned SrcR = MI->getOperand(2).getReg();
1255 bool IsKill = MI->getOperand(2).isKill();
1256
1257 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1258 int FI = MI->getOperand(0).getIndex();
1259
1260 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1261 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1262 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1263 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1264 : Hexagon::A2_tfrcrr;
1265 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1266 .addReg(SrcR, getKillRegState(IsKill));
1267
1268 // S2_storeri_io FI, 0, TmpR
1269 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1270 .addFrameIndex(FI)
1271 .addImm(0)
1272 .addReg(TmpR, RegState::Kill)
1273 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1274
1275 NewRegs.push_back(TmpR);
1276 B.erase(It);
1277 return true;
1278}
1279
1280bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1281 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1282 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1283 MachineInstr *MI = &*It;
1284 DebugLoc DL = MI->getDebugLoc();
1285 unsigned Opc = MI->getOpcode();
1286 unsigned DstR = MI->getOperand(0).getReg();
1287
1288 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1289 int FI = MI->getOperand(1).getIndex();
1290
1291 // TmpR = L2_loadri_io FI, 0
1292 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1293 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1294 .addFrameIndex(FI)
1295 .addImm(0)
1296 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1297
1298 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1299 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1300 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1301 : Hexagon::A2_tfrrcr;
1302 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1303 .addReg(TmpR, RegState::Kill);
1304
1305 NewRegs.push_back(TmpR);
1306 B.erase(It);
1307 return true;
1308}
1309
1310
1311bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1312 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1313 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1314 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1315 MachineInstr *MI = &*It;
1316 DebugLoc DL = MI->getDebugLoc();
1317 unsigned SrcR = MI->getOperand(2).getReg();
1318 bool IsKill = MI->getOperand(2).isKill();
1319
1320 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1321 int FI = MI->getOperand(0).getIndex();
1322
1323 bool Is128B = HST.useHVXDblOps();
1324 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1325 : &Hexagon::VectorRegs128BRegClass;
1326
1327 // Insert transfer to general vector register.
1328 // TmpR0 = A2_tfrsi 0x01010101
1329 // TmpR1 = V6_vandqrt Qx, TmpR0
1330 // store FI, 0, TmpR1
1331 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1332 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1333
1334 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1335 .addImm(0x01010101);
1336
1337 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1338 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1339 .addReg(SrcR, getKillRegState(IsKill))
1340 .addReg(TmpR0, RegState::Kill);
1341
1342 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1343 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1344 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1345
1346 NewRegs.push_back(TmpR0);
1347 NewRegs.push_back(TmpR1);
1348 B.erase(It);
1349 return true;
1350}
1351
1352bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1353 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1354 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1355 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1356 MachineInstr *MI = &*It;
1357 DebugLoc DL = MI->getDebugLoc();
1358 unsigned DstR = MI->getOperand(0).getReg();
1359
1360 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1361 int FI = MI->getOperand(1).getIndex();
1362
1363 bool Is128B = HST.useHVXDblOps();
1364 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1365 : &Hexagon::VectorRegs128BRegClass;
1366
1367 // TmpR0 = A2_tfrsi 0x01010101
1368 // TmpR1 = load FI, 0
1369 // DstR = V6_vandvrt TmpR1, TmpR0
1370 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1371 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1372
1373 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1374 .addImm(0x01010101);
1375 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1376 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1377 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1378
1379 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1380 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1381 .addReg(TmpR1, RegState::Kill)
1382 .addReg(TmpR0, RegState::Kill);
1383
1384 NewRegs.push_back(TmpR0);
1385 NewRegs.push_back(TmpR1);
1386 B.erase(It);
1387 return true;
1388}
1389
1390bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1391 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1392 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1393 MachineFunction &MF = *B.getParent();
1394 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1395 auto &MFI = *MF.getFrameInfo();
1396 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1397 MachineInstr *MI = &*It;
1398 DebugLoc DL = MI->getDebugLoc();
1399
1400 unsigned SrcR = MI->getOperand(2).getReg();
1401 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1402 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1403 bool IsKill = MI->getOperand(2).isKill();
1404
1405 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1406 int FI = MI->getOperand(0).getIndex();
1407
1408 bool Is128B = HST.useHVXDblOps();
1409 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1410 : &Hexagon::VectorRegs128BRegClass;
1411 unsigned Size = RC->getSize();
1412 unsigned NeedAlign = RC->getAlignment();
1413 unsigned HasAlign = MFI.getObjectAlignment(FI);
1414 unsigned StoreOpc;
1415
1416 // Store low part.
1417 if (NeedAlign <= HasAlign)
1418 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1419 else
1420 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1421
1422 BuildMI(B, It, DL, HII.get(StoreOpc))
1423 .addFrameIndex(FI)
1424 .addImm(0)
1425 .addReg(SrcLo, getKillRegState(IsKill))
1426 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1427
1428 // Load high part.
1429 if (NeedAlign <= MinAlign(HasAlign, Size))
1430 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1431 else
1432 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1433
1434 BuildMI(B, It, DL, HII.get(StoreOpc))
1435 .addFrameIndex(FI)
1436 .addImm(Size)
1437 .addReg(SrcHi, getKillRegState(IsKill))
1438 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1439
1440 B.erase(It);
1441 return true;
1442}
1443
1444bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1445 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1446 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1447 MachineFunction &MF = *B.getParent();
1448 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1449 auto &MFI = *MF.getFrameInfo();
1450 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1451 MachineInstr *MI = &*It;
1452 DebugLoc DL = MI->getDebugLoc();
1453
1454 unsigned DstR = MI->getOperand(0).getReg();
1455 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1456 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1457
1458 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1459 int FI = MI->getOperand(1).getIndex();
1460
1461 bool Is128B = HST.useHVXDblOps();
1462 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1463 : &Hexagon::VectorRegs128BRegClass;
1464 unsigned Size = RC->getSize();
1465 unsigned NeedAlign = RC->getAlignment();
1466 unsigned HasAlign = MFI.getObjectAlignment(FI);
1467 unsigned LoadOpc;
1468
1469 // Load low part.
1470 if (NeedAlign <= HasAlign)
1471 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1472 else
1473 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1474
1475 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1476 .addFrameIndex(FI)
1477 .addImm(0)
1478 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1479
1480 // Load high part.
1481 if (NeedAlign <= MinAlign(HasAlign, Size))
1482 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1483 else
1484 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1485
1486 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1487 .addFrameIndex(FI)
1488 .addImm(Size)
1489 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1490
1491 B.erase(It);
1492 return true;
1493}
1494
1495bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1496 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1497 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1498 MachineFunction &MF = *B.getParent();
1499 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1500 auto &MFI = *MF.getFrameInfo();
1501 MachineInstr *MI = &*It;
1502 DebugLoc DL = MI->getDebugLoc();
1503
1504 unsigned SrcR = MI->getOperand(2).getReg();
1505 bool IsKill = MI->getOperand(2).isKill();
1506
1507 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1508 int FI = MI->getOperand(0).getIndex();
1509
1510 bool Is128B = HST.useHVXDblOps();
1511 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1512 : &Hexagon::VectorRegs128BRegClass;
1513
1514 unsigned NeedAlign = RC->getAlignment();
1515 unsigned HasAlign = MFI.getObjectAlignment(FI);
1516 unsigned StoreOpc;
1517
1518 if (NeedAlign <= HasAlign)
1519 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1520 else
1521 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1522
1523 BuildMI(B, It, DL, HII.get(StoreOpc))
1524 .addFrameIndex(FI)
1525 .addImm(0)
1526 .addReg(SrcR, getKillRegState(IsKill))
1527 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1528
1529 B.erase(It);
1530 return true;
1531}
1532
1533bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1534 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1535 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1536 MachineFunction &MF = *B.getParent();
1537 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1538 auto &MFI = *MF.getFrameInfo();
1539 MachineInstr *MI = &*It;
1540 DebugLoc DL = MI->getDebugLoc();
1541
1542 unsigned DstR = MI->getOperand(0).getReg();
1543
1544 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1545 int FI = MI->getOperand(1).getIndex();
1546
1547 bool Is128B = HST.useHVXDblOps();
1548 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1549 : &Hexagon::VectorRegs128BRegClass;
1550
1551 unsigned NeedAlign = RC->getAlignment();
1552 unsigned HasAlign = MFI.getObjectAlignment(FI);
1553 unsigned LoadOpc;
1554
1555 if (NeedAlign <= HasAlign)
1556 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1557 else
1558 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1559
1560 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1561 .addFrameIndex(FI)
1562 .addImm(0)
1563 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1564
1565 B.erase(It);
1566 return true;
1567}
1568
1569
1570bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1571 SmallVectorImpl<unsigned> &NewRegs) const {
1572 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001573 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001574 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001575 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001576
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001577 for (auto &B : MF) {
1578 // Traverse the basic block.
1579 MachineBasicBlock::iterator NextI;
1580 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1581 MachineInstr *MI = &*I;
1582 NextI = std::next(I);
1583 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001584
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001585 switch (Opc) {
1586 case TargetOpcode::COPY:
1587 Changed = expandCopy(B, I, MRI, HII, NewRegs);
1588 break;
1589 case Hexagon::STriw_pred:
1590 case Hexagon::STriw_mod:
1591 Changed = expandStoreInt(B, I, MRI, HII, NewRegs);
1592 break;
1593 case Hexagon::LDriw_pred:
1594 case Hexagon::LDriw_mod:
1595 Changed = expandLoadInt(B, I, MRI, HII, NewRegs);
1596 break;
1597 case Hexagon::STriq_pred_V6:
1598 case Hexagon::STriq_pred_V6_128B:
1599 Changed = expandStoreVecPred(B, I, MRI, HII, NewRegs);
1600 break;
1601 case Hexagon::LDriq_pred_V6:
1602 case Hexagon::LDriq_pred_V6_128B:
1603 Changed = expandLoadVecPred(B, I, MRI, HII, NewRegs);
1604 break;
1605 case Hexagon::LDrivv_pseudo_V6:
1606 case Hexagon::LDrivv_pseudo_V6_128B:
1607 Changed = expandLoadVec2(B, I, MRI, HII, NewRegs);
1608 break;
1609 case Hexagon::STrivv_pseudo_V6:
1610 case Hexagon::STrivv_pseudo_V6_128B:
1611 Changed = expandStoreVec2(B, I, MRI, HII, NewRegs);
1612 break;
1613 case Hexagon::STriv_pseudo_V6:
1614 case Hexagon::STriv_pseudo_V6_128B:
1615 Changed = expandStoreVec(B, I, MRI, HII, NewRegs);
1616 break;
1617 case Hexagon::LDriv_pseudo_V6:
1618 case Hexagon::LDriv_pseudo_V6_128B:
1619 Changed = expandLoadVec(B, I, MRI, HII, NewRegs);
1620 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001621 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001622 }
1623 }
1624
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001625 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001626}
1627
1628
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001629void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1630 BitVector &SavedRegs,
1631 RegScavenger *RS) const {
1632 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1633 auto &HRI = *HST.getRegisterInfo();
1634
1635 SavedRegs.resize(HRI.getNumRegs());
1636
1637 // If we have a function containing __builtin_eh_return we want to spill and
1638 // restore all callee saved registers. Pretend that they are used.
1639 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1640 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1641 SavedRegs.set(*R);
1642
1643 // Replace predicate register pseudo spill code.
1644 SmallVector<unsigned,8> NewRegs;
1645 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001646 if (OptimizeSpillSlots)
1647 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001648
1649 // We need to reserve a a spill slot if scavenging could potentially require
1650 // spilling a scavenged register.
1651 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1652 MachineRegisterInfo &MRI = MF.getRegInfo();
1653 SetVector<const TargetRegisterClass*> SpillRCs;
1654 for (unsigned VR : NewRegs)
1655 SpillRCs.insert(MRI.getRegClass(VR));
1656
1657 MachineFrameInfo &MFI = *MF.getFrameInfo();
1658 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1659 if (SpillRCs.count(&IntRC)) {
1660 for (int i = 0; i < NumberScavengerSlots; i++) {
1661 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1662 IntRC.getAlignment());
1663 RS->addScavengingFrameIndex(NewFI);
1664 }
1665 }
1666 for (auto *RC : SpillRCs) {
1667 if (RC == &IntRC)
1668 continue;
1669 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1670 RS->addScavengingFrameIndex(NewFI);
1671 }
1672 }
1673
1674 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1675}
1676
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001677
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001678unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1679 HexagonBlockRanges::IndexRange &FIR,
1680 HexagonBlockRanges::InstrIndexMap &IndexMap,
1681 HexagonBlockRanges::RegToRangeMap &DeadMap,
1682 const TargetRegisterClass *RC) const {
1683 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1684 auto &MRI = MF.getRegInfo();
1685
1686 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1687 auto F = DeadMap.find({Reg,0});
1688 if (F == DeadMap.end())
1689 return false;
1690 for (auto &DR : F->second)
1691 if (DR.contains(FIR))
1692 return true;
1693 return false;
1694 };
1695
1696 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1697 bool Dead = true;
1698 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1699 if (isDead(R.Reg))
1700 continue;
1701 Dead = false;
1702 break;
1703 }
1704 if (Dead)
1705 return Reg;
1706 }
1707 return 0;
1708}
1709
1710void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1711 SmallVectorImpl<unsigned> &VRegs) const {
1712 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1713 auto &HII = *HST.getInstrInfo();
1714 auto &HRI = *HST.getRegisterInfo();
1715 auto &MRI = MF.getRegInfo();
1716 HexagonBlockRanges HBR(MF);
1717
1718 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1719 BlockIndexMap;
1720 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1721 BlockRangeMap;
1722 typedef HexagonBlockRanges::IndexType IndexType;
1723
1724 struct SlotInfo {
1725 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001726 unsigned Size;
1727 const TargetRegisterClass *RC;
1728
1729 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001730 };
1731
1732 BlockIndexMap BlockIndexes;
1733 SmallSet<int,4> BadFIs;
1734 std::map<int,SlotInfo> FIRangeMap;
1735
1736 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1737 -> const TargetRegisterClass* {
1738 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1739 assert(R.Sub == 0);
1740 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1741 auto *RCR = MRI.getRegClass(R.Reg);
1742 if (R.Sub == 0)
1743 return RCR;
1744 unsigned PR = *RCR->begin();
1745 R.Reg = HRI.getSubReg(PR, R.Sub);
1746 }
1747 return HRI.getMinimalPhysRegClass(R.Reg);
1748 };
1749 // Accumulate register classes: get a common class for a pre-existing
1750 // class HaveRC and a new class NewRC. Return nullptr if a common class
1751 // cannot be found, otherwise return the resulting class. If HaveRC is
1752 // nullptr, assume that it is still unset.
1753 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1754 const TargetRegisterClass *NewRC)
1755 -> const TargetRegisterClass* {
1756 if (HaveRC == nullptr || HaveRC == NewRC)
1757 return NewRC;
1758 // Different classes, both non-null. Pick the more general one.
1759 if (HaveRC->hasSubClassEq(NewRC))
1760 return HaveRC;
1761 if (NewRC->hasSubClassEq(HaveRC))
1762 return NewRC;
1763 return nullptr;
1764 };
1765
1766 // Scan all blocks in the function. Check all occurrences of frame indexes,
1767 // and collect relevant information.
1768 for (auto &B : MF) {
1769 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001770 // Emplace appears not to be supported in gcc 4.7.2-4.
1771 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001772 auto P = BlockIndexes.insert(
1773 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001774 auto &IndexMap = P.first->second;
1775 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1776 << IndexMap << '\n');
1777
1778 for (auto &In : B) {
1779 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001780 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1781 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001782 if (Load && Store) {
1783 // If it's both a load and a store, then we won't handle it.
1784 BadFIs.insert(LFI);
1785 BadFIs.insert(SFI);
1786 continue;
1787 }
1788 // Check for register classes of the register used as the source for
1789 // the store, and the register used as the destination for the load.
1790 // Also, only accept base+imm_offset addressing modes. Other addressing
1791 // modes can have side-effects (post-increments, etc.). For stack
1792 // slots they are very unlikely, so there is not much loss due to
1793 // this restriction.
1794 if (Load || Store) {
1795 int TFI = Load ? LFI : SFI;
1796 unsigned AM = HII.getAddrMode(&In);
1797 SlotInfo &SI = FIRangeMap[TFI];
1798 bool Bad = (AM != HexagonII::BaseImmOffset);
1799 if (!Bad) {
1800 // If the addressing mode is ok, check the register class.
1801 const TargetRegisterClass *RC = nullptr;
1802 if (Load) {
1803 MachineOperand &DataOp = In.getOperand(0);
1804 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1805 } else {
1806 MachineOperand &DataOp = In.getOperand(2);
1807 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1808 }
1809 RC = getCommonRC(SI.RC, RC);
1810 if (RC == nullptr)
1811 Bad = true;
1812 else
1813 SI.RC = RC;
1814 }
1815 if (!Bad) {
1816 // Check sizes.
1817 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1818 if (SI.Size != 0 && SI.Size != S)
1819 Bad = true;
1820 else
1821 SI.Size = S;
1822 }
1823 if (Bad)
1824 BadFIs.insert(TFI);
1825 }
1826
1827 // Locate uses of frame indices.
1828 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1829 const MachineOperand &Op = In.getOperand(i);
1830 if (!Op.isFI())
1831 continue;
1832 int FI = Op.getIndex();
1833 // Make sure that the following operand is an immediate and that
1834 // it is 0. This is the offset in the stack object.
1835 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1836 In.getOperand(i+1).getImm() != 0)
1837 BadFIs.insert(FI);
1838 if (BadFIs.count(FI))
1839 continue;
1840
1841 IndexType Index = IndexMap.getIndex(&In);
1842 if (Load) {
1843 if (LastStore[FI] == IndexType::None)
1844 LastStore[FI] = IndexType::Entry;
1845 LastLoad[FI] = Index;
1846 } else if (Store) {
1847 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1848 if (LastStore[FI] != IndexType::None)
1849 RL.add(LastStore[FI], LastLoad[FI], false, false);
1850 else if (LastLoad[FI] != IndexType::None)
1851 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1852 LastLoad[FI] = IndexType::None;
1853 LastStore[FI] = Index;
1854 } else {
1855 BadFIs.insert(FI);
1856 }
1857 }
1858 }
1859
1860 for (auto &I : LastLoad) {
1861 IndexType LL = I.second;
1862 if (LL == IndexType::None)
1863 continue;
1864 auto &RL = FIRangeMap[I.first].Map[&B];
1865 IndexType &LS = LastStore[I.first];
1866 if (LS != IndexType::None)
1867 RL.add(LS, LL, false, false);
1868 else
1869 RL.add(IndexType::Entry, LL, false, false);
1870 LS = IndexType::None;
1871 }
1872 for (auto &I : LastStore) {
1873 IndexType LS = I.second;
1874 if (LS == IndexType::None)
1875 continue;
1876 auto &RL = FIRangeMap[I.first].Map[&B];
1877 RL.add(LS, IndexType::None, false, false);
1878 }
1879 }
1880
1881 DEBUG({
1882 for (auto &P : FIRangeMap) {
1883 dbgs() << "fi#" << P.first;
1884 if (BadFIs.count(P.first))
1885 dbgs() << " (bad)";
1886 dbgs() << " RC: ";
1887 if (P.second.RC != nullptr)
1888 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1889 else
1890 dbgs() << "<null>\n";
1891 for (auto &R : P.second.Map)
1892 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1893 }
1894 });
1895
1896 // When a slot is loaded from in a block without being stored to in the
1897 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1898 // consider this slot to be live-on-exit from all blocks.
1899 SmallSet<int,4> LoxFIs;
1900
1901 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1902
1903 for (auto &P : FIRangeMap) {
1904 // P = pair(FI, map: BB->RangeList)
1905 if (BadFIs.count(P.first))
1906 continue;
1907 for (auto &B : MF) {
1908 auto F = P.second.Map.find(&B);
1909 // F = pair(BB, RangeList)
1910 if (F == P.second.Map.end() || F->second.empty())
1911 continue;
1912 HexagonBlockRanges::IndexRange &IR = F->second.front();
1913 if (IR.start() == IndexType::Entry)
1914 LoxFIs.insert(P.first);
1915 BlockFIMap[&B].push_back(P.first);
1916 }
1917 }
1918
1919 DEBUG({
1920 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1921 for (auto &P : BlockFIMap) {
1922 auto &FIs = P.second;
1923 if (FIs.empty())
1924 continue;
1925 dbgs() << " BB#" << P.first->getNumber() << ": {";
1926 for (auto I : FIs) {
1927 dbgs() << " fi#" << I;
1928 if (LoxFIs.count(I))
1929 dbgs() << '*';
1930 }
1931 dbgs() << " }\n";
1932 }
1933 });
1934
1935 // eliminate loads, when all loads eliminated, eliminate all stores.
1936 for (auto &B : MF) {
1937 auto F = BlockIndexes.find(&B);
1938 assert(F != BlockIndexes.end());
1939 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1940 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
1941 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
1942 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
1943 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
1944
1945 for (auto FI : BlockFIMap[&B]) {
1946 if (BadFIs.count(FI))
1947 continue;
1948 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
1949 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1950 for (auto &Range : RL) {
1951 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
1952 if (!IndexType::isInstr(Range.start()) ||
1953 !IndexType::isInstr(Range.end()))
1954 continue;
1955 MachineInstr *SI = IM.getInstr(Range.start());
1956 MachineInstr *EI = IM.getInstr(Range.end());
1957 assert(SI->mayStore() && "Unexpected start instruction");
1958 assert(EI->mayLoad() && "Unexpected end instruction");
1959 MachineOperand &SrcOp = SI->getOperand(2);
1960
1961 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
1962 SrcOp.getSubReg() };
1963 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
1964 // The this-> is needed to unconfuse MSVC.
1965 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
1966 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
1967 if (FoundR == 0)
1968 continue;
1969
1970 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
1971 MachineBasicBlock::iterator StartIt = SI, NextIt;
1972 MachineInstr *CopyIn = nullptr;
1973 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
1974 DebugLoc DL = SI->getDebugLoc();
1975 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
1976 .addOperand(SrcOp);
1977 }
1978
1979 ++StartIt;
1980 // Check if this is a last store and the FI is live-on-exit.
1981 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
1982 // Update store's source register.
1983 if (unsigned SR = SrcOp.getSubReg())
1984 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
1985 else
1986 SrcOp.setReg(FoundR);
1987 SrcOp.setSubReg(0);
1988 // We are keeping this register live.
1989 SrcOp.setIsKill(false);
1990 } else {
1991 B.erase(SI);
1992 IM.replaceInstr(SI, CopyIn);
1993 }
1994
1995 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
1996 for (auto It = StartIt; It != EndIt; It = NextIt) {
1997 MachineInstr *MI = &*It;
1998 NextIt = std::next(It);
1999 int TFI;
2000 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2001 continue;
2002 unsigned DstR = MI->getOperand(0).getReg();
2003 assert(MI->getOperand(0).getSubReg() == 0);
2004 MachineInstr *CopyOut = nullptr;
2005 if (DstR != FoundR) {
2006 DebugLoc DL = MI->getDebugLoc();
2007 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2008 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2009 unsigned CopyOpc = TargetOpcode::COPY;
2010 if (HII.isSignExtendingLoad(MI))
2011 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2012 else if (HII.isZeroExtendingLoad(MI))
2013 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2014 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2015 .addReg(FoundR, getKillRegState(MI == EI));
2016 }
2017 IM.replaceInstr(MI, CopyOut);
2018 B.erase(It);
2019 }
2020
2021 // Update the dead map.
2022 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2023 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2024 DM[RR].subtract(Range);
2025 } // for Range in range list
2026 }
2027 }
2028}
2029
2030
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002031void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002032 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002033 MachineBasicBlock &MB = *AI->getParent();
2034 DebugLoc DL = AI->getDebugLoc();
2035 unsigned A = AI->getOperand(2).getImm();
2036
2037 // Have
2038 // Rd = alloca Rs, #A
2039 //
2040 // If Rs and Rd are different registers, use this sequence:
2041 // Rd = sub(r29, Rs)
2042 // r29 = sub(r29, Rs)
2043 // Rd = and(Rd, #-A) ; if necessary
2044 // r29 = and(r29, #-A) ; if necessary
2045 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2046 // otherwise, do
2047 // Rd = sub(r29, Rs)
2048 // Rd = and(Rd, #-A) ; if necessary
2049 // r29 = Rd
2050 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2051
2052 MachineOperand &RdOp = AI->getOperand(0);
2053 MachineOperand &RsOp = AI->getOperand(1);
2054 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2055
2056 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002057 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002058 .addReg(SP)
2059 .addReg(Rs);
2060 if (Rs != Rd) {
2061 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002062 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002063 .addReg(SP)
2064 .addReg(Rs);
2065 }
2066 if (A > 8) {
2067 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002068 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002069 .addReg(Rd)
2070 .addImm(-int64_t(A));
2071 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002072 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002073 .addReg(SP)
2074 .addImm(-int64_t(A));
2075 }
2076 if (Rs == Rd) {
2077 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002078 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002079 .addReg(Rd);
2080 }
2081 if (CF > 0) {
2082 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002083 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002084 .addReg(Rd)
2085 .addImm(CF);
2086 }
2087}
2088
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002089
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002090bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2091 const MachineFrameInfo *MFI = MF.getFrameInfo();
2092 if (!MFI->hasVarSizedObjects())
2093 return false;
2094 unsigned MaxA = MFI->getMaxAlignment();
2095 if (MaxA <= getStackAlignment())
2096 return false;
2097 return true;
2098}
2099
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002100
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002101const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2102 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002103 for (auto &B : MF)
2104 for (auto &I : B)
2105 if (I.getOpcode() == Hexagon::ALIGNA)
2106 return &I;
2107 return nullptr;
2108}
2109
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002110
Sanjay Patel924879a2015-08-04 15:49:57 +00002111// FIXME: Use Function::optForSize().
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002112inline static bool isOptSize(const MachineFunction &MF) {
2113 AttributeSet AF = MF.getFunction()->getAttributes();
2114 return AF.hasAttribute(AttributeSet::FunctionIndex,
2115 Attribute::OptimizeForSize);
2116}
2117
2118inline static bool isMinSize(const MachineFunction &MF) {
Sanjay Patel924879a2015-08-04 15:49:57 +00002119 return MF.getFunction()->optForMinSize();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002120}
2121
2122
2123/// Determine whether the callee-saved register saves and restores should
2124/// be generated via inline code. If this function returns "true", inline
2125/// code will be generated. If this function returns "false", additional
2126/// checks are performed, which may still lead to the inline code.
2127bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2128 const CSIVect &CSI) const {
2129 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2130 return true;
2131 if (!isOptSize(MF) && !isMinSize(MF))
2132 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2133 return true;
2134
2135 // Check if CSI only has double registers, and if the registers form
2136 // a contiguous block starting from D8.
2137 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2138 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2139 unsigned R = CSI[i].getReg();
2140 if (!Hexagon::DoubleRegsRegClass.contains(R))
2141 return true;
2142 Regs[R] = true;
2143 }
2144 int F = Regs.find_first();
2145 if (F != Hexagon::D8)
2146 return true;
2147 while (F >= 0) {
2148 int N = Regs.find_next(F);
2149 if (N >= 0 && N != F+1)
2150 return true;
2151 F = N;
2152 }
2153
2154 return false;
2155}
2156
2157
2158bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2159 const CSIVect &CSI) const {
2160 if (shouldInlineCSR(MF, CSI))
2161 return false;
2162 unsigned NumCSI = CSI.size();
2163 if (NumCSI <= 1)
2164 return false;
2165
2166 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2167 : SpillFuncThreshold;
2168 return Threshold < NumCSI;
2169}
2170
2171
2172bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2173 const CSIVect &CSI) const {
2174 if (shouldInlineCSR(MF, CSI))
2175 return false;
2176 unsigned NumCSI = CSI.size();
2177 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2178 : SpillFuncThreshold;
2179 return Threshold < NumCSI;
2180}