blob: 43ff10b98cb0916213a8473f872f4b9851d48c98 [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 Parzyszeka5bd29542016-05-16 18:02:28 +0000128static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000129 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
130 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000131
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000132static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000133 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
134 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000135
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000136static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000137 cl::Hidden, cl::desc("Specify Os spill func threshold"),
138 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000139
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000140static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
141 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
142 cl::init(false), cl::ZeroOrMore);
143
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000144static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
145 cl::init(true), cl::Hidden, cl::ZeroOrMore,
146 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000147
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000148static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
149 cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
150 "shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000151
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000152static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
153 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
154 cl::init(false), cl::ZeroOrMore);
155
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000156static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
157 cl::Hidden, cl::desc("Use allocframe more conservatively"));
158
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000159static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
160 cl::init(true), cl::desc("Optimize spill slots"));
161
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000162
163namespace llvm {
164 void initializeHexagonCallFrameInformationPass(PassRegistry&);
165 FunctionPass *createHexagonCallFrameInformation();
166}
167
168namespace {
169 class HexagonCallFrameInformation : public MachineFunctionPass {
170 public:
171 static char ID;
172 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
173 PassRegistry &PR = *PassRegistry::getPassRegistry();
174 initializeHexagonCallFrameInformationPass(PR);
175 }
176 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000177 MachineFunctionProperties getRequiredProperties() const override {
178 return MachineFunctionProperties().set(
179 MachineFunctionProperties::Property::AllVRegsAllocated);
180 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000181 };
182
183 char HexagonCallFrameInformation::ID = 0;
184}
185
186bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
187 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
188 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
189 MF.getFunction()->needsUnwindTableEntry();
190
191 if (!NeedCFI)
192 return false;
193 HFI.insertCFIInstructions(MF);
194 return true;
195}
196
197INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
198 "Hexagon call frame information", false, false)
199
200FunctionPass *llvm::createHexagonCallFrameInformation() {
201 return new HexagonCallFrameInformation();
202}
203
204
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000205namespace {
206 /// Map a register pair Reg to the subregister that has the greater "number",
207 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
208 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
209 bool hireg = true) {
210 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
211 return Reg;
212
213 unsigned RegNo = 0;
214 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
215 if (hireg) {
216 if (*SubRegs > RegNo)
217 RegNo = *SubRegs;
218 } else {
219 if (!RegNo || *SubRegs < RegNo)
220 RegNo = *SubRegs;
221 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000222 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000223 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000224 }
225
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000226 /// Returns the callee saved register with the largest id in the vector.
227 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
228 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000229 static_assert(Hexagon::R1 > 0,
230 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000231 if (CSI.empty())
232 return 0;
233
234 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
235 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
236 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
237 if (Reg > Max)
238 Max = Reg;
239 }
240 return Max;
241 }
242
243 /// Checks if the basic block contains any instruction that needs a stack
244 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000245 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
246 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000247 for (auto &I : MBB) {
248 const MachineInstr *MI = &I;
249 if (MI->isCall())
250 return true;
251 unsigned Opc = MI->getOpcode();
252 switch (Opc) {
253 case Hexagon::ALLOCA:
254 case Hexagon::ALIGNA:
255 return true;
256 default:
257 break;
258 }
259 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000260 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000261 // While the presence of a frame index does not prove that a stack
262 // frame will be required, all frame indexes should be within alloc-
263 // frame/deallocframe. Otherwise, the code that translates a frame
264 // index into an offset would have to be aware of the placement of
265 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000266 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000268 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000269 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000270 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000271 // Virtual registers will need scavenging, which then may require
272 // a stack slot.
273 if (TargetRegisterInfo::isVirtualRegister(R))
274 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000275 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
276 if (CSR[*S])
277 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000278 }
279 }
280 return false;
281 }
282
283 /// Returns true if MBB has a machine instructions that indicates a tail call
284 /// in the block.
285 bool hasTailCall(const MachineBasicBlock &MBB) {
286 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
287 unsigned RetOpc = I->getOpcode();
288 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
289 }
290
291 /// Returns true if MBB contains an instruction that returns.
292 bool hasReturn(const MachineBasicBlock &MBB) {
293 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
294 if (I->isReturn())
295 return true;
296 return false;
297 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000298
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000299 /// Returns the "return" instruction from this block, or nullptr if there
300 /// isn't any.
301 MachineInstr *getReturn(MachineBasicBlock &MBB) {
302 for (auto &I : MBB)
303 if (I.isReturn())
304 return &I;
305 return nullptr;
306 }
307
308 bool isRestoreCall(unsigned Opc) {
309 switch (Opc) {
310 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
311 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
312 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
313 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
314 return true;
315 }
316 return false;
317 }
318
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000319 inline bool isOptNone(const MachineFunction &MF) {
320 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
321 MF.getTarget().getOptLevel() == CodeGenOpt::None;
322 }
323
324 inline bool isOptSize(const MachineFunction &MF) {
325 const Function &F = *MF.getFunction();
326 return F.optForSize() && !F.optForMinSize();
327 }
328
329 inline bool isMinSize(const MachineFunction &MF) {
330 return MF.getFunction()->optForMinSize();
331 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000332}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000333
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000334
335/// Implements shrink-wrapping of the stack frame. By default, stack frame
336/// is created in the function entry block, and is cleaned up in every block
337/// that returns. This function finds alternate blocks: one for the frame
338/// setup (prolog) and one for the cleanup (epilog).
339void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
340 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
341 static unsigned ShrinkCounter = 0;
342
343 if (ShrinkLimit.getPosition()) {
344 if (ShrinkCounter >= ShrinkLimit)
345 return;
346 ShrinkCounter++;
347 }
348
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000349 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000350 auto &HRI = *HST.getRegisterInfo();
351
352 MachineDominatorTree MDT;
353 MDT.runOnMachineFunction(MF);
354 MachinePostDominatorTree MPT;
355 MPT.runOnMachineFunction(MF);
356
357 typedef DenseMap<unsigned,unsigned> UnsignedMap;
358 UnsignedMap RPO;
359 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
360 RPOTType RPOT(&MF);
361 unsigned RPON = 0;
362 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
363 RPO[(*I)->getNumber()] = RPON++;
364
365 // Don't process functions that have loops, at least for now. Placement
366 // of prolog and epilog must take loop structure into account. For simpli-
367 // city don't do it right now.
368 for (auto &I : MF) {
369 unsigned BN = RPO[I.getNumber()];
370 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
371 // If found a back-edge, return.
372 if (RPO[(*SI)->getNumber()] <= BN)
373 return;
374 }
375 }
376
377 // Collect the set of blocks that need a stack frame to execute. Scan
378 // each block for uses/defs of callee-saved registers, calls, etc.
379 SmallVector<MachineBasicBlock*,16> SFBlocks;
380 BitVector CSR(Hexagon::NUM_TARGET_REGS);
381 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000382 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
383 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000384
385 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000386 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000387 SFBlocks.push_back(&I);
388
389 DEBUG({
390 dbgs() << "Blocks needing SF: {";
391 for (auto &B : SFBlocks)
392 dbgs() << " BB#" << B->getNumber();
393 dbgs() << " }\n";
394 });
395 // No frame needed?
396 if (SFBlocks.empty())
397 return;
398
399 // Pick a common dominator and a common post-dominator.
400 MachineBasicBlock *DomB = SFBlocks[0];
401 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
402 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
403 if (!DomB)
404 break;
405 }
406 MachineBasicBlock *PDomB = SFBlocks[0];
407 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
408 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
409 if (!PDomB)
410 break;
411 }
412 DEBUG({
413 dbgs() << "Computed dom block: BB#";
414 if (DomB) dbgs() << DomB->getNumber();
415 else dbgs() << "<null>";
416 dbgs() << ", computed pdom block: BB#";
417 if (PDomB) dbgs() << PDomB->getNumber();
418 else dbgs() << "<null>";
419 dbgs() << "\n";
420 });
421 if (!DomB || !PDomB)
422 return;
423
424 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
425 if (!MDT.dominates(DomB, PDomB)) {
426 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
427 return;
428 }
429 if (!MPT.dominates(PDomB, DomB)) {
430 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
431 return;
432 }
433
434 // Finally, everything seems right.
435 PrologB = DomB;
436 EpilogB = PDomB;
437}
438
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000439
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000440/// Perform most of the PEI work here:
441/// - saving/restoring of the callee-saved registers,
442/// - stack frame creation and destruction.
443/// Normally, this work is distributed among various functions, but doing it
444/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000445void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
446 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000447 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000448 auto &HRI = *HST.getRegisterInfo();
449
450 MachineFrameInfo *MFI = MF.getFrameInfo();
451 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
452
453 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
454 if (EnableShrinkWrapping)
455 findShrunkPrologEpilog(MF, PrologB, EpilogB);
456
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000457 bool PrologueStubs = false;
458 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
459 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000460
461 if (EpilogB) {
462 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
463 insertEpilogueInBlock(*EpilogB);
464 } else {
465 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000466 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000467 insertCSRRestoresInBlock(B, CSI, HRI);
468
469 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000470 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000471 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000472
473 for (auto &B : MF) {
474 if (B.empty())
475 continue;
476 MachineInstr *RetI = getReturn(B);
477 if (!RetI || isRestoreCall(RetI->getOpcode()))
478 continue;
479 for (auto &R : CSI)
480 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
481 }
482 }
483
484 if (EpilogB) {
485 // If there is an epilog block, it may not have a return instruction.
486 // In such case, we need to add the callee-saved registers as live-ins
487 // in all blocks on all paths from the epilog to any return block.
488 unsigned MaxBN = 0;
489 for (auto &B : MF)
490 if (B.getNumber() >= 0)
491 MaxBN = std::max(MaxBN, unsigned(B.getNumber()));
492 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
493 updateExitPaths(*EpilogB, EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000494 }
495}
496
497
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000498void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
499 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000500 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000501 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000502 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000503 auto &HII = *HST.getInstrInfo();
504 auto &HRI = *HST.getRegisterInfo();
505 DebugLoc dl;
506
507 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
508
509 // Calculate the total stack frame size.
510 // Get the number of bytes to allocate from the FrameInfo.
511 unsigned FrameSize = MFI->getStackSize();
512 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000513 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000514 MFI->setMaxCallFrameSize(MaxCFA);
515
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000516 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000517 MFI->setStackSize(FrameSize);
518
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000519 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000520
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000521 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000522 unsigned NumBytes = MFI->getStackSize();
523 unsigned SP = HRI.getStackRegister();
524 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000525 MachineBasicBlock::iterator InsertPt = MBB.begin();
526
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000527 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
528 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000529
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000530 for (auto MI : AdjustRegs) {
531 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
532 expandAlloca(MI, HII, SP, MaxCF);
533 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000534 }
535
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000536 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000537 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000538
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000539 // Check for overflow.
540 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
541 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000542
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000543 // Create a dummy memory operand to avoid allocframe from being treated as
544 // a volatile memory reference.
545 MachineMemOperand *MMO =
546 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
547 4, 4);
548
549 if (NumBytes >= ALLOCFRAME_MAX) {
550 // Emit allocframe(#0).
551 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
552 .addImm(0)
553 .addMemOperand(MMO);
554
555 // Subtract offset from frame pointer.
556 // We use a caller-saved non-parameter register for that.
557 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
558 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
559 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000560 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
561 .addReg(SP)
562 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000563 } else {
564 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
565 .addImm(NumBytes)
566 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000567 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000568
569 if (AlignStack) {
570 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
571 .addReg(SP)
572 .addImm(-int64_t(MaxAlign));
573 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000574
575 // If the stack-checking is enabled, and we spilled the callee-saved
576 // registers inline (i.e. did not use a spill function), then call
577 // the stack checker directly.
578 if (EnableStackOVFSanitizer && !PrologueStubs)
579 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
580 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000581}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000582
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000583void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
584 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000585 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000586 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000587
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000588 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000589 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000590 auto &HRI = *HST.getRegisterInfo();
591 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000592
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000593 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000594 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
595
596 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
597 DebugLoc DL;
598 if (InsertPt != MBB.end())
599 DL = InsertPt->getDebugLoc();
600 else if (!MBB.empty())
601 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000602
603 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000604 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000605 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
606 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
607 .addReg(SP)
608 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000609 return;
610 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000611
612 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
613 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000614 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
615 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000616 MachineBasicBlock::iterator It = RetI;
617 ++It;
618 // Delete all instructions after the RESTORE (except labels).
619 while (It != MBB.end()) {
620 if (!It->isLabel())
621 It = MBB.erase(It);
622 else
623 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000624 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000625 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000626 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000627
628 // It is possible that the restoring code is a call to a library function.
629 // All of the restore* functions include "deallocframe", so we need to make
630 // sure that we don't add an extra one.
631 bool NeedsDeallocframe = true;
632 if (!MBB.empty() && InsertPt != MBB.begin()) {
633 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
634 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000635 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
636 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000637 NeedsDeallocframe = false;
638 }
639
640 if (!NeedsDeallocframe)
641 return;
642 // If the returning instruction is JMPret, replace it with dealloc_return,
643 // otherwise just add deallocframe. The function could be returning via a
644 // tail call.
645 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
646 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
647 return;
648 }
649 unsigned NewOpc = Hexagon::L4_return;
650 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
651 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000652 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000653 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000654}
655
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000656
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000657bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
658 MachineBasicBlock *RestoreB, BitVector &DoneT, BitVector &DoneF,
659 BitVector &Path) const {
660 assert(MBB.getNumber() >= 0);
661 unsigned BN = MBB.getNumber();
662 if (Path[BN] || DoneF[BN])
663 return false;
664 if (DoneT[BN])
665 return true;
666
667 auto &CSI = MBB.getParent()->getFrameInfo()->getCalleeSavedInfo();
668
669 Path[BN] = true;
670 bool ReachedExit = false;
671 for (auto &SB : MBB.successors())
672 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
673
674 if (!MBB.empty() && MBB.back().isReturn()) {
675 // Add implicit uses of all callee-saved registers to the reached
676 // return instructions. This is to prevent the anti-dependency breaker
677 // from renaming these registers.
678 MachineInstr &RetI = MBB.back();
679 if (!isRestoreCall(RetI.getOpcode()))
680 for (auto &R : CSI)
681 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
682 ReachedExit = true;
683 }
684
685 // We don't want to add unnecessary live-ins to the restore block: since
686 // the callee-saved registers are being defined in it, the entry of the
687 // restore block cannot be on the path from the definitions to any exit.
688 if (ReachedExit && &MBB != RestoreB) {
689 for (auto &R : CSI)
690 if (!MBB.isLiveIn(R.getReg()))
691 MBB.addLiveIn(R.getReg());
692 DoneT[BN] = true;
693 }
694 if (!ReachedExit)
695 DoneF[BN] = true;
696
697 Path[BN] = false;
698 return ReachedExit;
699}
700
701
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000702namespace {
703 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
704 if (!It->isBundle())
705 return It->getOpcode() == Hexagon::S2_allocframe;
706 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000707 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000708 while (++I != End && I->isBundled())
709 if (I->getOpcode() == Hexagon::S2_allocframe)
710 return true;
711 return false;
712 }
713
714 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
715 for (auto &I : B)
716 if (IsAllocFrame(I))
717 return I;
718 return B.end();
719 }
720}
721
722
723void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
724 for (auto &B : MF) {
725 auto AF = FindAllocFrame(B);
726 if (AF == B.end())
727 continue;
728 insertCFIInstructionsAt(B, ++AF);
729 }
730}
731
732
733void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
734 MachineBasicBlock::iterator At) const {
735 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000736 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000737 MachineModuleInfo &MMI = MF.getMMI();
738 auto &HST = MF.getSubtarget<HexagonSubtarget>();
739 auto &HII = *HST.getInstrInfo();
740 auto &HRI = *HST.getRegisterInfo();
741
742 // If CFI instructions have debug information attached, something goes
743 // wrong with the final assembly generation: the prolog_end is placed
744 // in a wrong location.
745 DebugLoc DL;
746 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
747
748 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000749 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000750
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000751 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000752 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
753 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000754
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000755 // Define CFA via an offset from the value of FP.
756 //
757 // -8 -4 0 (SP)
758 // --+----+----+---------------------
759 // | FP | LR | increasing addresses -->
760 // --+----+----+---------------------
761 // | +-- Old SP (before allocframe)
762 // +-- New FP (after allocframe)
763 //
764 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
765 // MCCFIInstruction::createOffset takes the offset without sign change.
766 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
767 BuildMI(MBB, At, DL, CFID)
768 .addCFIIndex(MMI.addFrameInst(DefCfa));
769 // R31 (return addr) = CFA - 4
770 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
771 BuildMI(MBB, At, DL, CFID)
772 .addCFIIndex(MMI.addFrameInst(OffR31));
773 // R30 (frame ptr) = CFA - 8
774 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
775 BuildMI(MBB, At, DL, CFID)
776 .addCFIIndex(MMI.addFrameInst(OffR30));
777 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000778
779 static unsigned int RegsToMove[] = {
780 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
781 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
782 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
783 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
784 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
785 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
786 Hexagon::NoRegister
787 };
788
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000789 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000790
791 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
792 unsigned Reg = RegsToMove[i];
793 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
794 return C.getReg() == Reg;
795 };
796 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
797 if (F == CSI.end())
798 continue;
799
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000800 int64_t Offset;
801 if (HasFP) {
802 // If the function has a frame pointer (i.e. has an allocframe),
803 // then the CFA has been defined in terms of FP. Any offsets in
804 // the following CFI instructions have to be defined relative
805 // to FP, which points to the bottom of the stack frame.
806 // The function getFrameIndexReference can still choose to use SP
807 // for the offset calculation, so we cannot simply call it here.
808 // Instead, get the offset (relative to the FP) directly.
809 Offset = MFI.getObjectOffset(F->getFrameIdx());
810 } else {
811 unsigned FrameReg;
812 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
813 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000814 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000815 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000816
817 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
818 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
819 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
820 Offset);
821 BuildMI(MBB, At, DL, CFID)
822 .addCFIIndex(MMI.addFrameInst(OffReg));
823 } else {
824 // Split the double regs into subregs, and generate appropriate
825 // cfi_offsets.
826 // The only reason, we are split double regs is, llvm-mc does not
827 // understand paired registers for cfi_offset.
828 // Eg .cfi_offset r1:0, -64
829
830 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
831 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
832 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
833 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
834 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
835 Offset+4);
836 BuildMI(MBB, At, DL, CFID)
837 .addCFIIndex(MMI.addFrameInst(OffHi));
838 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
839 Offset);
840 BuildMI(MBB, At, DL, CFID)
841 .addCFIIndex(MMI.addFrameInst(OffLo));
842 }
843 }
844}
845
846
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000847bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000848 auto &MFI = *MF.getFrameInfo();
849 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
850
851 bool HasFixed = MFI.getNumFixedObjects();
852 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
853 .getLocalFrameObjectCount();
854 bool HasExtraAlign = HRI.needsStackRealignment(MF);
855 bool HasAlloca = MFI.hasVarSizedObjects();
856
857 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
858 // that this shouldn't be required, but doing so now because gcc does and
859 // gdb can't break at the start of the function without it. Will remove if
860 // this turns out to be a gdb bug.
861 //
862 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
863 return true;
864
865 // By default we want to use SP (since it's always there). FP requires
866 // some setup (i.e. ALLOCFRAME).
867 // Fixed and preallocated objects need FP if the distance from them to
868 // the SP is unknown (as is with alloca or aligna).
869 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
870 return true;
871
872 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000873 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000874 return true;
875 }
876
877 if (MFI.hasCalls() ||
878 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
879 return true;
880
881 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000882}
883
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000884
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000885enum SpillKind {
886 SK_ToMem,
887 SK_FromMem,
888 SK_FromMemTailcall
889};
890
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000891static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
892 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000893 const char * V4SpillToMemoryFunctions[] = {
894 "__save_r16_through_r17",
895 "__save_r16_through_r19",
896 "__save_r16_through_r21",
897 "__save_r16_through_r23",
898 "__save_r16_through_r25",
899 "__save_r16_through_r27" };
900
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000901 const char * V4SpillToMemoryStkchkFunctions[] = {
902 "__save_r16_through_r17_stkchk",
903 "__save_r16_through_r19_stkchk",
904 "__save_r16_through_r21_stkchk",
905 "__save_r16_through_r23_stkchk",
906 "__save_r16_through_r25_stkchk",
907 "__save_r16_through_r27_stkchk" };
908
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000909 const char * V4SpillFromMemoryFunctions[] = {
910 "__restore_r16_through_r17_and_deallocframe",
911 "__restore_r16_through_r19_and_deallocframe",
912 "__restore_r16_through_r21_and_deallocframe",
913 "__restore_r16_through_r23_and_deallocframe",
914 "__restore_r16_through_r25_and_deallocframe",
915 "__restore_r16_through_r27_and_deallocframe" };
916
917 const char * V4SpillFromMemoryTailcallFunctions[] = {
918 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
919 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
920 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
921 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
922 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
923 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
924 };
925
926 const char **SpillFunc = nullptr;
927
928 switch(SpillType) {
929 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000930 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
931 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000932 break;
933 case SK_FromMem:
934 SpillFunc = V4SpillFromMemoryFunctions;
935 break;
936 case SK_FromMemTailcall:
937 SpillFunc = V4SpillFromMemoryTailcallFunctions;
938 break;
939 }
940 assert(SpillFunc && "Unknown spill kind");
941
942 // Spill all callee-saved registers up to the highest register used.
943 switch (MaxReg) {
944 case Hexagon::R17:
945 return SpillFunc[0];
946 case Hexagon::R19:
947 return SpillFunc[1];
948 case Hexagon::R21:
949 return SpillFunc[2];
950 case Hexagon::R23:
951 return SpillFunc[3];
952 case Hexagon::R25:
953 return SpillFunc[4];
954 case Hexagon::R27:
955 return SpillFunc[5];
956 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000957 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000958 }
959 return 0;
960}
961
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000962
James Y Knight5567baf2015-08-15 02:32:35 +0000963int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000964 int FI, unsigned &FrameReg) const {
965 auto &MFI = *MF.getFrameInfo();
966 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000967
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000968 int Offset = MFI.getObjectOffset(FI);
969 bool HasAlloca = MFI.hasVarSizedObjects();
970 bool HasExtraAlign = HRI.needsStackRealignment(MF);
971 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000972
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000973 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000974 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
975 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000976 unsigned FrameSize = MFI.getStackSize();
977
978 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
979 // Use FP at -O0, except when there are objects with extra alignment.
980 // That additional alignment requirement may cause a pad to be inserted,
981 // which will make it impossible to use FP to access objects located
982 // past the pad.
983 if (NoOpt && !HasExtraAlign)
984 UseFP = true;
985 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
986 // Fixed and preallocated objects will be located before any padding
987 // so FP must be used to access them.
988 UseFP |= (HasAlloca || HasExtraAlign);
989 } else {
990 if (HasAlloca) {
991 if (HasExtraAlign)
992 UseAP = true;
993 else
994 UseFP = true;
995 }
996 }
997
998 // If FP was picked, then there had better be FP.
999 bool HasFP = hasFP(MF);
1000 assert((HasFP || !UseFP) && "This function must have frame pointer");
1001
1002 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1003 // FP/LR. If the base register is used to access an object across these
1004 // 8 bytes, then the offset will need to be adjusted by 8.
1005 //
1006 // After allocframe:
1007 // HexagonISelLowering adds 8 to ---+
1008 // the offsets of all stack-based |
1009 // arguments (*) |
1010 // |
1011 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1012 // ------------------------+-----+------------------------> increasing
1013 // <local objects> |FP/LR| <input arguments> addresses
1014 // -----------------+------+-----+------------------------>
1015 // | |
1016 // SP/AP point --+ +-- FP points here (**)
1017 // somewhere on
1018 // this side of FP/LR
1019 //
1020 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1021 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1022
1023 // The lowering assumes that FP/LR is present, and so the offsets of
1024 // the formal arguments start at 8. If FP/LR is not there we need to
1025 // reduce the offset by 8.
1026 if (Offset > 0 && !HasFP)
1027 Offset -= 8;
1028
1029 if (UseFP)
1030 FrameReg = FP;
1031 else if (UseAP)
1032 FrameReg = AP;
1033 else
1034 FrameReg = SP;
1035
1036 // Calculate the actual offset in the instruction. If there is no FP
1037 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1038 // there will be no SP -= FrameSize), so the frame size should not be
1039 // added to the calculated offset.
1040 int RealOffset = Offset;
1041 if (!UseFP && !UseAP && HasFP)
1042 RealOffset = FrameSize+Offset;
1043 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001044}
1045
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001046
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001047bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001048 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1049 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001050 if (CSI.empty())
1051 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001052
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001053 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001054 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001055 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001056 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1057 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001058
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001059 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001060 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001061 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001062 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1063 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1064 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001065 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001066 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001067 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001068
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001069 // Call spill function.
1070 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001071 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001072 if (StkOvrFlowEnabled) {
1073 if (LongCalls)
1074 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1075 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1076 else
1077 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1078 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1079 } else {
1080 if (LongCalls)
1081 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1082 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1083 else
1084 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1085 : Hexagon::SAVE_REGISTERS_CALL_V4;
1086 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001087
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001088 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001089 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001090 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001091
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001092 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001093 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001094 // Add live in registers.
1095 for (unsigned I = 0; I < CSI.size(); ++I)
1096 MBB.addLiveIn(CSI[I].getReg());
1097 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001098 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001099
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001100 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001101 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001102 // Add live in registers. We treat eh_return callee saved register r0 - r3
1103 // specially. They are not really callee saved registers as they are not
1104 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001105 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1106 int FI = CSI[i].getFrameIdx();
1107 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001108 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001109 if (IsKill)
1110 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001111 }
1112 return true;
1113}
1114
1115
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001116bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1117 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1118 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001119 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001120
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001121 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1122 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001123 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1124 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001125
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001126 if (useRestoreFunction(MF, CSI)) {
1127 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1128 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1129 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1130 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001131 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001132 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001133 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001134
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001135 // Call spill function.
1136 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1137 : MBB.getLastNonDebugInstr()->getDebugLoc();
1138 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001139
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001140 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001141 unsigned RetOpc;
1142 if (LongCalls)
1143 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1144 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1145 else
1146 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1147 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1148 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001149 .addExternalSymbol(RestoreFn);
1150 } else {
1151 // The block has a return.
1152 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1153 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001154 unsigned RetOpc;
1155 if (LongCalls)
1156 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1157 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1158 else
1159 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1160 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1161 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001162 .addExternalSymbol(RestoreFn);
1163 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001164 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001165 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001166 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001167 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001168 }
1169
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001170 for (unsigned i = 0; i < CSI.size(); ++i) {
1171 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001172 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1173 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001174 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001175 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001176
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001177 return true;
1178}
1179
Hans Wennborge1a2e902016-03-31 18:33:38 +00001180MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1181 MachineFunction &MF, MachineBasicBlock &MBB,
1182 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001183 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001184 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001185 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001186 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1187 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001188 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001189}
1190
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001191
1192void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1193 MachineFunction &MF, RegScavenger *RS) const {
1194 // If this function has uses aligned stack and also has variable sized stack
1195 // objects, then we need to map all spill slots to fixed positions, so that
1196 // they can be accessed through FP. Otherwise they would have to be accessed
1197 // via AP, which may not be available at the particular place in the program.
1198 MachineFrameInfo *MFI = MF.getFrameInfo();
1199 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001200 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001201
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001202 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001203 return;
1204
1205 unsigned LFS = MFI->getLocalFrameSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001206 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1207 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1208 continue;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001209 unsigned S = MFI->getObjectSize(i);
1210 // Reduce the alignment to at most 8. This will require unaligned vector
1211 // stores if they happen here.
1212 unsigned A = std::max(MFI->getObjectAlignment(i), 8U);
1213 MFI->setObjectAlignment(i, 8);
1214 LFS = alignTo(LFS+S, A);
1215 MFI->mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001216 }
1217
1218 MFI->setLocalFrameSize(LFS);
1219 unsigned A = MFI->getLocalFrameMaxAlign();
1220 assert(A <= 8 && "Unexpected local frame alignment");
1221 if (A == 0)
1222 MFI->setLocalFrameMaxAlign(8);
1223 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001224
1225 // Set the physical aligned-stack base address register.
1226 unsigned AP = 0;
1227 if (const MachineInstr *AI = getAlignaInstr(MF))
1228 AP = AI->getOperand(0).getReg();
1229 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1230 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001231}
1232
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001233/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001234static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001235 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001236 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001237
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001238 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1239 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1240 if (MRI.isPhysRegUsed(*AI))
1241 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001242 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001243 };
1244
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001245 // Check for an unused caller-saved register. Callee-saved registers
1246 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001247 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001248 if (!IsUsed(*P))
1249 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001250
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001251 // All caller-saved registers are used.
1252 return true;
1253}
1254
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001255
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001256#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001257static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001258 dbgs() << '{';
1259 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1260 unsigned R = x;
1261 dbgs() << ' ' << PrintReg(R, &TRI);
1262 }
1263 dbgs() << " }";
1264}
1265#endif
1266
1267
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001268bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1269 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001270 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001271 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001272 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001273 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001274
1275 // Generate a set of unique, callee-saved registers (SRegs), where each
1276 // register in the set is maximal in terms of sub-/super-register relation,
1277 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1278
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001279 // (1) For each callee-saved register, add that register and all of its
1280 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001281 DEBUG(dbgs() << "Initial CS registers: {");
1282 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1283 unsigned R = CSI[i].getReg();
1284 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1285 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1286 SRegs[*SR] = true;
1287 }
1288 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001289 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001290
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001291 // (2) For each reserved register, remove that register and all of its
1292 // sub- and super-registers from SRegs.
1293 BitVector Reserved = TRI->getReservedRegs(MF);
1294 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1295 unsigned R = x;
1296 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1297 SRegs[*SR] = false;
1298 }
1299 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1300 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1301
1302 // (3) Collect all registers that have at least one sub-register in SRegs,
1303 // and also have no sub-registers that are reserved. These will be the can-
1304 // didates for saving as a whole instead of their individual sub-registers.
1305 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1306 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001307 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1308 unsigned R = x;
1309 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1310 TmpSup[*SR] = true;
1311 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001312 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1313 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001314 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1315 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001316 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001317 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001318 break;
1319 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001320 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001321 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001322
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001323 // (4) Include all super-registers found in (3) into SRegs.
1324 SRegs |= TmpSup;
1325 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001326
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001327 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001328 // remove R from SRegs.
1329 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1330 unsigned R = x;
1331 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1332 if (!SRegs[*SR])
1333 continue;
1334 SRegs[R] = false;
1335 break;
1336 }
1337 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001338 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001339
1340 // Now, for each register that has a fixed stack slot, create the stack
1341 // object for it.
1342 CSI.clear();
1343
1344 typedef TargetFrameLowering::SpillSlot SpillSlot;
1345 unsigned NumFixed;
1346 int MinOffset = 0; // CS offsets are negative.
1347 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1348 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1349 if (!SRegs[S->Reg])
1350 continue;
1351 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1352 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1353 MinOffset = std::min(MinOffset, S->Offset);
1354 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1355 SRegs[S->Reg] = false;
1356 }
1357
1358 // There can be some registers that don't have fixed slots. For example,
1359 // we need to store R0-R3 in functions with exception handling. For each
1360 // such register, create a non-fixed stack object.
1361 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1362 unsigned R = x;
1363 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1364 int Off = MinOffset - RC->getSize();
1365 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1366 assert(isPowerOf2_32(Align));
1367 Off &= -Align;
1368 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1369 MinOffset = std::min(MinOffset, Off);
1370 CSI.push_back(CalleeSavedInfo(R, FI));
1371 SRegs[R] = false;
1372 }
1373
1374 DEBUG({
1375 dbgs() << "CS information: {";
1376 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1377 int FI = CSI[i].getFrameIdx();
1378 int Off = MFI->getObjectOffset(FI);
1379 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1380 if (Off >= 0)
1381 dbgs() << '+';
1382 dbgs() << Off;
1383 }
1384 dbgs() << " }\n";
1385 });
1386
1387#ifndef NDEBUG
1388 // Verify that all registers were handled.
1389 bool MissedReg = false;
1390 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1391 unsigned R = x;
1392 dbgs() << PrintReg(R, TRI) << ' ';
1393 MissedReg = true;
1394 }
1395 if (MissedReg)
1396 llvm_unreachable("...there are unhandled callee-saved registers!");
1397#endif
1398
1399 return true;
1400}
1401
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001402
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001403bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1404 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1405 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1406 MachineInstr *MI = &*It;
1407 DebugLoc DL = MI->getDebugLoc();
1408 unsigned DstR = MI->getOperand(0).getReg();
1409 unsigned SrcR = MI->getOperand(1).getReg();
1410 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1411 !Hexagon::ModRegsRegClass.contains(SrcR))
1412 return false;
1413
1414 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1415 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1416 .addOperand(MI->getOperand(1));
1417 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1418 .addReg(TmpR, RegState::Kill);
1419
1420 NewRegs.push_back(TmpR);
1421 B.erase(It);
1422 return true;
1423}
1424
1425bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1426 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1427 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1428 MachineInstr *MI = &*It;
1429 DebugLoc DL = MI->getDebugLoc();
1430 unsigned Opc = MI->getOpcode();
1431 unsigned SrcR = MI->getOperand(2).getReg();
1432 bool IsKill = MI->getOperand(2).isKill();
1433
1434 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1435 int FI = MI->getOperand(0).getIndex();
1436
1437 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1438 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1439 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1440 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1441 : Hexagon::A2_tfrcrr;
1442 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1443 .addReg(SrcR, getKillRegState(IsKill));
1444
1445 // S2_storeri_io FI, 0, TmpR
1446 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1447 .addFrameIndex(FI)
1448 .addImm(0)
1449 .addReg(TmpR, RegState::Kill)
1450 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1451
1452 NewRegs.push_back(TmpR);
1453 B.erase(It);
1454 return true;
1455}
1456
1457bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1458 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1459 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1460 MachineInstr *MI = &*It;
1461 DebugLoc DL = MI->getDebugLoc();
1462 unsigned Opc = MI->getOpcode();
1463 unsigned DstR = MI->getOperand(0).getReg();
1464
1465 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1466 int FI = MI->getOperand(1).getIndex();
1467
1468 // TmpR = L2_loadri_io FI, 0
1469 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1470 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1471 .addFrameIndex(FI)
1472 .addImm(0)
1473 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1474
1475 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1476 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1477 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1478 : Hexagon::A2_tfrrcr;
1479 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1480 .addReg(TmpR, RegState::Kill);
1481
1482 NewRegs.push_back(TmpR);
1483 B.erase(It);
1484 return true;
1485}
1486
1487
1488bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1489 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1490 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1491 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1492 MachineInstr *MI = &*It;
1493 DebugLoc DL = MI->getDebugLoc();
1494 unsigned SrcR = MI->getOperand(2).getReg();
1495 bool IsKill = MI->getOperand(2).isKill();
1496
1497 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1498 int FI = MI->getOperand(0).getIndex();
1499
1500 bool Is128B = HST.useHVXDblOps();
1501 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1502 : &Hexagon::VectorRegs128BRegClass;
1503
1504 // Insert transfer to general vector register.
1505 // TmpR0 = A2_tfrsi 0x01010101
1506 // TmpR1 = V6_vandqrt Qx, TmpR0
1507 // store FI, 0, TmpR1
1508 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1509 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1510
1511 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1512 .addImm(0x01010101);
1513
1514 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1515 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1516 .addReg(SrcR, getKillRegState(IsKill))
1517 .addReg(TmpR0, RegState::Kill);
1518
1519 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1520 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1521 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1522
1523 NewRegs.push_back(TmpR0);
1524 NewRegs.push_back(TmpR1);
1525 B.erase(It);
1526 return true;
1527}
1528
1529bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1530 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1531 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1532 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1533 MachineInstr *MI = &*It;
1534 DebugLoc DL = MI->getDebugLoc();
1535 unsigned DstR = MI->getOperand(0).getReg();
1536
1537 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1538 int FI = MI->getOperand(1).getIndex();
1539
1540 bool Is128B = HST.useHVXDblOps();
1541 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1542 : &Hexagon::VectorRegs128BRegClass;
1543
1544 // TmpR0 = A2_tfrsi 0x01010101
1545 // TmpR1 = load FI, 0
1546 // DstR = V6_vandvrt TmpR1, TmpR0
1547 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1548 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1549
1550 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1551 .addImm(0x01010101);
1552 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1553 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1554 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1555
1556 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1557 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1558 .addReg(TmpR1, RegState::Kill)
1559 .addReg(TmpR0, RegState::Kill);
1560
1561 NewRegs.push_back(TmpR0);
1562 NewRegs.push_back(TmpR1);
1563 B.erase(It);
1564 return true;
1565}
1566
1567bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1568 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1569 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1570 MachineFunction &MF = *B.getParent();
1571 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1572 auto &MFI = *MF.getFrameInfo();
1573 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1574 MachineInstr *MI = &*It;
1575 DebugLoc DL = MI->getDebugLoc();
1576
1577 unsigned SrcR = MI->getOperand(2).getReg();
1578 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1579 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1580 bool IsKill = MI->getOperand(2).isKill();
1581
1582 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1583 int FI = MI->getOperand(0).getIndex();
1584
1585 bool Is128B = HST.useHVXDblOps();
1586 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1587 : &Hexagon::VectorRegs128BRegClass;
1588 unsigned Size = RC->getSize();
1589 unsigned NeedAlign = RC->getAlignment();
1590 unsigned HasAlign = MFI.getObjectAlignment(FI);
1591 unsigned StoreOpc;
1592
1593 // Store low part.
1594 if (NeedAlign <= HasAlign)
1595 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1596 else
1597 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1598
1599 BuildMI(B, It, DL, HII.get(StoreOpc))
1600 .addFrameIndex(FI)
1601 .addImm(0)
1602 .addReg(SrcLo, getKillRegState(IsKill))
1603 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1604
1605 // Load high part.
1606 if (NeedAlign <= MinAlign(HasAlign, Size))
1607 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1608 else
1609 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1610
1611 BuildMI(B, It, DL, HII.get(StoreOpc))
1612 .addFrameIndex(FI)
1613 .addImm(Size)
1614 .addReg(SrcHi, getKillRegState(IsKill))
1615 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1616
1617 B.erase(It);
1618 return true;
1619}
1620
1621bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1622 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1623 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1624 MachineFunction &MF = *B.getParent();
1625 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1626 auto &MFI = *MF.getFrameInfo();
1627 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1628 MachineInstr *MI = &*It;
1629 DebugLoc DL = MI->getDebugLoc();
1630
1631 unsigned DstR = MI->getOperand(0).getReg();
1632 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1633 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1634
1635 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1636 int FI = MI->getOperand(1).getIndex();
1637
1638 bool Is128B = HST.useHVXDblOps();
1639 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1640 : &Hexagon::VectorRegs128BRegClass;
1641 unsigned Size = RC->getSize();
1642 unsigned NeedAlign = RC->getAlignment();
1643 unsigned HasAlign = MFI.getObjectAlignment(FI);
1644 unsigned LoadOpc;
1645
1646 // Load low part.
1647 if (NeedAlign <= HasAlign)
1648 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1649 else
1650 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1651
1652 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1653 .addFrameIndex(FI)
1654 .addImm(0)
1655 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1656
1657 // Load high part.
1658 if (NeedAlign <= MinAlign(HasAlign, Size))
1659 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1660 else
1661 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1662
1663 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1664 .addFrameIndex(FI)
1665 .addImm(Size)
1666 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1667
1668 B.erase(It);
1669 return true;
1670}
1671
1672bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1673 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1674 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1675 MachineFunction &MF = *B.getParent();
1676 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1677 auto &MFI = *MF.getFrameInfo();
1678 MachineInstr *MI = &*It;
1679 DebugLoc DL = MI->getDebugLoc();
1680
1681 unsigned SrcR = MI->getOperand(2).getReg();
1682 bool IsKill = MI->getOperand(2).isKill();
1683
1684 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1685 int FI = MI->getOperand(0).getIndex();
1686
1687 bool Is128B = HST.useHVXDblOps();
1688 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1689 : &Hexagon::VectorRegs128BRegClass;
1690
1691 unsigned NeedAlign = RC->getAlignment();
1692 unsigned HasAlign = MFI.getObjectAlignment(FI);
1693 unsigned StoreOpc;
1694
1695 if (NeedAlign <= HasAlign)
1696 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1697 else
1698 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1699
1700 BuildMI(B, It, DL, HII.get(StoreOpc))
1701 .addFrameIndex(FI)
1702 .addImm(0)
1703 .addReg(SrcR, getKillRegState(IsKill))
1704 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1705
1706 B.erase(It);
1707 return true;
1708}
1709
1710bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1711 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1712 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1713 MachineFunction &MF = *B.getParent();
1714 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1715 auto &MFI = *MF.getFrameInfo();
1716 MachineInstr *MI = &*It;
1717 DebugLoc DL = MI->getDebugLoc();
1718
1719 unsigned DstR = MI->getOperand(0).getReg();
1720
1721 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1722 int FI = MI->getOperand(1).getIndex();
1723
1724 bool Is128B = HST.useHVXDblOps();
1725 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1726 : &Hexagon::VectorRegs128BRegClass;
1727
1728 unsigned NeedAlign = RC->getAlignment();
1729 unsigned HasAlign = MFI.getObjectAlignment(FI);
1730 unsigned LoadOpc;
1731
1732 if (NeedAlign <= HasAlign)
1733 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1734 else
1735 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1736
1737 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1738 .addFrameIndex(FI)
1739 .addImm(0)
1740 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1741
1742 B.erase(It);
1743 return true;
1744}
1745
1746
1747bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1748 SmallVectorImpl<unsigned> &NewRegs) const {
1749 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001750 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001751 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001752 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001753
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001754 for (auto &B : MF) {
1755 // Traverse the basic block.
1756 MachineBasicBlock::iterator NextI;
1757 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1758 MachineInstr *MI = &*I;
1759 NextI = std::next(I);
1760 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001761
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001762 switch (Opc) {
1763 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001764 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001765 break;
1766 case Hexagon::STriw_pred:
1767 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001768 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001769 break;
1770 case Hexagon::LDriw_pred:
1771 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001772 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001773 break;
1774 case Hexagon::STriq_pred_V6:
1775 case Hexagon::STriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001776 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001777 break;
1778 case Hexagon::LDriq_pred_V6:
1779 case Hexagon::LDriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001780 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001781 break;
1782 case Hexagon::LDrivv_pseudo_V6:
1783 case Hexagon::LDrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001784 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001785 break;
1786 case Hexagon::STrivv_pseudo_V6:
1787 case Hexagon::STrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001788 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001789 break;
1790 case Hexagon::STriv_pseudo_V6:
1791 case Hexagon::STriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001792 Changed |= expandStoreVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001793 break;
1794 case Hexagon::LDriv_pseudo_V6:
1795 case Hexagon::LDriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001796 Changed |= expandLoadVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001797 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001798 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001799 }
1800 }
1801
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001802 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001803}
1804
1805
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001806void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1807 BitVector &SavedRegs,
1808 RegScavenger *RS) const {
1809 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1810 auto &HRI = *HST.getRegisterInfo();
1811
1812 SavedRegs.resize(HRI.getNumRegs());
1813
1814 // If we have a function containing __builtin_eh_return we want to spill and
1815 // restore all callee saved registers. Pretend that they are used.
1816 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1817 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1818 SavedRegs.set(*R);
1819
1820 // Replace predicate register pseudo spill code.
1821 SmallVector<unsigned,8> NewRegs;
1822 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001823 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001824 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001825
1826 // We need to reserve a a spill slot if scavenging could potentially require
1827 // spilling a scavenged register.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001828 if (!NewRegs.empty()) {
1829 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001830 MachineRegisterInfo &MRI = MF.getRegInfo();
1831 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001832 // Reserve an int register in any case, because it could be used to hold
1833 // the stack offset in case it does not fit into a spill instruction.
1834 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1835
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001836 for (unsigned VR : NewRegs)
1837 SpillRCs.insert(MRI.getRegClass(VR));
1838
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001839 for (auto *RC : SpillRCs) {
1840 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1841 continue;
1842 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1843 unsigned S = RC->getSize(), A = RC->getAlignment();
1844 for (unsigned i = 0; i < Num; i++) {
1845 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001846 RS->addScavengingFrameIndex(NewFI);
1847 }
1848 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001849 }
1850
1851 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1852}
1853
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001854
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001855unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1856 HexagonBlockRanges::IndexRange &FIR,
1857 HexagonBlockRanges::InstrIndexMap &IndexMap,
1858 HexagonBlockRanges::RegToRangeMap &DeadMap,
1859 const TargetRegisterClass *RC) const {
1860 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1861 auto &MRI = MF.getRegInfo();
1862
1863 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1864 auto F = DeadMap.find({Reg,0});
1865 if (F == DeadMap.end())
1866 return false;
1867 for (auto &DR : F->second)
1868 if (DR.contains(FIR))
1869 return true;
1870 return false;
1871 };
1872
1873 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1874 bool Dead = true;
1875 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1876 if (isDead(R.Reg))
1877 continue;
1878 Dead = false;
1879 break;
1880 }
1881 if (Dead)
1882 return Reg;
1883 }
1884 return 0;
1885}
1886
1887void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1888 SmallVectorImpl<unsigned> &VRegs) const {
1889 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1890 auto &HII = *HST.getInstrInfo();
1891 auto &HRI = *HST.getRegisterInfo();
1892 auto &MRI = MF.getRegInfo();
1893 HexagonBlockRanges HBR(MF);
1894
1895 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1896 BlockIndexMap;
1897 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1898 BlockRangeMap;
1899 typedef HexagonBlockRanges::IndexType IndexType;
1900
1901 struct SlotInfo {
1902 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001903 unsigned Size;
1904 const TargetRegisterClass *RC;
1905
1906 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001907 };
1908
1909 BlockIndexMap BlockIndexes;
1910 SmallSet<int,4> BadFIs;
1911 std::map<int,SlotInfo> FIRangeMap;
1912
1913 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1914 -> const TargetRegisterClass* {
1915 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1916 assert(R.Sub == 0);
1917 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1918 auto *RCR = MRI.getRegClass(R.Reg);
1919 if (R.Sub == 0)
1920 return RCR;
1921 unsigned PR = *RCR->begin();
1922 R.Reg = HRI.getSubReg(PR, R.Sub);
1923 }
1924 return HRI.getMinimalPhysRegClass(R.Reg);
1925 };
1926 // Accumulate register classes: get a common class for a pre-existing
1927 // class HaveRC and a new class NewRC. Return nullptr if a common class
1928 // cannot be found, otherwise return the resulting class. If HaveRC is
1929 // nullptr, assume that it is still unset.
1930 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1931 const TargetRegisterClass *NewRC)
1932 -> const TargetRegisterClass* {
1933 if (HaveRC == nullptr || HaveRC == NewRC)
1934 return NewRC;
1935 // Different classes, both non-null. Pick the more general one.
1936 if (HaveRC->hasSubClassEq(NewRC))
1937 return HaveRC;
1938 if (NewRC->hasSubClassEq(HaveRC))
1939 return NewRC;
1940 return nullptr;
1941 };
1942
1943 // Scan all blocks in the function. Check all occurrences of frame indexes,
1944 // and collect relevant information.
1945 for (auto &B : MF) {
1946 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001947 // Emplace appears not to be supported in gcc 4.7.2-4.
1948 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001949 auto P = BlockIndexes.insert(
1950 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001951 auto &IndexMap = P.first->second;
1952 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1953 << IndexMap << '\n');
1954
1955 for (auto &In : B) {
1956 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001957 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
1958 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001959 if (Load && Store) {
1960 // If it's both a load and a store, then we won't handle it.
1961 BadFIs.insert(LFI);
1962 BadFIs.insert(SFI);
1963 continue;
1964 }
1965 // Check for register classes of the register used as the source for
1966 // the store, and the register used as the destination for the load.
1967 // Also, only accept base+imm_offset addressing modes. Other addressing
1968 // modes can have side-effects (post-increments, etc.). For stack
1969 // slots they are very unlikely, so there is not much loss due to
1970 // this restriction.
1971 if (Load || Store) {
1972 int TFI = Load ? LFI : SFI;
1973 unsigned AM = HII.getAddrMode(&In);
1974 SlotInfo &SI = FIRangeMap[TFI];
1975 bool Bad = (AM != HexagonII::BaseImmOffset);
1976 if (!Bad) {
1977 // If the addressing mode is ok, check the register class.
1978 const TargetRegisterClass *RC = nullptr;
1979 if (Load) {
1980 MachineOperand &DataOp = In.getOperand(0);
1981 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1982 } else {
1983 MachineOperand &DataOp = In.getOperand(2);
1984 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1985 }
1986 RC = getCommonRC(SI.RC, RC);
1987 if (RC == nullptr)
1988 Bad = true;
1989 else
1990 SI.RC = RC;
1991 }
1992 if (!Bad) {
1993 // Check sizes.
1994 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1995 if (SI.Size != 0 && SI.Size != S)
1996 Bad = true;
1997 else
1998 SI.Size = S;
1999 }
2000 if (Bad)
2001 BadFIs.insert(TFI);
2002 }
2003
2004 // Locate uses of frame indices.
2005 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2006 const MachineOperand &Op = In.getOperand(i);
2007 if (!Op.isFI())
2008 continue;
2009 int FI = Op.getIndex();
2010 // Make sure that the following operand is an immediate and that
2011 // it is 0. This is the offset in the stack object.
2012 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2013 In.getOperand(i+1).getImm() != 0)
2014 BadFIs.insert(FI);
2015 if (BadFIs.count(FI))
2016 continue;
2017
2018 IndexType Index = IndexMap.getIndex(&In);
2019 if (Load) {
2020 if (LastStore[FI] == IndexType::None)
2021 LastStore[FI] = IndexType::Entry;
2022 LastLoad[FI] = Index;
2023 } else if (Store) {
2024 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2025 if (LastStore[FI] != IndexType::None)
2026 RL.add(LastStore[FI], LastLoad[FI], false, false);
2027 else if (LastLoad[FI] != IndexType::None)
2028 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2029 LastLoad[FI] = IndexType::None;
2030 LastStore[FI] = Index;
2031 } else {
2032 BadFIs.insert(FI);
2033 }
2034 }
2035 }
2036
2037 for (auto &I : LastLoad) {
2038 IndexType LL = I.second;
2039 if (LL == IndexType::None)
2040 continue;
2041 auto &RL = FIRangeMap[I.first].Map[&B];
2042 IndexType &LS = LastStore[I.first];
2043 if (LS != IndexType::None)
2044 RL.add(LS, LL, false, false);
2045 else
2046 RL.add(IndexType::Entry, LL, false, false);
2047 LS = IndexType::None;
2048 }
2049 for (auto &I : LastStore) {
2050 IndexType LS = I.second;
2051 if (LS == IndexType::None)
2052 continue;
2053 auto &RL = FIRangeMap[I.first].Map[&B];
2054 RL.add(LS, IndexType::None, false, false);
2055 }
2056 }
2057
2058 DEBUG({
2059 for (auto &P : FIRangeMap) {
2060 dbgs() << "fi#" << P.first;
2061 if (BadFIs.count(P.first))
2062 dbgs() << " (bad)";
2063 dbgs() << " RC: ";
2064 if (P.second.RC != nullptr)
2065 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2066 else
2067 dbgs() << "<null>\n";
2068 for (auto &R : P.second.Map)
2069 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2070 }
2071 });
2072
2073 // When a slot is loaded from in a block without being stored to in the
2074 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2075 // consider this slot to be live-on-exit from all blocks.
2076 SmallSet<int,4> LoxFIs;
2077
2078 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2079
2080 for (auto &P : FIRangeMap) {
2081 // P = pair(FI, map: BB->RangeList)
2082 if (BadFIs.count(P.first))
2083 continue;
2084 for (auto &B : MF) {
2085 auto F = P.second.Map.find(&B);
2086 // F = pair(BB, RangeList)
2087 if (F == P.second.Map.end() || F->second.empty())
2088 continue;
2089 HexagonBlockRanges::IndexRange &IR = F->second.front();
2090 if (IR.start() == IndexType::Entry)
2091 LoxFIs.insert(P.first);
2092 BlockFIMap[&B].push_back(P.first);
2093 }
2094 }
2095
2096 DEBUG({
2097 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2098 for (auto &P : BlockFIMap) {
2099 auto &FIs = P.second;
2100 if (FIs.empty())
2101 continue;
2102 dbgs() << " BB#" << P.first->getNumber() << ": {";
2103 for (auto I : FIs) {
2104 dbgs() << " fi#" << I;
2105 if (LoxFIs.count(I))
2106 dbgs() << '*';
2107 }
2108 dbgs() << " }\n";
2109 }
2110 });
2111
2112 // eliminate loads, when all loads eliminated, eliminate all stores.
2113 for (auto &B : MF) {
2114 auto F = BlockIndexes.find(&B);
2115 assert(F != BlockIndexes.end());
2116 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2117 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2118 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2119 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2120 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2121
2122 for (auto FI : BlockFIMap[&B]) {
2123 if (BadFIs.count(FI))
2124 continue;
2125 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2126 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2127 for (auto &Range : RL) {
2128 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2129 if (!IndexType::isInstr(Range.start()) ||
2130 !IndexType::isInstr(Range.end()))
2131 continue;
2132 MachineInstr *SI = IM.getInstr(Range.start());
2133 MachineInstr *EI = IM.getInstr(Range.end());
2134 assert(SI->mayStore() && "Unexpected start instruction");
2135 assert(EI->mayLoad() && "Unexpected end instruction");
2136 MachineOperand &SrcOp = SI->getOperand(2);
2137
2138 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2139 SrcOp.getSubReg() };
2140 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
2141 // The this-> is needed to unconfuse MSVC.
2142 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2143 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2144 if (FoundR == 0)
2145 continue;
2146
2147 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2148 MachineBasicBlock::iterator StartIt = SI, NextIt;
2149 MachineInstr *CopyIn = nullptr;
2150 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00002151 const DebugLoc &DL = SI->getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002152 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2153 .addOperand(SrcOp);
2154 }
2155
2156 ++StartIt;
2157 // Check if this is a last store and the FI is live-on-exit.
2158 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2159 // Update store's source register.
2160 if (unsigned SR = SrcOp.getSubReg())
2161 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2162 else
2163 SrcOp.setReg(FoundR);
2164 SrcOp.setSubReg(0);
2165 // We are keeping this register live.
2166 SrcOp.setIsKill(false);
2167 } else {
2168 B.erase(SI);
2169 IM.replaceInstr(SI, CopyIn);
2170 }
2171
2172 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2173 for (auto It = StartIt; It != EndIt; It = NextIt) {
2174 MachineInstr *MI = &*It;
2175 NextIt = std::next(It);
2176 int TFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002177 if (!HII.isLoadFromStackSlot(*MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002178 continue;
2179 unsigned DstR = MI->getOperand(0).getReg();
2180 assert(MI->getOperand(0).getSubReg() == 0);
2181 MachineInstr *CopyOut = nullptr;
2182 if (DstR != FoundR) {
2183 DebugLoc DL = MI->getDebugLoc();
2184 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2185 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2186 unsigned CopyOpc = TargetOpcode::COPY;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002187 if (HII.isSignExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002188 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002189 else if (HII.isZeroExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002190 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2191 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2192 .addReg(FoundR, getKillRegState(MI == EI));
2193 }
2194 IM.replaceInstr(MI, CopyOut);
2195 B.erase(It);
2196 }
2197
2198 // Update the dead map.
2199 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2200 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2201 DM[RR].subtract(Range);
2202 } // for Range in range list
2203 }
2204 }
2205}
2206
2207
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002208void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002209 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002210 MachineBasicBlock &MB = *AI->getParent();
2211 DebugLoc DL = AI->getDebugLoc();
2212 unsigned A = AI->getOperand(2).getImm();
2213
2214 // Have
2215 // Rd = alloca Rs, #A
2216 //
2217 // If Rs and Rd are different registers, use this sequence:
2218 // Rd = sub(r29, Rs)
2219 // r29 = sub(r29, Rs)
2220 // Rd = and(Rd, #-A) ; if necessary
2221 // r29 = and(r29, #-A) ; if necessary
2222 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2223 // otherwise, do
2224 // Rd = sub(r29, Rs)
2225 // Rd = and(Rd, #-A) ; if necessary
2226 // r29 = Rd
2227 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2228
2229 MachineOperand &RdOp = AI->getOperand(0);
2230 MachineOperand &RsOp = AI->getOperand(1);
2231 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2232
2233 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002234 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002235 .addReg(SP)
2236 .addReg(Rs);
2237 if (Rs != Rd) {
2238 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002239 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002240 .addReg(SP)
2241 .addReg(Rs);
2242 }
2243 if (A > 8) {
2244 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002245 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002246 .addReg(Rd)
2247 .addImm(-int64_t(A));
2248 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002249 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002250 .addReg(SP)
2251 .addImm(-int64_t(A));
2252 }
2253 if (Rs == Rd) {
2254 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002255 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002256 .addReg(Rd);
2257 }
2258 if (CF > 0) {
2259 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002260 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002261 .addReg(Rd)
2262 .addImm(CF);
2263 }
2264}
2265
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002266
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002267bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2268 const MachineFrameInfo *MFI = MF.getFrameInfo();
2269 if (!MFI->hasVarSizedObjects())
2270 return false;
2271 unsigned MaxA = MFI->getMaxAlignment();
2272 if (MaxA <= getStackAlignment())
2273 return false;
2274 return true;
2275}
2276
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002277
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002278const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2279 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002280 for (auto &B : MF)
2281 for (auto &I : B)
2282 if (I.getOpcode() == Hexagon::ALIGNA)
2283 return &I;
2284 return nullptr;
2285}
2286
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002287
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002288/// Adds all callee-saved registers as implicit uses or defs to the
2289/// instruction.
2290void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2291 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2292 // Add the callee-saved registers as implicit uses.
2293 for (auto &R : CSI)
2294 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2295}
2296
2297
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002298/// Determine whether the callee-saved register saves and restores should
2299/// be generated via inline code. If this function returns "true", inline
2300/// code will be generated. If this function returns "false", additional
2301/// checks are performed, which may still lead to the inline code.
2302bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2303 const CSIVect &CSI) const {
2304 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2305 return true;
2306 if (!isOptSize(MF) && !isMinSize(MF))
2307 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2308 return true;
2309
2310 // Check if CSI only has double registers, and if the registers form
2311 // a contiguous block starting from D8.
2312 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2313 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2314 unsigned R = CSI[i].getReg();
2315 if (!Hexagon::DoubleRegsRegClass.contains(R))
2316 return true;
2317 Regs[R] = true;
2318 }
2319 int F = Regs.find_first();
2320 if (F != Hexagon::D8)
2321 return true;
2322 while (F >= 0) {
2323 int N = Regs.find_next(F);
2324 if (N >= 0 && N != F+1)
2325 return true;
2326 F = N;
2327 }
2328
2329 return false;
2330}
2331
2332
2333bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2334 const CSIVect &CSI) const {
2335 if (shouldInlineCSR(MF, CSI))
2336 return false;
2337 unsigned NumCSI = CSI.size();
2338 if (NumCSI <= 1)
2339 return false;
2340
2341 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2342 : SpillFuncThreshold;
2343 return Threshold < NumCSI;
2344}
2345
2346
2347bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2348 const CSIVect &CSI) const {
2349 if (shouldInlineCSR(MF, CSI))
2350 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002351 // The restore functions do a bit more than just restoring registers.
2352 // The non-returning versions will go back directly to the caller's
2353 // caller, others will clean up the stack frame in preparation for
2354 // a tail call. Using them can still save code size even if only one
2355 // register is getting restores. Make the decision based on -Oz:
2356 // using -Os will use inline restore for a single register.
2357 if (isMinSize(MF))
2358 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002359 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002360 if (NumCSI <= 1)
2361 return false;
2362
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002363 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2364 : SpillFuncThreshold;
2365 return Threshold < NumCSI;
2366}