blob: d90592df074d223c41639098488bdfc6d9f5d846 [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.
539 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4) {
540 MachineBasicBlock::iterator It = RetI;
541 ++It;
542 // Delete all instructions after the RESTORE (except labels).
543 while (It != MBB.end()) {
544 if (!It->isLabel())
545 It = MBB.erase(It);
546 else
547 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000548 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000549 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000550 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000551
552 // It is possible that the restoring code is a call to a library function.
553 // All of the restore* functions include "deallocframe", so we need to make
554 // sure that we don't add an extra one.
555 bool NeedsDeallocframe = true;
556 if (!MBB.empty() && InsertPt != MBB.begin()) {
557 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
558 unsigned COpc = PrevIt->getOpcode();
559 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4)
560 NeedsDeallocframe = false;
561 }
562
563 if (!NeedsDeallocframe)
564 return;
565 // If the returning instruction is JMPret, replace it with dealloc_return,
566 // otherwise just add deallocframe. The function could be returning via a
567 // tail call.
568 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
569 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
570 return;
571 }
572 unsigned NewOpc = Hexagon::L4_return;
573 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
574 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000575 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000576 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000577}
578
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000579
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000580namespace {
581 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
582 if (!It->isBundle())
583 return It->getOpcode() == Hexagon::S2_allocframe;
584 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000585 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000586 while (++I != End && I->isBundled())
587 if (I->getOpcode() == Hexagon::S2_allocframe)
588 return true;
589 return false;
590 }
591
592 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
593 for (auto &I : B)
594 if (IsAllocFrame(I))
595 return I;
596 return B.end();
597 }
598}
599
600
601void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
602 for (auto &B : MF) {
603 auto AF = FindAllocFrame(B);
604 if (AF == B.end())
605 continue;
606 insertCFIInstructionsAt(B, ++AF);
607 }
608}
609
610
611void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
612 MachineBasicBlock::iterator At) const {
613 MachineFunction &MF = *MBB.getParent();
614 MachineFrameInfo *MFI = MF.getFrameInfo();
615 MachineModuleInfo &MMI = MF.getMMI();
616 auto &HST = MF.getSubtarget<HexagonSubtarget>();
617 auto &HII = *HST.getInstrInfo();
618 auto &HRI = *HST.getRegisterInfo();
619
620 // If CFI instructions have debug information attached, something goes
621 // wrong with the final assembly generation: the prolog_end is placed
622 // in a wrong location.
623 DebugLoc DL;
624 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
625
626 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
627
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000628 if (hasFP(MF)) {
629 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
630 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000631
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000632 // Define CFA via an offset from the value of FP.
633 //
634 // -8 -4 0 (SP)
635 // --+----+----+---------------------
636 // | FP | LR | increasing addresses -->
637 // --+----+----+---------------------
638 // | +-- Old SP (before allocframe)
639 // +-- New FP (after allocframe)
640 //
641 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
642 // MCCFIInstruction::createOffset takes the offset without sign change.
643 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
644 BuildMI(MBB, At, DL, CFID)
645 .addCFIIndex(MMI.addFrameInst(DefCfa));
646 // R31 (return addr) = CFA - 4
647 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
648 BuildMI(MBB, At, DL, CFID)
649 .addCFIIndex(MMI.addFrameInst(OffR31));
650 // R30 (frame ptr) = CFA - 8
651 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
652 BuildMI(MBB, At, DL, CFID)
653 .addCFIIndex(MMI.addFrameInst(OffR30));
654 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000655
656 static unsigned int RegsToMove[] = {
657 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
658 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
659 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
660 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
661 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
662 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
663 Hexagon::NoRegister
664 };
665
666 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
667
668 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
669 unsigned Reg = RegsToMove[i];
670 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
671 return C.getReg() == Reg;
672 };
673 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
674 if (F == CSI.end())
675 continue;
676
677 // Subtract 8 to make room for R30 and R31, which are added above.
678 unsigned FrameReg;
679 int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
680
681 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
682 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
683 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
684 Offset);
685 BuildMI(MBB, At, DL, CFID)
686 .addCFIIndex(MMI.addFrameInst(OffReg));
687 } else {
688 // Split the double regs into subregs, and generate appropriate
689 // cfi_offsets.
690 // The only reason, we are split double regs is, llvm-mc does not
691 // understand paired registers for cfi_offset.
692 // Eg .cfi_offset r1:0, -64
693
694 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
695 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
696 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
697 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
698 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
699 Offset+4);
700 BuildMI(MBB, At, DL, CFID)
701 .addCFIIndex(MMI.addFrameInst(OffHi));
702 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
703 Offset);
704 BuildMI(MBB, At, DL, CFID)
705 .addCFIIndex(MMI.addFrameInst(OffLo));
706 }
707 }
708}
709
710
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000711bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000712 auto &MFI = *MF.getFrameInfo();
713 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
714
715 bool HasFixed = MFI.getNumFixedObjects();
716 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
717 .getLocalFrameObjectCount();
718 bool HasExtraAlign = HRI.needsStackRealignment(MF);
719 bool HasAlloca = MFI.hasVarSizedObjects();
720
721 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
722 // that this shouldn't be required, but doing so now because gcc does and
723 // gdb can't break at the start of the function without it. Will remove if
724 // this turns out to be a gdb bug.
725 //
726 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
727 return true;
728
729 // By default we want to use SP (since it's always there). FP requires
730 // some setup (i.e. ALLOCFRAME).
731 // Fixed and preallocated objects need FP if the distance from them to
732 // the SP is unknown (as is with alloca or aligna).
733 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
734 return true;
735
736 if (MFI.getStackSize() > 0) {
737 if (UseAllocframe)
738 return true;
739 }
740
741 if (MFI.hasCalls() ||
742 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
743 return true;
744
745 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000746}
747
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000748
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000749enum SpillKind {
750 SK_ToMem,
751 SK_FromMem,
752 SK_FromMemTailcall
753};
754
755static const char *
756getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType) {
757 const char * V4SpillToMemoryFunctions[] = {
758 "__save_r16_through_r17",
759 "__save_r16_through_r19",
760 "__save_r16_through_r21",
761 "__save_r16_through_r23",
762 "__save_r16_through_r25",
763 "__save_r16_through_r27" };
764
765 const char * V4SpillFromMemoryFunctions[] = {
766 "__restore_r16_through_r17_and_deallocframe",
767 "__restore_r16_through_r19_and_deallocframe",
768 "__restore_r16_through_r21_and_deallocframe",
769 "__restore_r16_through_r23_and_deallocframe",
770 "__restore_r16_through_r25_and_deallocframe",
771 "__restore_r16_through_r27_and_deallocframe" };
772
773 const char * V4SpillFromMemoryTailcallFunctions[] = {
774 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
775 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
776 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
777 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
778 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
779 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
780 };
781
782 const char **SpillFunc = nullptr;
783
784 switch(SpillType) {
785 case SK_ToMem:
786 SpillFunc = V4SpillToMemoryFunctions;
787 break;
788 case SK_FromMem:
789 SpillFunc = V4SpillFromMemoryFunctions;
790 break;
791 case SK_FromMemTailcall:
792 SpillFunc = V4SpillFromMemoryTailcallFunctions;
793 break;
794 }
795 assert(SpillFunc && "Unknown spill kind");
796
797 // Spill all callee-saved registers up to the highest register used.
798 switch (MaxReg) {
799 case Hexagon::R17:
800 return SpillFunc[0];
801 case Hexagon::R19:
802 return SpillFunc[1];
803 case Hexagon::R21:
804 return SpillFunc[2];
805 case Hexagon::R23:
806 return SpillFunc[3];
807 case Hexagon::R25:
808 return SpillFunc[4];
809 case Hexagon::R27:
810 return SpillFunc[5];
811 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000812 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000813 }
814 return 0;
815}
816
817/// Adds all callee-saved registers up to MaxReg to the instruction.
818static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
819 unsigned MaxReg, bool IsDef) {
820 // Add the callee-saved registers as implicit uses.
821 for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
822 MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
823 Inst->addOperand(ImpUse);
824 }
825}
826
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000827
James Y Knight5567baf2015-08-15 02:32:35 +0000828int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000829 int FI, unsigned &FrameReg) const {
830 auto &MFI = *MF.getFrameInfo();
831 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000832
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000833 int Offset = MFI.getObjectOffset(FI);
834 bool HasAlloca = MFI.hasVarSizedObjects();
835 bool HasExtraAlign = HRI.needsStackRealignment(MF);
836 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000837
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000838 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
839 unsigned AP = 0;
840 if (const MachineInstr *AI = getAlignaInstr(MF))
841 AP = AI->getOperand(0).getReg();
842 unsigned FrameSize = MFI.getStackSize();
843
844 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
845 // Use FP at -O0, except when there are objects with extra alignment.
846 // That additional alignment requirement may cause a pad to be inserted,
847 // which will make it impossible to use FP to access objects located
848 // past the pad.
849 if (NoOpt && !HasExtraAlign)
850 UseFP = true;
851 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
852 // Fixed and preallocated objects will be located before any padding
853 // so FP must be used to access them.
854 UseFP |= (HasAlloca || HasExtraAlign);
855 } else {
856 if (HasAlloca) {
857 if (HasExtraAlign)
858 UseAP = true;
859 else
860 UseFP = true;
861 }
862 }
863
864 // If FP was picked, then there had better be FP.
865 bool HasFP = hasFP(MF);
866 assert((HasFP || !UseFP) && "This function must have frame pointer");
867
868 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
869 // FP/LR. If the base register is used to access an object across these
870 // 8 bytes, then the offset will need to be adjusted by 8.
871 //
872 // After allocframe:
873 // HexagonISelLowering adds 8 to ---+
874 // the offsets of all stack-based |
875 // arguments (*) |
876 // |
877 // getObjectOffset < 0 0 8 getObjectOffset >= 8
878 // ------------------------+-----+------------------------> increasing
879 // <local objects> |FP/LR| <input arguments> addresses
880 // -----------------+------+-----+------------------------>
881 // | |
882 // SP/AP point --+ +-- FP points here (**)
883 // somewhere on
884 // this side of FP/LR
885 //
886 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
887 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
888
889 // The lowering assumes that FP/LR is present, and so the offsets of
890 // the formal arguments start at 8. If FP/LR is not there we need to
891 // reduce the offset by 8.
892 if (Offset > 0 && !HasFP)
893 Offset -= 8;
894
895 if (UseFP)
896 FrameReg = FP;
897 else if (UseAP)
898 FrameReg = AP;
899 else
900 FrameReg = SP;
901
902 // Calculate the actual offset in the instruction. If there is no FP
903 // (in other words, no allocframe), then SP will not be adjusted (i.e.
904 // there will be no SP -= FrameSize), so the frame size should not be
905 // added to the calculated offset.
906 int RealOffset = Offset;
907 if (!UseFP && !UseAP && HasFP)
908 RealOffset = FrameSize+Offset;
909 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000910}
911
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000912
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000913bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
914 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
915 if (CSI.empty())
916 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000917
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000918 MachineBasicBlock::iterator MI = MBB.begin();
919 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000920 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000921
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000922 if (useSpillFunction(MF, CSI)) {
923 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
924 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem);
925 // Call spill function.
926 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
927 MachineInstr *SaveRegsCall =
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000928 BuildMI(MBB, MI, DL, HII.get(Hexagon::SAVE_REGISTERS_CALL_V4))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000929 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000930 // Add callee-saved registers as use.
931 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
932 // Add live in registers.
933 for (unsigned I = 0; I < CSI.size(); ++I)
934 MBB.addLiveIn(CSI[I].getReg());
935 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000936 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000937
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000938 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000939 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000940 // Add live in registers. We treat eh_return callee saved register r0 - r3
941 // specially. They are not really callee saved registers as they are not
942 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000943 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
944 int FI = CSI[i].getFrameIdx();
945 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000946 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000947 if (IsKill)
948 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000949 }
950 return true;
951}
952
953
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000954bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
955 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
956 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000957 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000958
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000959 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
960 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000961 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000962
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000963 if (useRestoreFunction(MF, CSI)) {
964 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
965 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
966 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
967 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000968
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000969 // Call spill function.
970 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
971 : MBB.getLastNonDebugInstr()->getDebugLoc();
972 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000973
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000974 if (HasTC) {
975 unsigned ROpc = Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000976 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000977 .addExternalSymbol(RestoreFn);
978 } else {
979 // The block has a return.
980 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
981 assert(It->isReturn() && std::next(It) == MBB.end());
982 unsigned ROpc = Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000983 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000984 .addExternalSymbol(RestoreFn);
985 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000986 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000987 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000988 addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
989 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000990 }
991
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000992 for (unsigned i = 0; i < CSI.size(); ++i) {
993 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000994 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
995 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000996 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000997 }
998 return true;
999}
1000
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001001
1002void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1003 MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001004 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001005 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001006 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001007 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1008 "Cannot handle this call frame pseudo instruction");
Eli Bendersky8da87162013-02-21 20:05:00 +00001009 MBB.erase(I);
1010}
1011
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001012
1013void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1014 MachineFunction &MF, RegScavenger *RS) const {
1015 // If this function has uses aligned stack and also has variable sized stack
1016 // objects, then we need to map all spill slots to fixed positions, so that
1017 // they can be accessed through FP. Otherwise they would have to be accessed
1018 // via AP, which may not be available at the particular place in the program.
1019 MachineFrameInfo *MFI = MF.getFrameInfo();
1020 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001021 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001022
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001023 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001024 return;
1025
1026 unsigned LFS = MFI->getLocalFrameSize();
1027 int Offset = -LFS;
1028 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1029 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1030 continue;
1031 int S = MFI->getObjectSize(i);
1032 LFS += S;
1033 Offset -= S;
1034 MFI->mapLocalFrameObject(i, Offset);
1035 }
1036
1037 MFI->setLocalFrameSize(LFS);
1038 unsigned A = MFI->getLocalFrameMaxAlign();
1039 assert(A <= 8 && "Unexpected local frame alignment");
1040 if (A == 0)
1041 MFI->setLocalFrameMaxAlign(8);
1042 MFI->setUseLocalStackAllocationBlock(true);
1043}
1044
1045/// Returns true if there is no caller saved registers available.
1046static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1047 const HexagonRegisterInfo &HRI) {
1048 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001049 BitVector Reserved = HRI.getReservedRegs(MF);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001050
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001051 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1052 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1053 if (MRI.isPhysRegUsed(*AI))
1054 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001055 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001056 };
1057
1058 // Check for an unused caller-saved register.
1059 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF); *P; ++P)
1060 if (!IsUsed(*P))
1061 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001062 // All caller-saved registers are used.
1063 return true;
1064}
1065
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001066
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001067#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001068static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001069 dbgs() << '{';
1070 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1071 unsigned R = x;
1072 dbgs() << ' ' << PrintReg(R, &TRI);
1073 }
1074 dbgs() << " }";
1075}
1076#endif
1077
1078
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001079bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1080 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001081 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001082 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001083 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001084 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001085
1086 // Generate a set of unique, callee-saved registers (SRegs), where each
1087 // register in the set is maximal in terms of sub-/super-register relation,
1088 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1089
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001090 // (1) For each callee-saved register, add that register and all of its
1091 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001092 DEBUG(dbgs() << "Initial CS registers: {");
1093 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1094 unsigned R = CSI[i].getReg();
1095 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1096 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1097 SRegs[*SR] = true;
1098 }
1099 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001100 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001101
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001102 // (2) For each reserved register, remove that register and all of its
1103 // sub- and super-registers from SRegs.
1104 BitVector Reserved = TRI->getReservedRegs(MF);
1105 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1106 unsigned R = x;
1107 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1108 SRegs[*SR] = false;
1109 }
1110 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1111 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1112
1113 // (3) Collect all registers that have at least one sub-register in SRegs,
1114 // and also have no sub-registers that are reserved. These will be the can-
1115 // didates for saving as a whole instead of their individual sub-registers.
1116 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1117 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001118 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1119 unsigned R = x;
1120 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1121 TmpSup[*SR] = true;
1122 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001123 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1124 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001125 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1126 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001127 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001128 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001129 break;
1130 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001131 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001132 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001133
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001134 // (4) Include all super-registers found in (3) into SRegs.
1135 SRegs |= TmpSup;
1136 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001137
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001138 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001139 // remove R from SRegs.
1140 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1141 unsigned R = x;
1142 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1143 if (!SRegs[*SR])
1144 continue;
1145 SRegs[R] = false;
1146 break;
1147 }
1148 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001149 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001150
1151 // Now, for each register that has a fixed stack slot, create the stack
1152 // object for it.
1153 CSI.clear();
1154
1155 typedef TargetFrameLowering::SpillSlot SpillSlot;
1156 unsigned NumFixed;
1157 int MinOffset = 0; // CS offsets are negative.
1158 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1159 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1160 if (!SRegs[S->Reg])
1161 continue;
1162 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1163 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1164 MinOffset = std::min(MinOffset, S->Offset);
1165 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1166 SRegs[S->Reg] = false;
1167 }
1168
1169 // There can be some registers that don't have fixed slots. For example,
1170 // we need to store R0-R3 in functions with exception handling. For each
1171 // such register, create a non-fixed stack object.
1172 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1173 unsigned R = x;
1174 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1175 int Off = MinOffset - RC->getSize();
1176 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1177 assert(isPowerOf2_32(Align));
1178 Off &= -Align;
1179 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1180 MinOffset = std::min(MinOffset, Off);
1181 CSI.push_back(CalleeSavedInfo(R, FI));
1182 SRegs[R] = false;
1183 }
1184
1185 DEBUG({
1186 dbgs() << "CS information: {";
1187 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1188 int FI = CSI[i].getFrameIdx();
1189 int Off = MFI->getObjectOffset(FI);
1190 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1191 if (Off >= 0)
1192 dbgs() << '+';
1193 dbgs() << Off;
1194 }
1195 dbgs() << " }\n";
1196 });
1197
1198#ifndef NDEBUG
1199 // Verify that all registers were handled.
1200 bool MissedReg = false;
1201 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1202 unsigned R = x;
1203 dbgs() << PrintReg(R, TRI) << ' ';
1204 MissedReg = true;
1205 }
1206 if (MissedReg)
1207 llvm_unreachable("...there are unhandled callee-saved registers!");
1208#endif
1209
1210 return true;
1211}
1212
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001213
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001214bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1215 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1216 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1217 MachineInstr *MI = &*It;
1218 DebugLoc DL = MI->getDebugLoc();
1219 unsigned DstR = MI->getOperand(0).getReg();
1220 unsigned SrcR = MI->getOperand(1).getReg();
1221 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1222 !Hexagon::ModRegsRegClass.contains(SrcR))
1223 return false;
1224
1225 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1226 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1227 .addOperand(MI->getOperand(1));
1228 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1229 .addReg(TmpR, RegState::Kill);
1230
1231 NewRegs.push_back(TmpR);
1232 B.erase(It);
1233 return true;
1234}
1235
1236bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1237 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1238 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1239 MachineInstr *MI = &*It;
1240 DebugLoc DL = MI->getDebugLoc();
1241 unsigned Opc = MI->getOpcode();
1242 unsigned SrcR = MI->getOperand(2).getReg();
1243 bool IsKill = MI->getOperand(2).isKill();
1244
1245 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1246 int FI = MI->getOperand(0).getIndex();
1247
1248 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1249 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1250 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1251 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1252 : Hexagon::A2_tfrcrr;
1253 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1254 .addReg(SrcR, getKillRegState(IsKill));
1255
1256 // S2_storeri_io FI, 0, TmpR
1257 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1258 .addFrameIndex(FI)
1259 .addImm(0)
1260 .addReg(TmpR, RegState::Kill)
1261 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1262
1263 NewRegs.push_back(TmpR);
1264 B.erase(It);
1265 return true;
1266}
1267
1268bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1269 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1270 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1271 MachineInstr *MI = &*It;
1272 DebugLoc DL = MI->getDebugLoc();
1273 unsigned Opc = MI->getOpcode();
1274 unsigned DstR = MI->getOperand(0).getReg();
1275
1276 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1277 int FI = MI->getOperand(1).getIndex();
1278
1279 // TmpR = L2_loadri_io FI, 0
1280 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1281 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1282 .addFrameIndex(FI)
1283 .addImm(0)
1284 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1285
1286 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1287 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1288 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1289 : Hexagon::A2_tfrrcr;
1290 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1291 .addReg(TmpR, RegState::Kill);
1292
1293 NewRegs.push_back(TmpR);
1294 B.erase(It);
1295 return true;
1296}
1297
1298
1299bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1300 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1301 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1302 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1303 MachineInstr *MI = &*It;
1304 DebugLoc DL = MI->getDebugLoc();
1305 unsigned SrcR = MI->getOperand(2).getReg();
1306 bool IsKill = MI->getOperand(2).isKill();
1307
1308 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1309 int FI = MI->getOperand(0).getIndex();
1310
1311 bool Is128B = HST.useHVXDblOps();
1312 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1313 : &Hexagon::VectorRegs128BRegClass;
1314
1315 // Insert transfer to general vector register.
1316 // TmpR0 = A2_tfrsi 0x01010101
1317 // TmpR1 = V6_vandqrt Qx, TmpR0
1318 // store FI, 0, TmpR1
1319 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1320 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1321
1322 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1323 .addImm(0x01010101);
1324
1325 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1326 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1327 .addReg(SrcR, getKillRegState(IsKill))
1328 .addReg(TmpR0, RegState::Kill);
1329
1330 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1331 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1332 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1333
1334 NewRegs.push_back(TmpR0);
1335 NewRegs.push_back(TmpR1);
1336 B.erase(It);
1337 return true;
1338}
1339
1340bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1341 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1342 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1343 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1344 MachineInstr *MI = &*It;
1345 DebugLoc DL = MI->getDebugLoc();
1346 unsigned DstR = MI->getOperand(0).getReg();
1347
1348 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1349 int FI = MI->getOperand(1).getIndex();
1350
1351 bool Is128B = HST.useHVXDblOps();
1352 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1353 : &Hexagon::VectorRegs128BRegClass;
1354
1355 // TmpR0 = A2_tfrsi 0x01010101
1356 // TmpR1 = load FI, 0
1357 // DstR = V6_vandvrt TmpR1, TmpR0
1358 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1359 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1360
1361 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1362 .addImm(0x01010101);
1363 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1364 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1365 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1366
1367 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1368 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1369 .addReg(TmpR1, RegState::Kill)
1370 .addReg(TmpR0, RegState::Kill);
1371
1372 NewRegs.push_back(TmpR0);
1373 NewRegs.push_back(TmpR1);
1374 B.erase(It);
1375 return true;
1376}
1377
1378bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1379 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1380 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1381 MachineFunction &MF = *B.getParent();
1382 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1383 auto &MFI = *MF.getFrameInfo();
1384 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1385 MachineInstr *MI = &*It;
1386 DebugLoc DL = MI->getDebugLoc();
1387
1388 unsigned SrcR = MI->getOperand(2).getReg();
1389 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1390 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1391 bool IsKill = MI->getOperand(2).isKill();
1392
1393 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1394 int FI = MI->getOperand(0).getIndex();
1395
1396 bool Is128B = HST.useHVXDblOps();
1397 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1398 : &Hexagon::VectorRegs128BRegClass;
1399 unsigned Size = RC->getSize();
1400 unsigned NeedAlign = RC->getAlignment();
1401 unsigned HasAlign = MFI.getObjectAlignment(FI);
1402 unsigned StoreOpc;
1403
1404 // Store low part.
1405 if (NeedAlign <= HasAlign)
1406 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1407 else
1408 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1409
1410 BuildMI(B, It, DL, HII.get(StoreOpc))
1411 .addFrameIndex(FI)
1412 .addImm(0)
1413 .addReg(SrcLo, getKillRegState(IsKill))
1414 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1415
1416 // Load high part.
1417 if (NeedAlign <= MinAlign(HasAlign, Size))
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(Size)
1425 .addReg(SrcHi, getKillRegState(IsKill))
1426 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1427
1428 B.erase(It);
1429 return true;
1430}
1431
1432bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1433 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1434 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1435 MachineFunction &MF = *B.getParent();
1436 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1437 auto &MFI = *MF.getFrameInfo();
1438 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1439 MachineInstr *MI = &*It;
1440 DebugLoc DL = MI->getDebugLoc();
1441
1442 unsigned DstR = MI->getOperand(0).getReg();
1443 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1444 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1445
1446 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1447 int FI = MI->getOperand(1).getIndex();
1448
1449 bool Is128B = HST.useHVXDblOps();
1450 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1451 : &Hexagon::VectorRegs128BRegClass;
1452 unsigned Size = RC->getSize();
1453 unsigned NeedAlign = RC->getAlignment();
1454 unsigned HasAlign = MFI.getObjectAlignment(FI);
1455 unsigned LoadOpc;
1456
1457 // Load low part.
1458 if (NeedAlign <= HasAlign)
1459 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1460 else
1461 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1462
1463 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1464 .addFrameIndex(FI)
1465 .addImm(0)
1466 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1467
1468 // Load high part.
1469 if (NeedAlign <= MinAlign(HasAlign, Size))
1470 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1471 else
1472 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1473
1474 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1475 .addFrameIndex(FI)
1476 .addImm(Size)
1477 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1478
1479 B.erase(It);
1480 return true;
1481}
1482
1483bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1484 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1485 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1486 MachineFunction &MF = *B.getParent();
1487 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1488 auto &MFI = *MF.getFrameInfo();
1489 MachineInstr *MI = &*It;
1490 DebugLoc DL = MI->getDebugLoc();
1491
1492 unsigned SrcR = MI->getOperand(2).getReg();
1493 bool IsKill = MI->getOperand(2).isKill();
1494
1495 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1496 int FI = MI->getOperand(0).getIndex();
1497
1498 bool Is128B = HST.useHVXDblOps();
1499 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1500 : &Hexagon::VectorRegs128BRegClass;
1501
1502 unsigned NeedAlign = RC->getAlignment();
1503 unsigned HasAlign = MFI.getObjectAlignment(FI);
1504 unsigned StoreOpc;
1505
1506 if (NeedAlign <= HasAlign)
1507 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1508 else
1509 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1510
1511 BuildMI(B, It, DL, HII.get(StoreOpc))
1512 .addFrameIndex(FI)
1513 .addImm(0)
1514 .addReg(SrcR, getKillRegState(IsKill))
1515 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1516
1517 B.erase(It);
1518 return true;
1519}
1520
1521bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1522 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1523 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1524 MachineFunction &MF = *B.getParent();
1525 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1526 auto &MFI = *MF.getFrameInfo();
1527 MachineInstr *MI = &*It;
1528 DebugLoc DL = MI->getDebugLoc();
1529
1530 unsigned DstR = MI->getOperand(0).getReg();
1531
1532 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1533 int FI = MI->getOperand(1).getIndex();
1534
1535 bool Is128B = HST.useHVXDblOps();
1536 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1537 : &Hexagon::VectorRegs128BRegClass;
1538
1539 unsigned NeedAlign = RC->getAlignment();
1540 unsigned HasAlign = MFI.getObjectAlignment(FI);
1541 unsigned LoadOpc;
1542
1543 if (NeedAlign <= HasAlign)
1544 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1545 else
1546 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1547
1548 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1549 .addFrameIndex(FI)
1550 .addImm(0)
1551 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1552
1553 B.erase(It);
1554 return true;
1555}
1556
1557
1558bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1559 SmallVectorImpl<unsigned> &NewRegs) const {
1560 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001561 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001562 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001563 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001564
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001565 for (auto &B : MF) {
1566 // Traverse the basic block.
1567 MachineBasicBlock::iterator NextI;
1568 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1569 MachineInstr *MI = &*I;
1570 NextI = std::next(I);
1571 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001572
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001573 switch (Opc) {
1574 case TargetOpcode::COPY:
1575 Changed = expandCopy(B, I, MRI, HII, NewRegs);
1576 break;
1577 case Hexagon::STriw_pred:
1578 case Hexagon::STriw_mod:
1579 Changed = expandStoreInt(B, I, MRI, HII, NewRegs);
1580 break;
1581 case Hexagon::LDriw_pred:
1582 case Hexagon::LDriw_mod:
1583 Changed = expandLoadInt(B, I, MRI, HII, NewRegs);
1584 break;
1585 case Hexagon::STriq_pred_V6:
1586 case Hexagon::STriq_pred_V6_128B:
1587 Changed = expandStoreVecPred(B, I, MRI, HII, NewRegs);
1588 break;
1589 case Hexagon::LDriq_pred_V6:
1590 case Hexagon::LDriq_pred_V6_128B:
1591 Changed = expandLoadVecPred(B, I, MRI, HII, NewRegs);
1592 break;
1593 case Hexagon::LDrivv_pseudo_V6:
1594 case Hexagon::LDrivv_pseudo_V6_128B:
1595 Changed = expandLoadVec2(B, I, MRI, HII, NewRegs);
1596 break;
1597 case Hexagon::STrivv_pseudo_V6:
1598 case Hexagon::STrivv_pseudo_V6_128B:
1599 Changed = expandStoreVec2(B, I, MRI, HII, NewRegs);
1600 break;
1601 case Hexagon::STriv_pseudo_V6:
1602 case Hexagon::STriv_pseudo_V6_128B:
1603 Changed = expandStoreVec(B, I, MRI, HII, NewRegs);
1604 break;
1605 case Hexagon::LDriv_pseudo_V6:
1606 case Hexagon::LDriv_pseudo_V6_128B:
1607 Changed = expandLoadVec(B, I, MRI, HII, NewRegs);
1608 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001609 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001610 }
1611 }
1612
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001613 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001614}
1615
1616
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001617void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1618 BitVector &SavedRegs,
1619 RegScavenger *RS) const {
1620 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1621 auto &HRI = *HST.getRegisterInfo();
1622
1623 SavedRegs.resize(HRI.getNumRegs());
1624
1625 // If we have a function containing __builtin_eh_return we want to spill and
1626 // restore all callee saved registers. Pretend that they are used.
1627 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1628 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1629 SavedRegs.set(*R);
1630
1631 // Replace predicate register pseudo spill code.
1632 SmallVector<unsigned,8> NewRegs;
1633 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001634 if (OptimizeSpillSlots)
1635 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001636
1637 // We need to reserve a a spill slot if scavenging could potentially require
1638 // spilling a scavenged register.
1639 if (!NewRegs.empty() && needToReserveScavengingSpillSlots(MF, HRI)) {
1640 MachineRegisterInfo &MRI = MF.getRegInfo();
1641 SetVector<const TargetRegisterClass*> SpillRCs;
1642 for (unsigned VR : NewRegs)
1643 SpillRCs.insert(MRI.getRegClass(VR));
1644
1645 MachineFrameInfo &MFI = *MF.getFrameInfo();
1646 const TargetRegisterClass &IntRC = Hexagon::IntRegsRegClass;
1647 if (SpillRCs.count(&IntRC)) {
1648 for (int i = 0; i < NumberScavengerSlots; i++) {
1649 int NewFI = MFI.CreateSpillStackObject(IntRC.getSize(),
1650 IntRC.getAlignment());
1651 RS->addScavengingFrameIndex(NewFI);
1652 }
1653 }
1654 for (auto *RC : SpillRCs) {
1655 if (RC == &IntRC)
1656 continue;
1657 int NewFI = MFI.CreateSpillStackObject(RC->getSize(), RC->getAlignment());
1658 RS->addScavengingFrameIndex(NewFI);
1659 }
1660 }
1661
1662 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1663}
1664
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001665
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001666unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1667 HexagonBlockRanges::IndexRange &FIR,
1668 HexagonBlockRanges::InstrIndexMap &IndexMap,
1669 HexagonBlockRanges::RegToRangeMap &DeadMap,
1670 const TargetRegisterClass *RC) const {
1671 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1672 auto &MRI = MF.getRegInfo();
1673
1674 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1675 auto F = DeadMap.find({Reg,0});
1676 if (F == DeadMap.end())
1677 return false;
1678 for (auto &DR : F->second)
1679 if (DR.contains(FIR))
1680 return true;
1681 return false;
1682 };
1683
1684 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1685 bool Dead = true;
1686 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1687 if (isDead(R.Reg))
1688 continue;
1689 Dead = false;
1690 break;
1691 }
1692 if (Dead)
1693 return Reg;
1694 }
1695 return 0;
1696}
1697
1698void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1699 SmallVectorImpl<unsigned> &VRegs) const {
1700 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1701 auto &HII = *HST.getInstrInfo();
1702 auto &HRI = *HST.getRegisterInfo();
1703 auto &MRI = MF.getRegInfo();
1704 HexagonBlockRanges HBR(MF);
1705
1706 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1707 BlockIndexMap;
1708 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1709 BlockRangeMap;
1710 typedef HexagonBlockRanges::IndexType IndexType;
1711
1712 struct SlotInfo {
1713 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001714 unsigned Size;
1715 const TargetRegisterClass *RC;
1716
1717 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001718 };
1719
1720 BlockIndexMap BlockIndexes;
1721 SmallSet<int,4> BadFIs;
1722 std::map<int,SlotInfo> FIRangeMap;
1723
1724 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1725 -> const TargetRegisterClass* {
1726 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1727 assert(R.Sub == 0);
1728 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1729 auto *RCR = MRI.getRegClass(R.Reg);
1730 if (R.Sub == 0)
1731 return RCR;
1732 unsigned PR = *RCR->begin();
1733 R.Reg = HRI.getSubReg(PR, R.Sub);
1734 }
1735 return HRI.getMinimalPhysRegClass(R.Reg);
1736 };
1737 // Accumulate register classes: get a common class for a pre-existing
1738 // class HaveRC and a new class NewRC. Return nullptr if a common class
1739 // cannot be found, otherwise return the resulting class. If HaveRC is
1740 // nullptr, assume that it is still unset.
1741 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1742 const TargetRegisterClass *NewRC)
1743 -> const TargetRegisterClass* {
1744 if (HaveRC == nullptr || HaveRC == NewRC)
1745 return NewRC;
1746 // Different classes, both non-null. Pick the more general one.
1747 if (HaveRC->hasSubClassEq(NewRC))
1748 return HaveRC;
1749 if (NewRC->hasSubClassEq(HaveRC))
1750 return NewRC;
1751 return nullptr;
1752 };
1753
1754 // Scan all blocks in the function. Check all occurrences of frame indexes,
1755 // and collect relevant information.
1756 for (auto &B : MF) {
1757 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001758 // Emplace appears not to be supported in gcc 4.7.2-4.
1759 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001760 auto P = BlockIndexes.insert(
1761 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001762 auto &IndexMap = P.first->second;
1763 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1764 << IndexMap << '\n');
1765
1766 for (auto &In : B) {
1767 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001768 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1769 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001770 if (Load && Store) {
1771 // If it's both a load and a store, then we won't handle it.
1772 BadFIs.insert(LFI);
1773 BadFIs.insert(SFI);
1774 continue;
1775 }
1776 // Check for register classes of the register used as the source for
1777 // the store, and the register used as the destination for the load.
1778 // Also, only accept base+imm_offset addressing modes. Other addressing
1779 // modes can have side-effects (post-increments, etc.). For stack
1780 // slots they are very unlikely, so there is not much loss due to
1781 // this restriction.
1782 if (Load || Store) {
1783 int TFI = Load ? LFI : SFI;
1784 unsigned AM = HII.getAddrMode(&In);
1785 SlotInfo &SI = FIRangeMap[TFI];
1786 bool Bad = (AM != HexagonII::BaseImmOffset);
1787 if (!Bad) {
1788 // If the addressing mode is ok, check the register class.
1789 const TargetRegisterClass *RC = nullptr;
1790 if (Load) {
1791 MachineOperand &DataOp = In.getOperand(0);
1792 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1793 } else {
1794 MachineOperand &DataOp = In.getOperand(2);
1795 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1796 }
1797 RC = getCommonRC(SI.RC, RC);
1798 if (RC == nullptr)
1799 Bad = true;
1800 else
1801 SI.RC = RC;
1802 }
1803 if (!Bad) {
1804 // Check sizes.
1805 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1806 if (SI.Size != 0 && SI.Size != S)
1807 Bad = true;
1808 else
1809 SI.Size = S;
1810 }
1811 if (Bad)
1812 BadFIs.insert(TFI);
1813 }
1814
1815 // Locate uses of frame indices.
1816 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1817 const MachineOperand &Op = In.getOperand(i);
1818 if (!Op.isFI())
1819 continue;
1820 int FI = Op.getIndex();
1821 // Make sure that the following operand is an immediate and that
1822 // it is 0. This is the offset in the stack object.
1823 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1824 In.getOperand(i+1).getImm() != 0)
1825 BadFIs.insert(FI);
1826 if (BadFIs.count(FI))
1827 continue;
1828
1829 IndexType Index = IndexMap.getIndex(&In);
1830 if (Load) {
1831 if (LastStore[FI] == IndexType::None)
1832 LastStore[FI] = IndexType::Entry;
1833 LastLoad[FI] = Index;
1834 } else if (Store) {
1835 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1836 if (LastStore[FI] != IndexType::None)
1837 RL.add(LastStore[FI], LastLoad[FI], false, false);
1838 else if (LastLoad[FI] != IndexType::None)
1839 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1840 LastLoad[FI] = IndexType::None;
1841 LastStore[FI] = Index;
1842 } else {
1843 BadFIs.insert(FI);
1844 }
1845 }
1846 }
1847
1848 for (auto &I : LastLoad) {
1849 IndexType LL = I.second;
1850 if (LL == IndexType::None)
1851 continue;
1852 auto &RL = FIRangeMap[I.first].Map[&B];
1853 IndexType &LS = LastStore[I.first];
1854 if (LS != IndexType::None)
1855 RL.add(LS, LL, false, false);
1856 else
1857 RL.add(IndexType::Entry, LL, false, false);
1858 LS = IndexType::None;
1859 }
1860 for (auto &I : LastStore) {
1861 IndexType LS = I.second;
1862 if (LS == IndexType::None)
1863 continue;
1864 auto &RL = FIRangeMap[I.first].Map[&B];
1865 RL.add(LS, IndexType::None, false, false);
1866 }
1867 }
1868
1869 DEBUG({
1870 for (auto &P : FIRangeMap) {
1871 dbgs() << "fi#" << P.first;
1872 if (BadFIs.count(P.first))
1873 dbgs() << " (bad)";
1874 dbgs() << " RC: ";
1875 if (P.second.RC != nullptr)
1876 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1877 else
1878 dbgs() << "<null>\n";
1879 for (auto &R : P.second.Map)
1880 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1881 }
1882 });
1883
1884 // When a slot is loaded from in a block without being stored to in the
1885 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1886 // consider this slot to be live-on-exit from all blocks.
1887 SmallSet<int,4> LoxFIs;
1888
1889 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1890
1891 for (auto &P : FIRangeMap) {
1892 // P = pair(FI, map: BB->RangeList)
1893 if (BadFIs.count(P.first))
1894 continue;
1895 for (auto &B : MF) {
1896 auto F = P.second.Map.find(&B);
1897 // F = pair(BB, RangeList)
1898 if (F == P.second.Map.end() || F->second.empty())
1899 continue;
1900 HexagonBlockRanges::IndexRange &IR = F->second.front();
1901 if (IR.start() == IndexType::Entry)
1902 LoxFIs.insert(P.first);
1903 BlockFIMap[&B].push_back(P.first);
1904 }
1905 }
1906
1907 DEBUG({
1908 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1909 for (auto &P : BlockFIMap) {
1910 auto &FIs = P.second;
1911 if (FIs.empty())
1912 continue;
1913 dbgs() << " BB#" << P.first->getNumber() << ": {";
1914 for (auto I : FIs) {
1915 dbgs() << " fi#" << I;
1916 if (LoxFIs.count(I))
1917 dbgs() << '*';
1918 }
1919 dbgs() << " }\n";
1920 }
1921 });
1922
1923 // eliminate loads, when all loads eliminated, eliminate all stores.
1924 for (auto &B : MF) {
1925 auto F = BlockIndexes.find(&B);
1926 assert(F != BlockIndexes.end());
1927 HexagonBlockRanges::InstrIndexMap &IM = F->second;
1928 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
1929 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
1930 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
1931 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
1932
1933 for (auto FI : BlockFIMap[&B]) {
1934 if (BadFIs.count(FI))
1935 continue;
1936 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
1937 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1938 for (auto &Range : RL) {
1939 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
1940 if (!IndexType::isInstr(Range.start()) ||
1941 !IndexType::isInstr(Range.end()))
1942 continue;
1943 MachineInstr *SI = IM.getInstr(Range.start());
1944 MachineInstr *EI = IM.getInstr(Range.end());
1945 assert(SI->mayStore() && "Unexpected start instruction");
1946 assert(EI->mayLoad() && "Unexpected end instruction");
1947 MachineOperand &SrcOp = SI->getOperand(2);
1948
1949 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
1950 SrcOp.getSubReg() };
1951 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
1952 // The this-> is needed to unconfuse MSVC.
1953 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
1954 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
1955 if (FoundR == 0)
1956 continue;
1957
1958 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
1959 MachineBasicBlock::iterator StartIt = SI, NextIt;
1960 MachineInstr *CopyIn = nullptr;
1961 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
1962 DebugLoc DL = SI->getDebugLoc();
1963 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
1964 .addOperand(SrcOp);
1965 }
1966
1967 ++StartIt;
1968 // Check if this is a last store and the FI is live-on-exit.
1969 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
1970 // Update store's source register.
1971 if (unsigned SR = SrcOp.getSubReg())
1972 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
1973 else
1974 SrcOp.setReg(FoundR);
1975 SrcOp.setSubReg(0);
1976 // We are keeping this register live.
1977 SrcOp.setIsKill(false);
1978 } else {
1979 B.erase(SI);
1980 IM.replaceInstr(SI, CopyIn);
1981 }
1982
1983 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
1984 for (auto It = StartIt; It != EndIt; It = NextIt) {
1985 MachineInstr *MI = &*It;
1986 NextIt = std::next(It);
1987 int TFI;
1988 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
1989 continue;
1990 unsigned DstR = MI->getOperand(0).getReg();
1991 assert(MI->getOperand(0).getSubReg() == 0);
1992 MachineInstr *CopyOut = nullptr;
1993 if (DstR != FoundR) {
1994 DebugLoc DL = MI->getDebugLoc();
1995 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
1996 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
1997 unsigned CopyOpc = TargetOpcode::COPY;
1998 if (HII.isSignExtendingLoad(MI))
1999 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2000 else if (HII.isZeroExtendingLoad(MI))
2001 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2002 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2003 .addReg(FoundR, getKillRegState(MI == EI));
2004 }
2005 IM.replaceInstr(MI, CopyOut);
2006 B.erase(It);
2007 }
2008
2009 // Update the dead map.
2010 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2011 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2012 DM[RR].subtract(Range);
2013 } // for Range in range list
2014 }
2015 }
2016}
2017
2018
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002019void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002020 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002021 MachineBasicBlock &MB = *AI->getParent();
2022 DebugLoc DL = AI->getDebugLoc();
2023 unsigned A = AI->getOperand(2).getImm();
2024
2025 // Have
2026 // Rd = alloca Rs, #A
2027 //
2028 // If Rs and Rd are different registers, use this sequence:
2029 // Rd = sub(r29, Rs)
2030 // r29 = sub(r29, Rs)
2031 // Rd = and(Rd, #-A) ; if necessary
2032 // r29 = and(r29, #-A) ; if necessary
2033 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2034 // otherwise, do
2035 // Rd = sub(r29, Rs)
2036 // Rd = and(Rd, #-A) ; if necessary
2037 // r29 = Rd
2038 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2039
2040 MachineOperand &RdOp = AI->getOperand(0);
2041 MachineOperand &RsOp = AI->getOperand(1);
2042 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2043
2044 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002045 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002046 .addReg(SP)
2047 .addReg(Rs);
2048 if (Rs != Rd) {
2049 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002050 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002051 .addReg(SP)
2052 .addReg(Rs);
2053 }
2054 if (A > 8) {
2055 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002056 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002057 .addReg(Rd)
2058 .addImm(-int64_t(A));
2059 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002060 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002061 .addReg(SP)
2062 .addImm(-int64_t(A));
2063 }
2064 if (Rs == Rd) {
2065 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002066 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002067 .addReg(Rd);
2068 }
2069 if (CF > 0) {
2070 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002071 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002072 .addReg(Rd)
2073 .addImm(CF);
2074 }
2075}
2076
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002077
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002078bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2079 const MachineFrameInfo *MFI = MF.getFrameInfo();
2080 if (!MFI->hasVarSizedObjects())
2081 return false;
2082 unsigned MaxA = MFI->getMaxAlignment();
2083 if (MaxA <= getStackAlignment())
2084 return false;
2085 return true;
2086}
2087
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002088
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002089const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2090 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002091 for (auto &B : MF)
2092 for (auto &I : B)
2093 if (I.getOpcode() == Hexagon::ALIGNA)
2094 return &I;
2095 return nullptr;
2096}
2097
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002098
Sanjay Patel924879a2015-08-04 15:49:57 +00002099// FIXME: Use Function::optForSize().
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002100inline static bool isOptSize(const MachineFunction &MF) {
2101 AttributeSet AF = MF.getFunction()->getAttributes();
2102 return AF.hasAttribute(AttributeSet::FunctionIndex,
2103 Attribute::OptimizeForSize);
2104}
2105
2106inline static bool isMinSize(const MachineFunction &MF) {
Sanjay Patel924879a2015-08-04 15:49:57 +00002107 return MF.getFunction()->optForMinSize();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002108}
2109
2110
2111/// Determine whether the callee-saved register saves and restores should
2112/// be generated via inline code. If this function returns "true", inline
2113/// code will be generated. If this function returns "false", additional
2114/// checks are performed, which may still lead to the inline code.
2115bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2116 const CSIVect &CSI) const {
2117 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2118 return true;
2119 if (!isOptSize(MF) && !isMinSize(MF))
2120 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2121 return true;
2122
2123 // Check if CSI only has double registers, and if the registers form
2124 // a contiguous block starting from D8.
2125 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2126 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2127 unsigned R = CSI[i].getReg();
2128 if (!Hexagon::DoubleRegsRegClass.contains(R))
2129 return true;
2130 Regs[R] = true;
2131 }
2132 int F = Regs.find_first();
2133 if (F != Hexagon::D8)
2134 return true;
2135 while (F >= 0) {
2136 int N = Regs.find_next(F);
2137 if (N >= 0 && N != F+1)
2138 return true;
2139 F = N;
2140 }
2141
2142 return false;
2143}
2144
2145
2146bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2147 const CSIVect &CSI) const {
2148 if (shouldInlineCSR(MF, CSI))
2149 return false;
2150 unsigned NumCSI = CSI.size();
2151 if (NumCSI <= 1)
2152 return false;
2153
2154 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2155 : SpillFuncThreshold;
2156 return Threshold < NumCSI;
2157}
2158
2159
2160bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2161 const CSIVect &CSI) const {
2162 if (shouldInlineCSR(MF, CSI))
2163 return false;
2164 unsigned NumCSI = CSI.size();
2165 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2166 : SpillFuncThreshold;
2167 return Threshold < NumCSI;
2168}