blob: 9c177c219622b9386e9a245280a71763d8831e00 [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 Parzyszekdc421642016-07-27 20:58:43 +0000162#ifndef NDEBUG
163static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
164 cl::init(UINT_MAX));
165static unsigned SpillOptCount = 0;
166#endif
167
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000168
169namespace llvm {
170 void initializeHexagonCallFrameInformationPass(PassRegistry&);
171 FunctionPass *createHexagonCallFrameInformation();
172}
173
174namespace {
175 class HexagonCallFrameInformation : public MachineFunctionPass {
176 public:
177 static char ID;
178 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
179 PassRegistry &PR = *PassRegistry::getPassRegistry();
180 initializeHexagonCallFrameInformationPass(PR);
181 }
182 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000183 MachineFunctionProperties getRequiredProperties() const override {
184 return MachineFunctionProperties().set(
185 MachineFunctionProperties::Property::AllVRegsAllocated);
186 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000187 };
188
189 char HexagonCallFrameInformation::ID = 0;
190}
191
192bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
193 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
194 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
195 MF.getFunction()->needsUnwindTableEntry();
196
197 if (!NeedCFI)
198 return false;
199 HFI.insertCFIInstructions(MF);
200 return true;
201}
202
203INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
204 "Hexagon call frame information", false, false)
205
206FunctionPass *llvm::createHexagonCallFrameInformation() {
207 return new HexagonCallFrameInformation();
208}
209
210
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000211namespace {
212 /// Map a register pair Reg to the subregister that has the greater "number",
213 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
214 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
215 bool hireg = true) {
216 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
217 return Reg;
218
219 unsigned RegNo = 0;
220 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
221 if (hireg) {
222 if (*SubRegs > RegNo)
223 RegNo = *SubRegs;
224 } else {
225 if (!RegNo || *SubRegs < RegNo)
226 RegNo = *SubRegs;
227 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000228 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000229 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000230 }
231
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000232 /// Returns the callee saved register with the largest id in the vector.
233 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
234 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000235 static_assert(Hexagon::R1 > 0,
236 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000237 if (CSI.empty())
238 return 0;
239
240 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
241 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
242 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
243 if (Reg > Max)
244 Max = Reg;
245 }
246 return Max;
247 }
248
249 /// Checks if the basic block contains any instruction that needs a stack
250 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000251 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
252 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000253 for (auto &I : MBB) {
254 const MachineInstr *MI = &I;
255 if (MI->isCall())
256 return true;
257 unsigned Opc = MI->getOpcode();
258 switch (Opc) {
259 case Hexagon::ALLOCA:
260 case Hexagon::ALIGNA:
261 return true;
262 default:
263 break;
264 }
265 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000266 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 // While the presence of a frame index does not prove that a stack
268 // frame will be required, all frame indexes should be within alloc-
269 // frame/deallocframe. Otherwise, the code that translates a frame
270 // index into an offset would have to be aware of the placement of
271 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000272 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000273 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000274 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000275 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000276 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000277 // Virtual registers will need scavenging, which then may require
278 // a stack slot.
279 if (TargetRegisterInfo::isVirtualRegister(R))
280 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000281 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
282 if (CSR[*S])
283 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000284 }
285 }
286 return false;
287 }
288
289 /// Returns true if MBB has a machine instructions that indicates a tail call
290 /// in the block.
291 bool hasTailCall(const MachineBasicBlock &MBB) {
292 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
293 unsigned RetOpc = I->getOpcode();
294 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
295 }
296
297 /// Returns true if MBB contains an instruction that returns.
298 bool hasReturn(const MachineBasicBlock &MBB) {
299 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
300 if (I->isReturn())
301 return true;
302 return false;
303 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000304
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000305 /// Returns the "return" instruction from this block, or nullptr if there
306 /// isn't any.
307 MachineInstr *getReturn(MachineBasicBlock &MBB) {
308 for (auto &I : MBB)
309 if (I.isReturn())
310 return &I;
311 return nullptr;
312 }
313
314 bool isRestoreCall(unsigned Opc) {
315 switch (Opc) {
316 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
317 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000318 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
319 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
320 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
321 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000322 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
323 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
324 return true;
325 }
326 return false;
327 }
328
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000329 inline bool isOptNone(const MachineFunction &MF) {
330 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
331 MF.getTarget().getOptLevel() == CodeGenOpt::None;
332 }
333
334 inline bool isOptSize(const MachineFunction &MF) {
335 const Function &F = *MF.getFunction();
336 return F.optForSize() && !F.optForMinSize();
337 }
338
339 inline bool isMinSize(const MachineFunction &MF) {
340 return MF.getFunction()->optForMinSize();
341 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000342}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000343
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000344
345/// Implements shrink-wrapping of the stack frame. By default, stack frame
346/// is created in the function entry block, and is cleaned up in every block
347/// that returns. This function finds alternate blocks: one for the frame
348/// setup (prolog) and one for the cleanup (epilog).
349void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
350 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
351 static unsigned ShrinkCounter = 0;
352
353 if (ShrinkLimit.getPosition()) {
354 if (ShrinkCounter >= ShrinkLimit)
355 return;
356 ShrinkCounter++;
357 }
358
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000359 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000360 auto &HRI = *HST.getRegisterInfo();
361
362 MachineDominatorTree MDT;
363 MDT.runOnMachineFunction(MF);
364 MachinePostDominatorTree MPT;
365 MPT.runOnMachineFunction(MF);
366
367 typedef DenseMap<unsigned,unsigned> UnsignedMap;
368 UnsignedMap RPO;
369 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
370 RPOTType RPOT(&MF);
371 unsigned RPON = 0;
372 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
373 RPO[(*I)->getNumber()] = RPON++;
374
375 // Don't process functions that have loops, at least for now. Placement
376 // of prolog and epilog must take loop structure into account. For simpli-
377 // city don't do it right now.
378 for (auto &I : MF) {
379 unsigned BN = RPO[I.getNumber()];
380 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
381 // If found a back-edge, return.
382 if (RPO[(*SI)->getNumber()] <= BN)
383 return;
384 }
385 }
386
387 // Collect the set of blocks that need a stack frame to execute. Scan
388 // each block for uses/defs of callee-saved registers, calls, etc.
389 SmallVector<MachineBasicBlock*,16> SFBlocks;
390 BitVector CSR(Hexagon::NUM_TARGET_REGS);
391 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000392 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
393 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000394
395 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000396 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000397 SFBlocks.push_back(&I);
398
399 DEBUG({
400 dbgs() << "Blocks needing SF: {";
401 for (auto &B : SFBlocks)
402 dbgs() << " BB#" << B->getNumber();
403 dbgs() << " }\n";
404 });
405 // No frame needed?
406 if (SFBlocks.empty())
407 return;
408
409 // Pick a common dominator and a common post-dominator.
410 MachineBasicBlock *DomB = SFBlocks[0];
411 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
412 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
413 if (!DomB)
414 break;
415 }
416 MachineBasicBlock *PDomB = SFBlocks[0];
417 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
418 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
419 if (!PDomB)
420 break;
421 }
422 DEBUG({
423 dbgs() << "Computed dom block: BB#";
424 if (DomB) dbgs() << DomB->getNumber();
425 else dbgs() << "<null>";
426 dbgs() << ", computed pdom block: BB#";
427 if (PDomB) dbgs() << PDomB->getNumber();
428 else dbgs() << "<null>";
429 dbgs() << "\n";
430 });
431 if (!DomB || !PDomB)
432 return;
433
434 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
435 if (!MDT.dominates(DomB, PDomB)) {
436 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
437 return;
438 }
439 if (!MPT.dominates(PDomB, DomB)) {
440 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
441 return;
442 }
443
444 // Finally, everything seems right.
445 PrologB = DomB;
446 EpilogB = PDomB;
447}
448
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000449
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000450/// Perform most of the PEI work here:
451/// - saving/restoring of the callee-saved registers,
452/// - stack frame creation and destruction.
453/// Normally, this work is distributed among various functions, but doing it
454/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000455void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
456 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000457 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000458 auto &HRI = *HST.getRegisterInfo();
459
460 MachineFrameInfo *MFI = MF.getFrameInfo();
461 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
462
463 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
464 if (EnableShrinkWrapping)
465 findShrunkPrologEpilog(MF, PrologB, EpilogB);
466
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000467 bool PrologueStubs = false;
468 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
469 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000470 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000471
472 if (EpilogB) {
473 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
474 insertEpilogueInBlock(*EpilogB);
475 } else {
476 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000477 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000478 insertCSRRestoresInBlock(B, CSI, HRI);
479
480 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000481 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000482 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000483
484 for (auto &B : MF) {
485 if (B.empty())
486 continue;
487 MachineInstr *RetI = getReturn(B);
488 if (!RetI || isRestoreCall(RetI->getOpcode()))
489 continue;
490 for (auto &R : CSI)
491 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
492 }
493 }
494
495 if (EpilogB) {
496 // If there is an epilog block, it may not have a return instruction.
497 // In such case, we need to add the callee-saved registers as live-ins
498 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000499 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000500 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000501 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000502 }
503}
504
505
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000506void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
507 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000508 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000509 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000510 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000511 auto &HII = *HST.getInstrInfo();
512 auto &HRI = *HST.getRegisterInfo();
513 DebugLoc dl;
514
515 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
516
517 // Calculate the total stack frame size.
518 // Get the number of bytes to allocate from the FrameInfo.
519 unsigned FrameSize = MFI->getStackSize();
520 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000521 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000522 MFI->setMaxCallFrameSize(MaxCFA);
523
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000524 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000525 MFI->setStackSize(FrameSize);
526
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000527 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000528
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000529 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000530 unsigned NumBytes = MFI->getStackSize();
531 unsigned SP = HRI.getStackRegister();
532 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000533 MachineBasicBlock::iterator InsertPt = MBB.begin();
534
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000535 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
536 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000537
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000538 for (auto MI : AdjustRegs) {
539 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
540 expandAlloca(MI, HII, SP, MaxCF);
541 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000542 }
543
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000544 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000545 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000546
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000547 // Check for overflow.
548 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
549 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000550
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000551 // Create a dummy memory operand to avoid allocframe from being treated as
552 // a volatile memory reference.
553 MachineMemOperand *MMO =
554 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
555 4, 4);
556
557 if (NumBytes >= ALLOCFRAME_MAX) {
558 // Emit allocframe(#0).
559 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
560 .addImm(0)
561 .addMemOperand(MMO);
562
563 // Subtract offset from frame pointer.
564 // We use a caller-saved non-parameter register for that.
565 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
566 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
567 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000568 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
569 .addReg(SP)
570 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000571 } else {
572 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
573 .addImm(NumBytes)
574 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000575 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000576
577 if (AlignStack) {
578 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
579 .addReg(SP)
580 .addImm(-int64_t(MaxAlign));
581 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000582
583 // If the stack-checking is enabled, and we spilled the callee-saved
584 // registers inline (i.e. did not use a spill function), then call
585 // the stack checker directly.
586 if (EnableStackOVFSanitizer && !PrologueStubs)
587 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
588 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000589}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000590
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000591void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
592 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000593 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000594 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000595
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000596 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000597 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000598 auto &HRI = *HST.getRegisterInfo();
599 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000600
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000601 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000602 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
603
604 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
605 DebugLoc DL;
606 if (InsertPt != MBB.end())
607 DL = InsertPt->getDebugLoc();
608 else if (!MBB.empty())
609 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000610
611 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000612 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000613 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
614 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
615 .addReg(SP)
616 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000617 return;
618 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000619
620 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
621 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000622 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000623 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
624 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
625 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000626 MachineBasicBlock::iterator It = RetI;
627 ++It;
628 // Delete all instructions after the RESTORE (except labels).
629 while (It != MBB.end()) {
630 if (!It->isLabel())
631 It = MBB.erase(It);
632 else
633 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000634 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000635 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000636 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000637
638 // It is possible that the restoring code is a call to a library function.
639 // All of the restore* functions include "deallocframe", so we need to make
640 // sure that we don't add an extra one.
641 bool NeedsDeallocframe = true;
642 if (!MBB.empty() && InsertPt != MBB.begin()) {
643 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
644 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000645 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000646 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
647 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
648 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
649 COpc == Hexagon::CALLv3nr || COpc == Hexagon::CALLRv3nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000650 NeedsDeallocframe = false;
651 }
652
653 if (!NeedsDeallocframe)
654 return;
655 // If the returning instruction is JMPret, replace it with dealloc_return,
656 // otherwise just add deallocframe. The function could be returning via a
657 // tail call.
658 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
659 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
660 return;
661 }
662 unsigned NewOpc = Hexagon::L4_return;
663 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
664 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000665 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000666 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000667}
668
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000669void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
670 MachineBasicBlock &SaveB) const {
671 SetVector<unsigned> Worklist;
672
673 MachineBasicBlock &EntryB = MF.front();
674 Worklist.insert(EntryB.getNumber());
675
676 unsigned SaveN = SaveB.getNumber();
677 auto &CSI = MF.getFrameInfo()->getCalleeSavedInfo();
678
679 for (unsigned i = 0; i < Worklist.size(); ++i) {
680 unsigned BN = Worklist[i];
681 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
682 for (auto &R : CSI)
683 if (!MBB.isLiveIn(R.getReg()))
684 MBB.addLiveIn(R.getReg());
685 if (BN != SaveN)
686 for (auto &SB : MBB.successors())
687 Worklist.insert(SB->getNumber());
688 }
689}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000690
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000691bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000692 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000693 BitVector &Path) const {
694 assert(MBB.getNumber() >= 0);
695 unsigned BN = MBB.getNumber();
696 if (Path[BN] || DoneF[BN])
697 return false;
698 if (DoneT[BN])
699 return true;
700
701 auto &CSI = MBB.getParent()->getFrameInfo()->getCalleeSavedInfo();
702
703 Path[BN] = true;
704 bool ReachedExit = false;
705 for (auto &SB : MBB.successors())
706 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
707
708 if (!MBB.empty() && MBB.back().isReturn()) {
709 // Add implicit uses of all callee-saved registers to the reached
710 // return instructions. This is to prevent the anti-dependency breaker
711 // from renaming these registers.
712 MachineInstr &RetI = MBB.back();
713 if (!isRestoreCall(RetI.getOpcode()))
714 for (auto &R : CSI)
715 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
716 ReachedExit = true;
717 }
718
719 // We don't want to add unnecessary live-ins to the restore block: since
720 // the callee-saved registers are being defined in it, the entry of the
721 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000722 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000723 for (auto &R : CSI)
724 if (!MBB.isLiveIn(R.getReg()))
725 MBB.addLiveIn(R.getReg());
726 DoneT[BN] = true;
727 }
728 if (!ReachedExit)
729 DoneF[BN] = true;
730
731 Path[BN] = false;
732 return ReachedExit;
733}
734
735
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000736namespace {
737 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
738 if (!It->isBundle())
739 return It->getOpcode() == Hexagon::S2_allocframe;
740 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000741 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000742 while (++I != End && I->isBundled())
743 if (I->getOpcode() == Hexagon::S2_allocframe)
744 return true;
745 return false;
746 }
747
748 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
749 for (auto &I : B)
750 if (IsAllocFrame(I))
751 return I;
752 return B.end();
753 }
754}
755
756
757void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
758 for (auto &B : MF) {
759 auto AF = FindAllocFrame(B);
760 if (AF == B.end())
761 continue;
762 insertCFIInstructionsAt(B, ++AF);
763 }
764}
765
766
767void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
768 MachineBasicBlock::iterator At) const {
769 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000770 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000771 MachineModuleInfo &MMI = MF.getMMI();
772 auto &HST = MF.getSubtarget<HexagonSubtarget>();
773 auto &HII = *HST.getInstrInfo();
774 auto &HRI = *HST.getRegisterInfo();
775
776 // If CFI instructions have debug information attached, something goes
777 // wrong with the final assembly generation: the prolog_end is placed
778 // in a wrong location.
779 DebugLoc DL;
780 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
781
782 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000783 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000784
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000785 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000786 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
787 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000788
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000789 // Define CFA via an offset from the value of FP.
790 //
791 // -8 -4 0 (SP)
792 // --+----+----+---------------------
793 // | FP | LR | increasing addresses -->
794 // --+----+----+---------------------
795 // | +-- Old SP (before allocframe)
796 // +-- New FP (after allocframe)
797 //
798 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
799 // MCCFIInstruction::createOffset takes the offset without sign change.
800 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
801 BuildMI(MBB, At, DL, CFID)
802 .addCFIIndex(MMI.addFrameInst(DefCfa));
803 // R31 (return addr) = CFA - 4
804 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
805 BuildMI(MBB, At, DL, CFID)
806 .addCFIIndex(MMI.addFrameInst(OffR31));
807 // R30 (frame ptr) = CFA - 8
808 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
809 BuildMI(MBB, At, DL, CFID)
810 .addCFIIndex(MMI.addFrameInst(OffR30));
811 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000812
813 static unsigned int RegsToMove[] = {
814 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
815 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
816 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
817 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
818 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
819 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
820 Hexagon::NoRegister
821 };
822
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000823 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000824
825 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
826 unsigned Reg = RegsToMove[i];
827 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
828 return C.getReg() == Reg;
829 };
830 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
831 if (F == CSI.end())
832 continue;
833
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000834 int64_t Offset;
835 if (HasFP) {
836 // If the function has a frame pointer (i.e. has an allocframe),
837 // then the CFA has been defined in terms of FP. Any offsets in
838 // the following CFI instructions have to be defined relative
839 // to FP, which points to the bottom of the stack frame.
840 // The function getFrameIndexReference can still choose to use SP
841 // for the offset calculation, so we cannot simply call it here.
842 // Instead, get the offset (relative to the FP) directly.
843 Offset = MFI.getObjectOffset(F->getFrameIdx());
844 } else {
845 unsigned FrameReg;
846 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
847 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000848 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000849 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000850
851 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
852 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
853 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
854 Offset);
855 BuildMI(MBB, At, DL, CFID)
856 .addCFIIndex(MMI.addFrameInst(OffReg));
857 } else {
858 // Split the double regs into subregs, and generate appropriate
859 // cfi_offsets.
860 // The only reason, we are split double regs is, llvm-mc does not
861 // understand paired registers for cfi_offset.
862 // Eg .cfi_offset r1:0, -64
863
864 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
865 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
866 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
867 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
868 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
869 Offset+4);
870 BuildMI(MBB, At, DL, CFID)
871 .addCFIIndex(MMI.addFrameInst(OffHi));
872 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
873 Offset);
874 BuildMI(MBB, At, DL, CFID)
875 .addCFIIndex(MMI.addFrameInst(OffLo));
876 }
877 }
878}
879
880
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000881bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000882 auto &MFI = *MF.getFrameInfo();
883 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
884
885 bool HasFixed = MFI.getNumFixedObjects();
886 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
887 .getLocalFrameObjectCount();
888 bool HasExtraAlign = HRI.needsStackRealignment(MF);
889 bool HasAlloca = MFI.hasVarSizedObjects();
890
891 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
892 // that this shouldn't be required, but doing so now because gcc does and
893 // gdb can't break at the start of the function without it. Will remove if
894 // this turns out to be a gdb bug.
895 //
896 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
897 return true;
898
899 // By default we want to use SP (since it's always there). FP requires
900 // some setup (i.e. ALLOCFRAME).
901 // Fixed and preallocated objects need FP if the distance from them to
902 // the SP is unknown (as is with alloca or aligna).
903 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
904 return true;
905
906 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000907 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000908 return true;
909 }
910
911 if (MFI.hasCalls() ||
912 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
913 return true;
914
915 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000916}
917
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000918
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000919enum SpillKind {
920 SK_ToMem,
921 SK_FromMem,
922 SK_FromMemTailcall
923};
924
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000925static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
926 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000927 const char * V4SpillToMemoryFunctions[] = {
928 "__save_r16_through_r17",
929 "__save_r16_through_r19",
930 "__save_r16_through_r21",
931 "__save_r16_through_r23",
932 "__save_r16_through_r25",
933 "__save_r16_through_r27" };
934
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000935 const char * V4SpillToMemoryStkchkFunctions[] = {
936 "__save_r16_through_r17_stkchk",
937 "__save_r16_through_r19_stkchk",
938 "__save_r16_through_r21_stkchk",
939 "__save_r16_through_r23_stkchk",
940 "__save_r16_through_r25_stkchk",
941 "__save_r16_through_r27_stkchk" };
942
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000943 const char * V4SpillFromMemoryFunctions[] = {
944 "__restore_r16_through_r17_and_deallocframe",
945 "__restore_r16_through_r19_and_deallocframe",
946 "__restore_r16_through_r21_and_deallocframe",
947 "__restore_r16_through_r23_and_deallocframe",
948 "__restore_r16_through_r25_and_deallocframe",
949 "__restore_r16_through_r27_and_deallocframe" };
950
951 const char * V4SpillFromMemoryTailcallFunctions[] = {
952 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
953 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
954 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
955 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
956 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
957 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
958 };
959
960 const char **SpillFunc = nullptr;
961
962 switch(SpillType) {
963 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000964 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
965 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000966 break;
967 case SK_FromMem:
968 SpillFunc = V4SpillFromMemoryFunctions;
969 break;
970 case SK_FromMemTailcall:
971 SpillFunc = V4SpillFromMemoryTailcallFunctions;
972 break;
973 }
974 assert(SpillFunc && "Unknown spill kind");
975
976 // Spill all callee-saved registers up to the highest register used.
977 switch (MaxReg) {
978 case Hexagon::R17:
979 return SpillFunc[0];
980 case Hexagon::R19:
981 return SpillFunc[1];
982 case Hexagon::R21:
983 return SpillFunc[2];
984 case Hexagon::R23:
985 return SpillFunc[3];
986 case Hexagon::R25:
987 return SpillFunc[4];
988 case Hexagon::R27:
989 return SpillFunc[5];
990 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000991 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000992 }
993 return 0;
994}
995
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000996
James Y Knight5567baf2015-08-15 02:32:35 +0000997int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000998 int FI, unsigned &FrameReg) const {
999 auto &MFI = *MF.getFrameInfo();
1000 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001001
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001002 int Offset = MFI.getObjectOffset(FI);
1003 bool HasAlloca = MFI.hasVarSizedObjects();
1004 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1005 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001006
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001007 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001008 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1009 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001010 unsigned FrameSize = MFI.getStackSize();
1011
1012 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1013 // Use FP at -O0, except when there are objects with extra alignment.
1014 // That additional alignment requirement may cause a pad to be inserted,
1015 // which will make it impossible to use FP to access objects located
1016 // past the pad.
1017 if (NoOpt && !HasExtraAlign)
1018 UseFP = true;
1019 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1020 // Fixed and preallocated objects will be located before any padding
1021 // so FP must be used to access them.
1022 UseFP |= (HasAlloca || HasExtraAlign);
1023 } else {
1024 if (HasAlloca) {
1025 if (HasExtraAlign)
1026 UseAP = true;
1027 else
1028 UseFP = true;
1029 }
1030 }
1031
1032 // If FP was picked, then there had better be FP.
1033 bool HasFP = hasFP(MF);
1034 assert((HasFP || !UseFP) && "This function must have frame pointer");
1035
1036 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1037 // FP/LR. If the base register is used to access an object across these
1038 // 8 bytes, then the offset will need to be adjusted by 8.
1039 //
1040 // After allocframe:
1041 // HexagonISelLowering adds 8 to ---+
1042 // the offsets of all stack-based |
1043 // arguments (*) |
1044 // |
1045 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1046 // ------------------------+-----+------------------------> increasing
1047 // <local objects> |FP/LR| <input arguments> addresses
1048 // -----------------+------+-----+------------------------>
1049 // | |
1050 // SP/AP point --+ +-- FP points here (**)
1051 // somewhere on
1052 // this side of FP/LR
1053 //
1054 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1055 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1056
1057 // The lowering assumes that FP/LR is present, and so the offsets of
1058 // the formal arguments start at 8. If FP/LR is not there we need to
1059 // reduce the offset by 8.
1060 if (Offset > 0 && !HasFP)
1061 Offset -= 8;
1062
1063 if (UseFP)
1064 FrameReg = FP;
1065 else if (UseAP)
1066 FrameReg = AP;
1067 else
1068 FrameReg = SP;
1069
1070 // Calculate the actual offset in the instruction. If there is no FP
1071 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1072 // there will be no SP -= FrameSize), so the frame size should not be
1073 // added to the calculated offset.
1074 int RealOffset = Offset;
1075 if (!UseFP && !UseAP && HasFP)
1076 RealOffset = FrameSize+Offset;
1077 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001078}
1079
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001080
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001081bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001082 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1083 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001084 if (CSI.empty())
1085 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001086
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001087 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001088 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001089 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001090 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1091 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001092
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001093 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001094 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001095 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001096 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1097 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1098 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001099 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001100 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001101 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001102
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001103 // Call spill function.
1104 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001105 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001106 if (StkOvrFlowEnabled) {
1107 if (LongCalls)
1108 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1109 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1110 else
1111 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1112 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1113 } else {
1114 if (LongCalls)
1115 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1116 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1117 else
1118 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1119 : Hexagon::SAVE_REGISTERS_CALL_V4;
1120 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001121
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001122 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001123 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001124 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001125
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001126 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001127 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001128 // Add live in registers.
1129 for (unsigned I = 0; I < CSI.size(); ++I)
1130 MBB.addLiveIn(CSI[I].getReg());
1131 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001132 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001133
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001134 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001135 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001136 // Add live in registers. We treat eh_return callee saved register r0 - r3
1137 // specially. They are not really callee saved registers as they are not
1138 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001139 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1140 int FI = CSI[i].getFrameIdx();
1141 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001142 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001143 if (IsKill)
1144 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001145 }
1146 return true;
1147}
1148
1149
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001150bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1151 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1152 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001153 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001154
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001155 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1156 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001157 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1158 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001159
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001160 if (useRestoreFunction(MF, CSI)) {
1161 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1162 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1163 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1164 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001165 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001166 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001167 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001168
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001169 // Call spill function.
1170 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1171 : MBB.getLastNonDebugInstr()->getDebugLoc();
1172 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001173
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001174 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001175 unsigned RetOpc;
1176 if (LongCalls)
1177 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1178 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1179 else
1180 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1181 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1182 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001183 .addExternalSymbol(RestoreFn);
1184 } else {
1185 // The block has a return.
1186 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1187 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001188 unsigned RetOpc;
1189 if (LongCalls)
1190 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1191 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1192 else
1193 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1194 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1195 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001196 .addExternalSymbol(RestoreFn);
1197 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001198 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001199 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001200 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001201 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001202 }
1203
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001204 for (unsigned i = 0; i < CSI.size(); ++i) {
1205 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001206 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1207 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001208 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001209 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001210
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001211 return true;
1212}
1213
Hans Wennborge1a2e902016-03-31 18:33:38 +00001214MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1215 MachineFunction &MF, MachineBasicBlock &MBB,
1216 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001217 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001218 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001219 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001220 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1221 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001222 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001223}
1224
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001225
1226void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1227 MachineFunction &MF, RegScavenger *RS) const {
1228 // If this function has uses aligned stack and also has variable sized stack
1229 // objects, then we need to map all spill slots to fixed positions, so that
1230 // they can be accessed through FP. Otherwise they would have to be accessed
1231 // via AP, which may not be available at the particular place in the program.
1232 MachineFrameInfo *MFI = MF.getFrameInfo();
1233 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001234 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001235
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001236 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001237 return;
1238
1239 unsigned LFS = MFI->getLocalFrameSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001240 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1241 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1242 continue;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001243 unsigned S = MFI->getObjectSize(i);
1244 // Reduce the alignment to at most 8. This will require unaligned vector
1245 // stores if they happen here.
1246 unsigned A = std::max(MFI->getObjectAlignment(i), 8U);
1247 MFI->setObjectAlignment(i, 8);
1248 LFS = alignTo(LFS+S, A);
1249 MFI->mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001250 }
1251
1252 MFI->setLocalFrameSize(LFS);
1253 unsigned A = MFI->getLocalFrameMaxAlign();
1254 assert(A <= 8 && "Unexpected local frame alignment");
1255 if (A == 0)
1256 MFI->setLocalFrameMaxAlign(8);
1257 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001258
1259 // Set the physical aligned-stack base address register.
1260 unsigned AP = 0;
1261 if (const MachineInstr *AI = getAlignaInstr(MF))
1262 AP = AI->getOperand(0).getReg();
1263 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1264 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001265}
1266
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001267/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001268static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001269 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001270 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001271
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001272 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1273 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1274 if (MRI.isPhysRegUsed(*AI))
1275 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001276 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001277 };
1278
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001279 // Check for an unused caller-saved register. Callee-saved registers
1280 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001281 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001282 if (!IsUsed(*P))
1283 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001284
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001285 // All caller-saved registers are used.
1286 return true;
1287}
1288
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001289
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001290#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001291static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001292 dbgs() << '{';
1293 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1294 unsigned R = x;
1295 dbgs() << ' ' << PrintReg(R, &TRI);
1296 }
1297 dbgs() << " }";
1298}
1299#endif
1300
1301
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001302bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1303 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001304 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001305 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001306 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001307 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001308
1309 // Generate a set of unique, callee-saved registers (SRegs), where each
1310 // register in the set is maximal in terms of sub-/super-register relation,
1311 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1312
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001313 // (1) For each callee-saved register, add that register and all of its
1314 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001315 DEBUG(dbgs() << "Initial CS registers: {");
1316 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1317 unsigned R = CSI[i].getReg();
1318 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1319 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1320 SRegs[*SR] = true;
1321 }
1322 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001323 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001324
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001325 // (2) For each reserved register, remove that register and all of its
1326 // sub- and super-registers from SRegs.
1327 BitVector Reserved = TRI->getReservedRegs(MF);
1328 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1329 unsigned R = x;
1330 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1331 SRegs[*SR] = false;
1332 }
1333 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1334 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1335
1336 // (3) Collect all registers that have at least one sub-register in SRegs,
1337 // and also have no sub-registers that are reserved. These will be the can-
1338 // didates for saving as a whole instead of their individual sub-registers.
1339 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1340 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001341 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1342 unsigned R = x;
1343 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1344 TmpSup[*SR] = true;
1345 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001346 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1347 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001348 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1349 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001350 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001351 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001352 break;
1353 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001354 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001355 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001356
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001357 // (4) Include all super-registers found in (3) into SRegs.
1358 SRegs |= TmpSup;
1359 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001360
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001361 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001362 // remove R from SRegs.
1363 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1364 unsigned R = x;
1365 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1366 if (!SRegs[*SR])
1367 continue;
1368 SRegs[R] = false;
1369 break;
1370 }
1371 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001372 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001373
1374 // Now, for each register that has a fixed stack slot, create the stack
1375 // object for it.
1376 CSI.clear();
1377
1378 typedef TargetFrameLowering::SpillSlot SpillSlot;
1379 unsigned NumFixed;
1380 int MinOffset = 0; // CS offsets are negative.
1381 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1382 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1383 if (!SRegs[S->Reg])
1384 continue;
1385 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1386 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1387 MinOffset = std::min(MinOffset, S->Offset);
1388 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1389 SRegs[S->Reg] = false;
1390 }
1391
1392 // There can be some registers that don't have fixed slots. For example,
1393 // we need to store R0-R3 in functions with exception handling. For each
1394 // such register, create a non-fixed stack object.
1395 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1396 unsigned R = x;
1397 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1398 int Off = MinOffset - RC->getSize();
1399 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1400 assert(isPowerOf2_32(Align));
1401 Off &= -Align;
1402 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1403 MinOffset = std::min(MinOffset, Off);
1404 CSI.push_back(CalleeSavedInfo(R, FI));
1405 SRegs[R] = false;
1406 }
1407
1408 DEBUG({
1409 dbgs() << "CS information: {";
1410 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1411 int FI = CSI[i].getFrameIdx();
1412 int Off = MFI->getObjectOffset(FI);
1413 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1414 if (Off >= 0)
1415 dbgs() << '+';
1416 dbgs() << Off;
1417 }
1418 dbgs() << " }\n";
1419 });
1420
1421#ifndef NDEBUG
1422 // Verify that all registers were handled.
1423 bool MissedReg = false;
1424 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1425 unsigned R = x;
1426 dbgs() << PrintReg(R, TRI) << ' ';
1427 MissedReg = true;
1428 }
1429 if (MissedReg)
1430 llvm_unreachable("...there are unhandled callee-saved registers!");
1431#endif
1432
1433 return true;
1434}
1435
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001436bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1437 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1438 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1439 MachineInstr *MI = &*It;
1440 DebugLoc DL = MI->getDebugLoc();
1441 unsigned DstR = MI->getOperand(0).getReg();
1442 unsigned SrcR = MI->getOperand(1).getReg();
1443 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1444 !Hexagon::ModRegsRegClass.contains(SrcR))
1445 return false;
1446
1447 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1448 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1449 .addOperand(MI->getOperand(1));
1450 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1451 .addReg(TmpR, RegState::Kill);
1452
1453 NewRegs.push_back(TmpR);
1454 B.erase(It);
1455 return true;
1456}
1457
1458bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1459 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1460 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1461 MachineInstr *MI = &*It;
1462 DebugLoc DL = MI->getDebugLoc();
1463 unsigned Opc = MI->getOpcode();
1464 unsigned SrcR = MI->getOperand(2).getReg();
1465 bool IsKill = MI->getOperand(2).isKill();
1466
1467 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1468 int FI = MI->getOperand(0).getIndex();
1469
1470 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1471 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1472 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1473 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1474 : Hexagon::A2_tfrcrr;
1475 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1476 .addReg(SrcR, getKillRegState(IsKill));
1477
1478 // S2_storeri_io FI, 0, TmpR
1479 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1480 .addFrameIndex(FI)
1481 .addImm(0)
1482 .addReg(TmpR, RegState::Kill)
1483 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1484
1485 NewRegs.push_back(TmpR);
1486 B.erase(It);
1487 return true;
1488}
1489
1490bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1491 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1492 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1493 MachineInstr *MI = &*It;
1494 DebugLoc DL = MI->getDebugLoc();
1495 unsigned Opc = MI->getOpcode();
1496 unsigned DstR = MI->getOperand(0).getReg();
1497
1498 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1499 int FI = MI->getOperand(1).getIndex();
1500
1501 // TmpR = L2_loadri_io FI, 0
1502 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1503 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1504 .addFrameIndex(FI)
1505 .addImm(0)
1506 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1507
1508 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1509 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1510 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1511 : Hexagon::A2_tfrrcr;
1512 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1513 .addReg(TmpR, RegState::Kill);
1514
1515 NewRegs.push_back(TmpR);
1516 B.erase(It);
1517 return true;
1518}
1519
1520
1521bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1522 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1523 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1524 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1525 MachineInstr *MI = &*It;
1526 DebugLoc DL = MI->getDebugLoc();
1527 unsigned SrcR = MI->getOperand(2).getReg();
1528 bool IsKill = MI->getOperand(2).isKill();
1529
1530 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1531 int FI = MI->getOperand(0).getIndex();
1532
1533 bool Is128B = HST.useHVXDblOps();
1534 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1535 : &Hexagon::VectorRegs128BRegClass;
1536
1537 // Insert transfer to general vector register.
1538 // TmpR0 = A2_tfrsi 0x01010101
1539 // TmpR1 = V6_vandqrt Qx, TmpR0
1540 // store FI, 0, TmpR1
1541 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1542 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1543
1544 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1545 .addImm(0x01010101);
1546
1547 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1548 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1549 .addReg(SrcR, getKillRegState(IsKill))
1550 .addReg(TmpR0, RegState::Kill);
1551
1552 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1553 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1554 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1555
1556 NewRegs.push_back(TmpR0);
1557 NewRegs.push_back(TmpR1);
1558 B.erase(It);
1559 return true;
1560}
1561
1562bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1563 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1564 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1565 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1566 MachineInstr *MI = &*It;
1567 DebugLoc DL = MI->getDebugLoc();
1568 unsigned DstR = MI->getOperand(0).getReg();
1569
1570 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1571 int FI = MI->getOperand(1).getIndex();
1572
1573 bool Is128B = HST.useHVXDblOps();
1574 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1575 : &Hexagon::VectorRegs128BRegClass;
1576
1577 // TmpR0 = A2_tfrsi 0x01010101
1578 // TmpR1 = load FI, 0
1579 // DstR = V6_vandvrt TmpR1, TmpR0
1580 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1581 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1582
1583 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1584 .addImm(0x01010101);
1585 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1586 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1587 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1588
1589 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1590 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1591 .addReg(TmpR1, RegState::Kill)
1592 .addReg(TmpR0, RegState::Kill);
1593
1594 NewRegs.push_back(TmpR0);
1595 NewRegs.push_back(TmpR1);
1596 B.erase(It);
1597 return true;
1598}
1599
1600bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1601 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1602 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1603 MachineFunction &MF = *B.getParent();
1604 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1605 auto &MFI = *MF.getFrameInfo();
1606 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1607 MachineInstr *MI = &*It;
1608 DebugLoc DL = MI->getDebugLoc();
1609
1610 unsigned SrcR = MI->getOperand(2).getReg();
1611 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1612 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1613 bool IsKill = MI->getOperand(2).isKill();
1614
1615 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1616 int FI = MI->getOperand(0).getIndex();
1617
1618 bool Is128B = HST.useHVXDblOps();
1619 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1620 : &Hexagon::VectorRegs128BRegClass;
1621 unsigned Size = RC->getSize();
1622 unsigned NeedAlign = RC->getAlignment();
1623 unsigned HasAlign = MFI.getObjectAlignment(FI);
1624 unsigned StoreOpc;
1625
1626 // Store low part.
1627 if (NeedAlign <= HasAlign)
1628 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1629 else
1630 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1631
1632 BuildMI(B, It, DL, HII.get(StoreOpc))
1633 .addFrameIndex(FI)
1634 .addImm(0)
1635 .addReg(SrcLo, getKillRegState(IsKill))
1636 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1637
1638 // Load high part.
1639 if (NeedAlign <= MinAlign(HasAlign, Size))
1640 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1641 else
1642 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1643
1644 BuildMI(B, It, DL, HII.get(StoreOpc))
1645 .addFrameIndex(FI)
1646 .addImm(Size)
1647 .addReg(SrcHi, getKillRegState(IsKill))
1648 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1649
1650 B.erase(It);
1651 return true;
1652}
1653
1654bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1655 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1656 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1657 MachineFunction &MF = *B.getParent();
1658 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1659 auto &MFI = *MF.getFrameInfo();
1660 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1661 MachineInstr *MI = &*It;
1662 DebugLoc DL = MI->getDebugLoc();
1663
1664 unsigned DstR = MI->getOperand(0).getReg();
1665 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1666 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1667
1668 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1669 int FI = MI->getOperand(1).getIndex();
1670
1671 bool Is128B = HST.useHVXDblOps();
1672 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1673 : &Hexagon::VectorRegs128BRegClass;
1674 unsigned Size = RC->getSize();
1675 unsigned NeedAlign = RC->getAlignment();
1676 unsigned HasAlign = MFI.getObjectAlignment(FI);
1677 unsigned LoadOpc;
1678
1679 // Load low part.
1680 if (NeedAlign <= HasAlign)
1681 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1682 else
1683 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1684
1685 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1686 .addFrameIndex(FI)
1687 .addImm(0)
1688 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1689
1690 // Load high part.
1691 if (NeedAlign <= MinAlign(HasAlign, Size))
1692 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1693 else
1694 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1695
1696 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1697 .addFrameIndex(FI)
1698 .addImm(Size)
1699 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1700
1701 B.erase(It);
1702 return true;
1703}
1704
1705bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1706 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1707 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1708 MachineFunction &MF = *B.getParent();
1709 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1710 auto &MFI = *MF.getFrameInfo();
1711 MachineInstr *MI = &*It;
1712 DebugLoc DL = MI->getDebugLoc();
1713
1714 unsigned SrcR = MI->getOperand(2).getReg();
1715 bool IsKill = MI->getOperand(2).isKill();
1716
1717 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1718 int FI = MI->getOperand(0).getIndex();
1719
1720 bool Is128B = HST.useHVXDblOps();
1721 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1722 : &Hexagon::VectorRegs128BRegClass;
1723
1724 unsigned NeedAlign = RC->getAlignment();
1725 unsigned HasAlign = MFI.getObjectAlignment(FI);
1726 unsigned StoreOpc;
1727
1728 if (NeedAlign <= HasAlign)
1729 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1730 else
1731 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1732
1733 BuildMI(B, It, DL, HII.get(StoreOpc))
1734 .addFrameIndex(FI)
1735 .addImm(0)
1736 .addReg(SrcR, getKillRegState(IsKill))
1737 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1738
1739 B.erase(It);
1740 return true;
1741}
1742
1743bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1744 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1745 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1746 MachineFunction &MF = *B.getParent();
1747 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1748 auto &MFI = *MF.getFrameInfo();
1749 MachineInstr *MI = &*It;
1750 DebugLoc DL = MI->getDebugLoc();
1751
1752 unsigned DstR = MI->getOperand(0).getReg();
1753
1754 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1755 int FI = MI->getOperand(1).getIndex();
1756
1757 bool Is128B = HST.useHVXDblOps();
1758 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1759 : &Hexagon::VectorRegs128BRegClass;
1760
1761 unsigned NeedAlign = RC->getAlignment();
1762 unsigned HasAlign = MFI.getObjectAlignment(FI);
1763 unsigned LoadOpc;
1764
1765 if (NeedAlign <= HasAlign)
1766 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1767 else
1768 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1769
1770 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1771 .addFrameIndex(FI)
1772 .addImm(0)
1773 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1774
1775 B.erase(It);
1776 return true;
1777}
1778
1779
1780bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1781 SmallVectorImpl<unsigned> &NewRegs) const {
1782 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001783 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001784 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001785 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001786
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001787 for (auto &B : MF) {
1788 // Traverse the basic block.
1789 MachineBasicBlock::iterator NextI;
1790 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1791 MachineInstr *MI = &*I;
1792 NextI = std::next(I);
1793 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001794
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001795 switch (Opc) {
1796 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001797 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001798 break;
1799 case Hexagon::STriw_pred:
1800 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001801 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001802 break;
1803 case Hexagon::LDriw_pred:
1804 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001805 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001806 break;
1807 case Hexagon::STriq_pred_V6:
1808 case Hexagon::STriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001809 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001810 break;
1811 case Hexagon::LDriq_pred_V6:
1812 case Hexagon::LDriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001813 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001814 break;
1815 case Hexagon::LDrivv_pseudo_V6:
1816 case Hexagon::LDrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001817 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001818 break;
1819 case Hexagon::STrivv_pseudo_V6:
1820 case Hexagon::STrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001821 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001822 break;
1823 case Hexagon::STriv_pseudo_V6:
1824 case Hexagon::STriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001825 Changed |= expandStoreVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001826 break;
1827 case Hexagon::LDriv_pseudo_V6:
1828 case Hexagon::LDriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001829 Changed |= expandLoadVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001830 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001831 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001832 }
1833 }
1834
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001835 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001836}
1837
1838
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001839void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1840 BitVector &SavedRegs,
1841 RegScavenger *RS) const {
1842 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1843 auto &HRI = *HST.getRegisterInfo();
1844
1845 SavedRegs.resize(HRI.getNumRegs());
1846
1847 // If we have a function containing __builtin_eh_return we want to spill and
1848 // restore all callee saved registers. Pretend that they are used.
1849 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1850 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1851 SavedRegs.set(*R);
1852
1853 // Replace predicate register pseudo spill code.
1854 SmallVector<unsigned,8> NewRegs;
1855 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001856 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001857 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001858
1859 // We need to reserve a a spill slot if scavenging could potentially require
1860 // spilling a scavenged register.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001861 if (!NewRegs.empty()) {
1862 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001863 MachineRegisterInfo &MRI = MF.getRegInfo();
1864 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001865 // Reserve an int register in any case, because it could be used to hold
1866 // the stack offset in case it does not fit into a spill instruction.
1867 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1868
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001869 for (unsigned VR : NewRegs)
1870 SpillRCs.insert(MRI.getRegClass(VR));
1871
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001872 for (auto *RC : SpillRCs) {
1873 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1874 continue;
1875 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1876 unsigned S = RC->getSize(), A = RC->getAlignment();
1877 for (unsigned i = 0; i < Num; i++) {
1878 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001879 RS->addScavengingFrameIndex(NewFI);
1880 }
1881 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001882 }
1883
1884 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1885}
1886
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001887
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001888unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1889 HexagonBlockRanges::IndexRange &FIR,
1890 HexagonBlockRanges::InstrIndexMap &IndexMap,
1891 HexagonBlockRanges::RegToRangeMap &DeadMap,
1892 const TargetRegisterClass *RC) const {
1893 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1894 auto &MRI = MF.getRegInfo();
1895
1896 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1897 auto F = DeadMap.find({Reg,0});
1898 if (F == DeadMap.end())
1899 return false;
1900 for (auto &DR : F->second)
1901 if (DR.contains(FIR))
1902 return true;
1903 return false;
1904 };
1905
1906 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1907 bool Dead = true;
1908 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1909 if (isDead(R.Reg))
1910 continue;
1911 Dead = false;
1912 break;
1913 }
1914 if (Dead)
1915 return Reg;
1916 }
1917 return 0;
1918}
1919
1920void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1921 SmallVectorImpl<unsigned> &VRegs) const {
1922 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1923 auto &HII = *HST.getInstrInfo();
1924 auto &HRI = *HST.getRegisterInfo();
1925 auto &MRI = MF.getRegInfo();
1926 HexagonBlockRanges HBR(MF);
1927
1928 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1929 BlockIndexMap;
1930 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1931 BlockRangeMap;
1932 typedef HexagonBlockRanges::IndexType IndexType;
1933
1934 struct SlotInfo {
1935 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001936 unsigned Size;
1937 const TargetRegisterClass *RC;
1938
1939 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001940 };
1941
1942 BlockIndexMap BlockIndexes;
1943 SmallSet<int,4> BadFIs;
1944 std::map<int,SlotInfo> FIRangeMap;
1945
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001946 // Accumulate register classes: get a common class for a pre-existing
1947 // class HaveRC and a new class NewRC. Return nullptr if a common class
1948 // cannot be found, otherwise return the resulting class. If HaveRC is
1949 // nullptr, assume that it is still unset.
1950 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1951 const TargetRegisterClass *NewRC)
1952 -> const TargetRegisterClass* {
1953 if (HaveRC == nullptr || HaveRC == NewRC)
1954 return NewRC;
1955 // Different classes, both non-null. Pick the more general one.
1956 if (HaveRC->hasSubClassEq(NewRC))
1957 return HaveRC;
1958 if (NewRC->hasSubClassEq(HaveRC))
1959 return NewRC;
1960 return nullptr;
1961 };
1962
1963 // Scan all blocks in the function. Check all occurrences of frame indexes,
1964 // and collect relevant information.
1965 for (auto &B : MF) {
1966 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001967 // Emplace appears not to be supported in gcc 4.7.2-4.
1968 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001969 auto P = BlockIndexes.insert(
1970 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001971 auto &IndexMap = P.first->second;
1972 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1973 << IndexMap << '\n');
1974
1975 for (auto &In : B) {
1976 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001977 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
1978 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001979 if (Load && Store) {
1980 // If it's both a load and a store, then we won't handle it.
1981 BadFIs.insert(LFI);
1982 BadFIs.insert(SFI);
1983 continue;
1984 }
1985 // Check for register classes of the register used as the source for
1986 // the store, and the register used as the destination for the load.
1987 // Also, only accept base+imm_offset addressing modes. Other addressing
1988 // modes can have side-effects (post-increments, etc.). For stack
1989 // slots they are very unlikely, so there is not much loss due to
1990 // this restriction.
1991 if (Load || Store) {
1992 int TFI = Load ? LFI : SFI;
1993 unsigned AM = HII.getAddrMode(&In);
1994 SlotInfo &SI = FIRangeMap[TFI];
1995 bool Bad = (AM != HexagonII::BaseImmOffset);
1996 if (!Bad) {
1997 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00001998 unsigned OpNum = Load ? 0 : 2;
1999 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002000 RC = getCommonRC(SI.RC, RC);
2001 if (RC == nullptr)
2002 Bad = true;
2003 else
2004 SI.RC = RC;
2005 }
2006 if (!Bad) {
2007 // Check sizes.
2008 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
2009 if (SI.Size != 0 && SI.Size != S)
2010 Bad = true;
2011 else
2012 SI.Size = S;
2013 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002014 if (!Bad) {
2015 for (auto *Mo : In.memoperands()) {
2016 if (!Mo->isVolatile())
2017 continue;
2018 Bad = true;
2019 break;
2020 }
2021 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002022 if (Bad)
2023 BadFIs.insert(TFI);
2024 }
2025
2026 // Locate uses of frame indices.
2027 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2028 const MachineOperand &Op = In.getOperand(i);
2029 if (!Op.isFI())
2030 continue;
2031 int FI = Op.getIndex();
2032 // Make sure that the following operand is an immediate and that
2033 // it is 0. This is the offset in the stack object.
2034 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2035 In.getOperand(i+1).getImm() != 0)
2036 BadFIs.insert(FI);
2037 if (BadFIs.count(FI))
2038 continue;
2039
2040 IndexType Index = IndexMap.getIndex(&In);
2041 if (Load) {
2042 if (LastStore[FI] == IndexType::None)
2043 LastStore[FI] = IndexType::Entry;
2044 LastLoad[FI] = Index;
2045 } else if (Store) {
2046 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2047 if (LastStore[FI] != IndexType::None)
2048 RL.add(LastStore[FI], LastLoad[FI], false, false);
2049 else if (LastLoad[FI] != IndexType::None)
2050 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2051 LastLoad[FI] = IndexType::None;
2052 LastStore[FI] = Index;
2053 } else {
2054 BadFIs.insert(FI);
2055 }
2056 }
2057 }
2058
2059 for (auto &I : LastLoad) {
2060 IndexType LL = I.second;
2061 if (LL == IndexType::None)
2062 continue;
2063 auto &RL = FIRangeMap[I.first].Map[&B];
2064 IndexType &LS = LastStore[I.first];
2065 if (LS != IndexType::None)
2066 RL.add(LS, LL, false, false);
2067 else
2068 RL.add(IndexType::Entry, LL, false, false);
2069 LS = IndexType::None;
2070 }
2071 for (auto &I : LastStore) {
2072 IndexType LS = I.second;
2073 if (LS == IndexType::None)
2074 continue;
2075 auto &RL = FIRangeMap[I.first].Map[&B];
2076 RL.add(LS, IndexType::None, false, false);
2077 }
2078 }
2079
2080 DEBUG({
2081 for (auto &P : FIRangeMap) {
2082 dbgs() << "fi#" << P.first;
2083 if (BadFIs.count(P.first))
2084 dbgs() << " (bad)";
2085 dbgs() << " RC: ";
2086 if (P.second.RC != nullptr)
2087 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2088 else
2089 dbgs() << "<null>\n";
2090 for (auto &R : P.second.Map)
2091 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2092 }
2093 });
2094
2095 // When a slot is loaded from in a block without being stored to in the
2096 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2097 // consider this slot to be live-on-exit from all blocks.
2098 SmallSet<int,4> LoxFIs;
2099
2100 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2101
2102 for (auto &P : FIRangeMap) {
2103 // P = pair(FI, map: BB->RangeList)
2104 if (BadFIs.count(P.first))
2105 continue;
2106 for (auto &B : MF) {
2107 auto F = P.second.Map.find(&B);
2108 // F = pair(BB, RangeList)
2109 if (F == P.second.Map.end() || F->second.empty())
2110 continue;
2111 HexagonBlockRanges::IndexRange &IR = F->second.front();
2112 if (IR.start() == IndexType::Entry)
2113 LoxFIs.insert(P.first);
2114 BlockFIMap[&B].push_back(P.first);
2115 }
2116 }
2117
2118 DEBUG({
2119 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2120 for (auto &P : BlockFIMap) {
2121 auto &FIs = P.second;
2122 if (FIs.empty())
2123 continue;
2124 dbgs() << " BB#" << P.first->getNumber() << ": {";
2125 for (auto I : FIs) {
2126 dbgs() << " fi#" << I;
2127 if (LoxFIs.count(I))
2128 dbgs() << '*';
2129 }
2130 dbgs() << " }\n";
2131 }
2132 });
2133
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002134#ifndef NDEBUG
2135 bool HasOptLimit = SpillOptMax.getPosition();
2136#endif
2137
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002138 // eliminate loads, when all loads eliminated, eliminate all stores.
2139 for (auto &B : MF) {
2140 auto F = BlockIndexes.find(&B);
2141 assert(F != BlockIndexes.end());
2142 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2143 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2144 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2145 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2146 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2147
2148 for (auto FI : BlockFIMap[&B]) {
2149 if (BadFIs.count(FI))
2150 continue;
2151 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2152 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2153 for (auto &Range : RL) {
2154 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2155 if (!IndexType::isInstr(Range.start()) ||
2156 !IndexType::isInstr(Range.end()))
2157 continue;
2158 MachineInstr *SI = IM.getInstr(Range.start());
2159 MachineInstr *EI = IM.getInstr(Range.end());
2160 assert(SI->mayStore() && "Unexpected start instruction");
2161 assert(EI->mayLoad() && "Unexpected end instruction");
2162 MachineOperand &SrcOp = SI->getOperand(2);
2163
2164 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2165 SrcOp.getSubReg() };
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002166 auto *RC = HII.getRegClass(SI->getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002167 // The this-> is needed to unconfuse MSVC.
2168 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2169 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2170 if (FoundR == 0)
2171 continue;
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002172#ifndef NDEBUG
2173 if (HasOptLimit) {
2174 if (SpillOptCount >= SpillOptMax)
2175 return;
2176 SpillOptCount++;
2177 }
2178#endif
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002179
2180 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2181 MachineBasicBlock::iterator StartIt = SI, NextIt;
2182 MachineInstr *CopyIn = nullptr;
2183 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00002184 const DebugLoc &DL = SI->getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002185 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2186 .addOperand(SrcOp);
2187 }
2188
2189 ++StartIt;
2190 // Check if this is a last store and the FI is live-on-exit.
2191 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2192 // Update store's source register.
2193 if (unsigned SR = SrcOp.getSubReg())
2194 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2195 else
2196 SrcOp.setReg(FoundR);
2197 SrcOp.setSubReg(0);
2198 // We are keeping this register live.
2199 SrcOp.setIsKill(false);
2200 } else {
2201 B.erase(SI);
2202 IM.replaceInstr(SI, CopyIn);
2203 }
2204
2205 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2206 for (auto It = StartIt; It != EndIt; It = NextIt) {
2207 MachineInstr *MI = &*It;
2208 NextIt = std::next(It);
2209 int TFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002210 if (!HII.isLoadFromStackSlot(*MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002211 continue;
2212 unsigned DstR = MI->getOperand(0).getReg();
2213 assert(MI->getOperand(0).getSubReg() == 0);
2214 MachineInstr *CopyOut = nullptr;
2215 if (DstR != FoundR) {
2216 DebugLoc DL = MI->getDebugLoc();
2217 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2218 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2219 unsigned CopyOpc = TargetOpcode::COPY;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002220 if (HII.isSignExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002221 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002222 else if (HII.isZeroExtendingLoad(*MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002223 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2224 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2225 .addReg(FoundR, getKillRegState(MI == EI));
2226 }
2227 IM.replaceInstr(MI, CopyOut);
2228 B.erase(It);
2229 }
2230
2231 // Update the dead map.
2232 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2233 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2234 DM[RR].subtract(Range);
2235 } // for Range in range list
2236 }
2237 }
2238}
2239
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002240void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002241 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002242 MachineBasicBlock &MB = *AI->getParent();
2243 DebugLoc DL = AI->getDebugLoc();
2244 unsigned A = AI->getOperand(2).getImm();
2245
2246 // Have
2247 // Rd = alloca Rs, #A
2248 //
2249 // If Rs and Rd are different registers, use this sequence:
2250 // Rd = sub(r29, Rs)
2251 // r29 = sub(r29, Rs)
2252 // Rd = and(Rd, #-A) ; if necessary
2253 // r29 = and(r29, #-A) ; if necessary
2254 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2255 // otherwise, do
2256 // Rd = sub(r29, Rs)
2257 // Rd = and(Rd, #-A) ; if necessary
2258 // r29 = Rd
2259 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2260
2261 MachineOperand &RdOp = AI->getOperand(0);
2262 MachineOperand &RsOp = AI->getOperand(1);
2263 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2264
2265 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002266 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002267 .addReg(SP)
2268 .addReg(Rs);
2269 if (Rs != Rd) {
2270 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002271 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002272 .addReg(SP)
2273 .addReg(Rs);
2274 }
2275 if (A > 8) {
2276 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002277 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002278 .addReg(Rd)
2279 .addImm(-int64_t(A));
2280 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002281 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002282 .addReg(SP)
2283 .addImm(-int64_t(A));
2284 }
2285 if (Rs == Rd) {
2286 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002287 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002288 .addReg(Rd);
2289 }
2290 if (CF > 0) {
2291 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002292 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002293 .addReg(Rd)
2294 .addImm(CF);
2295 }
2296}
2297
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002298
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002299bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2300 const MachineFrameInfo *MFI = MF.getFrameInfo();
2301 if (!MFI->hasVarSizedObjects())
2302 return false;
2303 unsigned MaxA = MFI->getMaxAlignment();
2304 if (MaxA <= getStackAlignment())
2305 return false;
2306 return true;
2307}
2308
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002309
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002310const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2311 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002312 for (auto &B : MF)
2313 for (auto &I : B)
2314 if (I.getOpcode() == Hexagon::ALIGNA)
2315 return &I;
2316 return nullptr;
2317}
2318
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002319
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002320/// Adds all callee-saved registers as implicit uses or defs to the
2321/// instruction.
2322void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2323 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2324 // Add the callee-saved registers as implicit uses.
2325 for (auto &R : CSI)
2326 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2327}
2328
2329
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002330/// Determine whether the callee-saved register saves and restores should
2331/// be generated via inline code. If this function returns "true", inline
2332/// code will be generated. If this function returns "false", additional
2333/// checks are performed, which may still lead to the inline code.
2334bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2335 const CSIVect &CSI) const {
2336 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2337 return true;
2338 if (!isOptSize(MF) && !isMinSize(MF))
2339 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2340 return true;
2341
2342 // Check if CSI only has double registers, and if the registers form
2343 // a contiguous block starting from D8.
2344 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2345 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2346 unsigned R = CSI[i].getReg();
2347 if (!Hexagon::DoubleRegsRegClass.contains(R))
2348 return true;
2349 Regs[R] = true;
2350 }
2351 int F = Regs.find_first();
2352 if (F != Hexagon::D8)
2353 return true;
2354 while (F >= 0) {
2355 int N = Regs.find_next(F);
2356 if (N >= 0 && N != F+1)
2357 return true;
2358 F = N;
2359 }
2360
2361 return false;
2362}
2363
2364
2365bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2366 const CSIVect &CSI) const {
2367 if (shouldInlineCSR(MF, CSI))
2368 return false;
2369 unsigned NumCSI = CSI.size();
2370 if (NumCSI <= 1)
2371 return false;
2372
2373 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2374 : SpillFuncThreshold;
2375 return Threshold < NumCSI;
2376}
2377
2378
2379bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2380 const CSIVect &CSI) const {
2381 if (shouldInlineCSR(MF, CSI))
2382 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002383 // The restore functions do a bit more than just restoring registers.
2384 // The non-returning versions will go back directly to the caller's
2385 // caller, others will clean up the stack frame in preparation for
2386 // a tail call. Using them can still save code size even if only one
2387 // register is getting restores. Make the decision based on -Oz:
2388 // using -Os will use inline restore for a single register.
2389 if (isMinSize(MF))
2390 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002391 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002392 if (NumCSI <= 1)
2393 return false;
2394
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002395 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2396 : SpillFuncThreshold;
2397 return Threshold < NumCSI;
2398}