blob: 4d6235a9fe50e110fc158f48f4c2d5abfec13dbe [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 Parzyszek23920ec2015-10-19 18:30:27 +0000152static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
153 cl::Hidden, cl::desc("Use allocframe more conservatively"));
154
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000155static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
156 cl::init(true), cl::desc("Optimize spill slots"));
157
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000158
159namespace llvm {
160 void initializeHexagonCallFrameInformationPass(PassRegistry&);
161 FunctionPass *createHexagonCallFrameInformation();
162}
163
164namespace {
165 class HexagonCallFrameInformation : public MachineFunctionPass {
166 public:
167 static char ID;
168 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
169 PassRegistry &PR = *PassRegistry::getPassRegistry();
170 initializeHexagonCallFrameInformationPass(PR);
171 }
172 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000173 MachineFunctionProperties getRequiredProperties() const override {
174 return MachineFunctionProperties().set(
175 MachineFunctionProperties::Property::AllVRegsAllocated);
176 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000177 };
178
179 char HexagonCallFrameInformation::ID = 0;
180}
181
182bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
183 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
184 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
185 MF.getFunction()->needsUnwindTableEntry();
186
187 if (!NeedCFI)
188 return false;
189 HFI.insertCFIInstructions(MF);
190 return true;
191}
192
193INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
194 "Hexagon call frame information", false, false)
195
196FunctionPass *llvm::createHexagonCallFrameInformation() {
197 return new HexagonCallFrameInformation();
198}
199
200
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000201namespace {
202 /// Map a register pair Reg to the subregister that has the greater "number",
203 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
204 unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
205 bool hireg = true) {
206 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
207 return Reg;
208
209 unsigned RegNo = 0;
210 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
211 if (hireg) {
212 if (*SubRegs > RegNo)
213 RegNo = *SubRegs;
214 } else {
215 if (!RegNo || *SubRegs < RegNo)
216 RegNo = *SubRegs;
217 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000218 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000219 return RegNo;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000220 }
221
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000222 /// Returns the callee saved register with the largest id in the vector.
223 unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
224 const TargetRegisterInfo &TRI) {
225 assert(Hexagon::R1 > 0 &&
226 "Assume physical registers are encoded as positive integers");
227 if (CSI.empty())
228 return 0;
229
230 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
231 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
232 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
233 if (Reg > Max)
234 Max = Reg;
235 }
236 return Max;
237 }
238
239 /// Checks if the basic block contains any instruction that needs a stack
240 /// frame to be already in place.
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000241 bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
242 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000243 for (auto &I : MBB) {
244 const MachineInstr *MI = &I;
245 if (MI->isCall())
246 return true;
247 unsigned Opc = MI->getOpcode();
248 switch (Opc) {
249 case Hexagon::ALLOCA:
250 case Hexagon::ALIGNA:
251 return true;
252 default:
253 break;
254 }
255 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000256 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000257 // While the presence of a frame index does not prove that a stack
258 // frame will be required, all frame indexes should be within alloc-
259 // frame/deallocframe. Otherwise, the code that translates a frame
260 // index into an offset would have to be aware of the placement of
261 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000262 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000263 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000264 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000265 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000266 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 // Virtual registers will need scavenging, which then may require
268 // a stack slot.
269 if (TargetRegisterInfo::isVirtualRegister(R))
270 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000271 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
272 if (CSR[*S])
273 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000274 }
275 }
276 return false;
277 }
278
279 /// Returns true if MBB has a machine instructions that indicates a tail call
280 /// in the block.
281 bool hasTailCall(const MachineBasicBlock &MBB) {
282 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
283 unsigned RetOpc = I->getOpcode();
284 return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
285 }
286
287 /// Returns true if MBB contains an instruction that returns.
288 bool hasReturn(const MachineBasicBlock &MBB) {
289 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
290 if (I->isReturn())
291 return true;
292 return false;
293 }
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000294
295 inline bool isOptNone(const MachineFunction &MF) {
296 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
297 MF.getTarget().getOptLevel() == CodeGenOpt::None;
298 }
299
300 inline bool isOptSize(const MachineFunction &MF) {
301 const Function &F = *MF.getFunction();
302 return F.optForSize() && !F.optForMinSize();
303 }
304
305 inline bool isMinSize(const MachineFunction &MF) {
306 return MF.getFunction()->optForMinSize();
307 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000308}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000309
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000310
311/// Implements shrink-wrapping of the stack frame. By default, stack frame
312/// is created in the function entry block, and is cleaned up in every block
313/// that returns. This function finds alternate blocks: one for the frame
314/// setup (prolog) and one for the cleanup (epilog).
315void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
316 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
317 static unsigned ShrinkCounter = 0;
318
319 if (ShrinkLimit.getPosition()) {
320 if (ShrinkCounter >= ShrinkLimit)
321 return;
322 ShrinkCounter++;
323 }
324
325 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
326 auto &HRI = *HST.getRegisterInfo();
327
328 MachineDominatorTree MDT;
329 MDT.runOnMachineFunction(MF);
330 MachinePostDominatorTree MPT;
331 MPT.runOnMachineFunction(MF);
332
333 typedef DenseMap<unsigned,unsigned> UnsignedMap;
334 UnsignedMap RPO;
335 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
336 RPOTType RPOT(&MF);
337 unsigned RPON = 0;
338 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
339 RPO[(*I)->getNumber()] = RPON++;
340
341 // Don't process functions that have loops, at least for now. Placement
342 // of prolog and epilog must take loop structure into account. For simpli-
343 // city don't do it right now.
344 for (auto &I : MF) {
345 unsigned BN = RPO[I.getNumber()];
346 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
347 // If found a back-edge, return.
348 if (RPO[(*SI)->getNumber()] <= BN)
349 return;
350 }
351 }
352
353 // Collect the set of blocks that need a stack frame to execute. Scan
354 // each block for uses/defs of callee-saved registers, calls, etc.
355 SmallVector<MachineBasicBlock*,16> SFBlocks;
356 BitVector CSR(Hexagon::NUM_TARGET_REGS);
357 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000358 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
359 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000360
361 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000362 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000363 SFBlocks.push_back(&I);
364
365 DEBUG({
366 dbgs() << "Blocks needing SF: {";
367 for (auto &B : SFBlocks)
368 dbgs() << " BB#" << B->getNumber();
369 dbgs() << " }\n";
370 });
371 // No frame needed?
372 if (SFBlocks.empty())
373 return;
374
375 // Pick a common dominator and a common post-dominator.
376 MachineBasicBlock *DomB = SFBlocks[0];
377 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
378 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
379 if (!DomB)
380 break;
381 }
382 MachineBasicBlock *PDomB = SFBlocks[0];
383 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
384 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
385 if (!PDomB)
386 break;
387 }
388 DEBUG({
389 dbgs() << "Computed dom block: BB#";
390 if (DomB) dbgs() << DomB->getNumber();
391 else dbgs() << "<null>";
392 dbgs() << ", computed pdom block: BB#";
393 if (PDomB) dbgs() << PDomB->getNumber();
394 else dbgs() << "<null>";
395 dbgs() << "\n";
396 });
397 if (!DomB || !PDomB)
398 return;
399
400 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
401 if (!MDT.dominates(DomB, PDomB)) {
402 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
403 return;
404 }
405 if (!MPT.dominates(PDomB, DomB)) {
406 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
407 return;
408 }
409
410 // Finally, everything seems right.
411 PrologB = DomB;
412 EpilogB = PDomB;
413}
414
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000415
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000416/// Perform most of the PEI work here:
417/// - saving/restoring of the callee-saved registers,
418/// - stack frame creation and destruction.
419/// Normally, this work is distributed among various functions, but doing it
420/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000421void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
422 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000423 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
424 auto &HRI = *HST.getRegisterInfo();
425
426 MachineFrameInfo *MFI = MF.getFrameInfo();
427 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
428
429 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
430 if (EnableShrinkWrapping)
431 findShrunkPrologEpilog(MF, PrologB, EpilogB);
432
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000433 bool PrologueStubs = false;
434 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
435 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000436
437 if (EpilogB) {
438 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
439 insertEpilogueInBlock(*EpilogB);
440 } else {
441 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000442 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000443 insertCSRRestoresInBlock(B, CSI, HRI);
444
445 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000446 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000447 insertEpilogueInBlock(B);
448 }
449}
450
451
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000452void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
453 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000454 MachineFunction &MF = *MBB.getParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000455 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000456 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000457 auto &HII = *HST.getInstrInfo();
458 auto &HRI = *HST.getRegisterInfo();
459 DebugLoc dl;
460
461 unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
462
463 // Calculate the total stack frame size.
464 // Get the number of bytes to allocate from the FrameInfo.
465 unsigned FrameSize = MFI->getStackSize();
466 // Round up the max call frame size to the max alignment on the stack.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000467 unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000468 MFI->setMaxCallFrameSize(MaxCFA);
469
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000470 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000471 MFI->setStackSize(FrameSize);
472
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000473 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000474
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000475 // Get the number of bytes to allocate from the FrameInfo.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000476 unsigned NumBytes = MFI->getStackSize();
477 unsigned SP = HRI.getStackRegister();
478 unsigned MaxCF = MFI->getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000479 MachineBasicBlock::iterator InsertPt = MBB.begin();
480
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000481 auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
482 auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000483
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000484 for (auto MI : AdjustRegs) {
485 assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
486 expandAlloca(MI, HII, SP, MaxCF);
487 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000488 }
489
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000490 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000491 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000492
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000493 // Check for overflow.
494 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
495 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000496
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000497 // Create a dummy memory operand to avoid allocframe from being treated as
498 // a volatile memory reference.
499 MachineMemOperand *MMO =
500 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
501 4, 4);
502
503 if (NumBytes >= ALLOCFRAME_MAX) {
504 // Emit allocframe(#0).
505 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
506 .addImm(0)
507 .addMemOperand(MMO);
508
509 // Subtract offset from frame pointer.
510 // We use a caller-saved non-parameter register for that.
511 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
512 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
513 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000514 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
515 .addReg(SP)
516 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000517 } else {
518 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
519 .addImm(NumBytes)
520 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000521 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000522
523 if (AlignStack) {
524 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
525 .addReg(SP)
526 .addImm(-int64_t(MaxAlign));
527 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000528
529 // If the stack-checking is enabled, and we spilled the callee-saved
530 // registers inline (i.e. did not use a spill function), then call
531 // the stack checker directly.
532 if (EnableStackOVFSanitizer && !PrologueStubs)
533 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CALLstk))
534 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000535}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000536
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000537void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
538 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000539 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000540 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000541
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000542 auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
543 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000544 auto &HRI = *HST.getRegisterInfo();
545 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000546
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000547 MachineInstr *RetI = nullptr;
548 for (auto &I : MBB) {
549 if (!I.isReturn())
550 continue;
551 RetI = &I;
552 break;
553 }
554 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
555
556 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
557 DebugLoc DL;
558 if (InsertPt != MBB.end())
559 DL = InsertPt->getDebugLoc();
560 else if (!MBB.empty())
561 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000562
563 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000564 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000565 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
566 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
567 .addReg(SP)
568 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000569 return;
570 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000571
572 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
573 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000574 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
575 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000576 MachineBasicBlock::iterator It = RetI;
577 ++It;
578 // Delete all instructions after the RESTORE (except labels).
579 while (It != MBB.end()) {
580 if (!It->isLabel())
581 It = MBB.erase(It);
582 else
583 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000584 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000585 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000586 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000587
588 // It is possible that the restoring code is a call to a library function.
589 // All of the restore* functions include "deallocframe", so we need to make
590 // sure that we don't add an extra one.
591 bool NeedsDeallocframe = true;
592 if (!MBB.empty() && InsertPt != MBB.begin()) {
593 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
594 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000595 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
596 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000597 NeedsDeallocframe = false;
598 }
599
600 if (!NeedsDeallocframe)
601 return;
602 // If the returning instruction is JMPret, replace it with dealloc_return,
603 // otherwise just add deallocframe. The function could be returning via a
604 // tail call.
605 if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
606 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
607 return;
608 }
609 unsigned NewOpc = Hexagon::L4_return;
610 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
611 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000612 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000613 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000614}
615
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000616
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000617namespace {
618 bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
619 if (!It->isBundle())
620 return It->getOpcode() == Hexagon::S2_allocframe;
621 auto End = It->getParent()->instr_end();
Duncan P. N. Exon Smithd84f6002016-02-22 21:30:15 +0000622 MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000623 while (++I != End && I->isBundled())
624 if (I->getOpcode() == Hexagon::S2_allocframe)
625 return true;
626 return false;
627 }
628
629 MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
630 for (auto &I : B)
631 if (IsAllocFrame(I))
632 return I;
633 return B.end();
634 }
635}
636
637
638void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
639 for (auto &B : MF) {
640 auto AF = FindAllocFrame(B);
641 if (AF == B.end())
642 continue;
643 insertCFIInstructionsAt(B, ++AF);
644 }
645}
646
647
648void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
649 MachineBasicBlock::iterator At) const {
650 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000651 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000652 MachineModuleInfo &MMI = MF.getMMI();
653 auto &HST = MF.getSubtarget<HexagonSubtarget>();
654 auto &HII = *HST.getInstrInfo();
655 auto &HRI = *HST.getRegisterInfo();
656
657 // If CFI instructions have debug information attached, something goes
658 // wrong with the final assembly generation: the prolog_end is placed
659 // in a wrong location.
660 DebugLoc DL;
661 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
662
663 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000664 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000665
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000666 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000667 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
668 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000669
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000670 // Define CFA via an offset from the value of FP.
671 //
672 // -8 -4 0 (SP)
673 // --+----+----+---------------------
674 // | FP | LR | increasing addresses -->
675 // --+----+----+---------------------
676 // | +-- Old SP (before allocframe)
677 // +-- New FP (after allocframe)
678 //
679 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
680 // MCCFIInstruction::createOffset takes the offset without sign change.
681 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
682 BuildMI(MBB, At, DL, CFID)
683 .addCFIIndex(MMI.addFrameInst(DefCfa));
684 // R31 (return addr) = CFA - 4
685 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
686 BuildMI(MBB, At, DL, CFID)
687 .addCFIIndex(MMI.addFrameInst(OffR31));
688 // R30 (frame ptr) = CFA - 8
689 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
690 BuildMI(MBB, At, DL, CFID)
691 .addCFIIndex(MMI.addFrameInst(OffR30));
692 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000693
694 static unsigned int RegsToMove[] = {
695 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
696 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
697 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
698 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
699 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
700 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
701 Hexagon::NoRegister
702 };
703
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000704 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000705
706 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
707 unsigned Reg = RegsToMove[i];
708 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
709 return C.getReg() == Reg;
710 };
711 auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
712 if (F == CSI.end())
713 continue;
714
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000715 int64_t Offset;
716 if (HasFP) {
717 // If the function has a frame pointer (i.e. has an allocframe),
718 // then the CFA has been defined in terms of FP. Any offsets in
719 // the following CFI instructions have to be defined relative
720 // to FP, which points to the bottom of the stack frame.
721 // The function getFrameIndexReference can still choose to use SP
722 // for the offset calculation, so we cannot simply call it here.
723 // Instead, get the offset (relative to the FP) directly.
724 Offset = MFI.getObjectOffset(F->getFrameIdx());
725 } else {
726 unsigned FrameReg;
727 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
728 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000729 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000730 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000731
732 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
733 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
734 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
735 Offset);
736 BuildMI(MBB, At, DL, CFID)
737 .addCFIIndex(MMI.addFrameInst(OffReg));
738 } else {
739 // Split the double regs into subregs, and generate appropriate
740 // cfi_offsets.
741 // The only reason, we are split double regs is, llvm-mc does not
742 // understand paired registers for cfi_offset.
743 // Eg .cfi_offset r1:0, -64
744
745 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
746 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
747 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
748 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
749 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
750 Offset+4);
751 BuildMI(MBB, At, DL, CFID)
752 .addCFIIndex(MMI.addFrameInst(OffHi));
753 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
754 Offset);
755 BuildMI(MBB, At, DL, CFID)
756 .addCFIIndex(MMI.addFrameInst(OffLo));
757 }
758 }
759}
760
761
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000762bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000763 auto &MFI = *MF.getFrameInfo();
764 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
765
766 bool HasFixed = MFI.getNumFixedObjects();
767 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
768 .getLocalFrameObjectCount();
769 bool HasExtraAlign = HRI.needsStackRealignment(MF);
770 bool HasAlloca = MFI.hasVarSizedObjects();
771
772 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
773 // that this shouldn't be required, but doing so now because gcc does and
774 // gdb can't break at the start of the function without it. Will remove if
775 // this turns out to be a gdb bug.
776 //
777 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
778 return true;
779
780 // By default we want to use SP (since it's always there). FP requires
781 // some setup (i.e. ALLOCFRAME).
782 // Fixed and preallocated objects need FP if the distance from them to
783 // the SP is unknown (as is with alloca or aligna).
784 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
785 return true;
786
787 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000788 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000789 return true;
790 }
791
792 if (MFI.hasCalls() ||
793 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
794 return true;
795
796 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000797}
798
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000799
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000800enum SpillKind {
801 SK_ToMem,
802 SK_FromMem,
803 SK_FromMemTailcall
804};
805
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000806static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
807 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000808 const char * V4SpillToMemoryFunctions[] = {
809 "__save_r16_through_r17",
810 "__save_r16_through_r19",
811 "__save_r16_through_r21",
812 "__save_r16_through_r23",
813 "__save_r16_through_r25",
814 "__save_r16_through_r27" };
815
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000816 const char * V4SpillToMemoryStkchkFunctions[] = {
817 "__save_r16_through_r17_stkchk",
818 "__save_r16_through_r19_stkchk",
819 "__save_r16_through_r21_stkchk",
820 "__save_r16_through_r23_stkchk",
821 "__save_r16_through_r25_stkchk",
822 "__save_r16_through_r27_stkchk" };
823
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000824 const char * V4SpillFromMemoryFunctions[] = {
825 "__restore_r16_through_r17_and_deallocframe",
826 "__restore_r16_through_r19_and_deallocframe",
827 "__restore_r16_through_r21_and_deallocframe",
828 "__restore_r16_through_r23_and_deallocframe",
829 "__restore_r16_through_r25_and_deallocframe",
830 "__restore_r16_through_r27_and_deallocframe" };
831
832 const char * V4SpillFromMemoryTailcallFunctions[] = {
833 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
834 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
835 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
836 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
837 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
838 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
839 };
840
841 const char **SpillFunc = nullptr;
842
843 switch(SpillType) {
844 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000845 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
846 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000847 break;
848 case SK_FromMem:
849 SpillFunc = V4SpillFromMemoryFunctions;
850 break;
851 case SK_FromMemTailcall:
852 SpillFunc = V4SpillFromMemoryTailcallFunctions;
853 break;
854 }
855 assert(SpillFunc && "Unknown spill kind");
856
857 // Spill all callee-saved registers up to the highest register used.
858 switch (MaxReg) {
859 case Hexagon::R17:
860 return SpillFunc[0];
861 case Hexagon::R19:
862 return SpillFunc[1];
863 case Hexagon::R21:
864 return SpillFunc[2];
865 case Hexagon::R23:
866 return SpillFunc[3];
867 case Hexagon::R25:
868 return SpillFunc[4];
869 case Hexagon::R27:
870 return SpillFunc[5];
871 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000872 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000873 }
874 return 0;
875}
876
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000877
James Y Knight5567baf2015-08-15 02:32:35 +0000878int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000879 int FI, unsigned &FrameReg) const {
880 auto &MFI = *MF.getFrameInfo();
881 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000882
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000883 int Offset = MFI.getObjectOffset(FI);
884 bool HasAlloca = MFI.hasVarSizedObjects();
885 bool HasExtraAlign = HRI.needsStackRealignment(MF);
886 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +0000887
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000888 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000889 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
890 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000891 unsigned FrameSize = MFI.getStackSize();
892
893 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
894 // Use FP at -O0, except when there are objects with extra alignment.
895 // That additional alignment requirement may cause a pad to be inserted,
896 // which will make it impossible to use FP to access objects located
897 // past the pad.
898 if (NoOpt && !HasExtraAlign)
899 UseFP = true;
900 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
901 // Fixed and preallocated objects will be located before any padding
902 // so FP must be used to access them.
903 UseFP |= (HasAlloca || HasExtraAlign);
904 } else {
905 if (HasAlloca) {
906 if (HasExtraAlign)
907 UseAP = true;
908 else
909 UseFP = true;
910 }
911 }
912
913 // If FP was picked, then there had better be FP.
914 bool HasFP = hasFP(MF);
915 assert((HasFP || !UseFP) && "This function must have frame pointer");
916
917 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
918 // FP/LR. If the base register is used to access an object across these
919 // 8 bytes, then the offset will need to be adjusted by 8.
920 //
921 // After allocframe:
922 // HexagonISelLowering adds 8 to ---+
923 // the offsets of all stack-based |
924 // arguments (*) |
925 // |
926 // getObjectOffset < 0 0 8 getObjectOffset >= 8
927 // ------------------------+-----+------------------------> increasing
928 // <local objects> |FP/LR| <input arguments> addresses
929 // -----------------+------+-----+------------------------>
930 // | |
931 // SP/AP point --+ +-- FP points here (**)
932 // somewhere on
933 // this side of FP/LR
934 //
935 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
936 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
937
938 // The lowering assumes that FP/LR is present, and so the offsets of
939 // the formal arguments start at 8. If FP/LR is not there we need to
940 // reduce the offset by 8.
941 if (Offset > 0 && !HasFP)
942 Offset -= 8;
943
944 if (UseFP)
945 FrameReg = FP;
946 else if (UseAP)
947 FrameReg = AP;
948 else
949 FrameReg = SP;
950
951 // Calculate the actual offset in the instruction. If there is no FP
952 // (in other words, no allocframe), then SP will not be adjusted (i.e.
953 // there will be no SP -= FrameSize), so the frame size should not be
954 // added to the calculated offset.
955 int RealOffset = Offset;
956 if (!UseFP && !UseAP && HasFP)
957 RealOffset = FrameSize+Offset;
958 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +0000959}
960
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000961
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000962bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000963 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
964 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000965 if (CSI.empty())
966 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000967
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000968 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000969 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000970 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000971 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000972
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000973 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000974 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000975 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000976 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
977 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
978 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000979 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
980 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
981
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000982 // Call spill function.
983 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000984 unsigned SpillOpc;
985 if (StkOvrFlowEnabled)
986 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
987 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
988 else
989 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
990 : Hexagon::SAVE_REGISTERS_CALL_V4;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000991
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000992 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000993 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000994 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000995 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +0000996 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000997 // Add live in registers.
998 for (unsigned I = 0; I < CSI.size(); ++I)
999 MBB.addLiveIn(CSI[I].getReg());
1000 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001001 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001002
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001003 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001004 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001005 // Add live in registers. We treat eh_return callee saved register r0 - r3
1006 // specially. They are not really callee saved registers as they are not
1007 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001008 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1009 int FI = CSI[i].getFrameIdx();
1010 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001011 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001012 if (IsKill)
1013 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001014 }
1015 return true;
1016}
1017
1018
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001019bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1020 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1021 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001022 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001023
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001024 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1025 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001026 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001027
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001028 if (useRestoreFunction(MF, CSI)) {
1029 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1030 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1031 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1032 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001033 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1034 bool IsPIC = HTM.getRelocationModel() == Reloc::PIC_;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001035
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001036 // Call spill function.
1037 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1038 : MBB.getLastNonDebugInstr()->getDebugLoc();
1039 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001040
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001041 if (HasTC) {
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001042 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1043 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001044 DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001045 .addExternalSymbol(RestoreFn);
1046 } else {
1047 // The block has a return.
1048 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1049 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001050 unsigned ROpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1051 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001052 DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001053 .addExternalSymbol(RestoreFn);
1054 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001055 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001056 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001057 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001058 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001059 }
1060
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001061 for (unsigned i = 0; i < CSI.size(); ++i) {
1062 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001063 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1064 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001065 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001066 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001067
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001068 return true;
1069}
1070
Hans Wennborge1a2e902016-03-31 18:33:38 +00001071MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1072 MachineFunction &MF, MachineBasicBlock &MBB,
1073 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001074 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001075 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001076 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001077 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1078 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001079 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001080}
1081
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001082
1083void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1084 MachineFunction &MF, RegScavenger *RS) const {
1085 // If this function has uses aligned stack and also has variable sized stack
1086 // objects, then we need to map all spill slots to fixed positions, so that
1087 // they can be accessed through FP. Otherwise they would have to be accessed
1088 // via AP, which may not be available at the particular place in the program.
1089 MachineFrameInfo *MFI = MF.getFrameInfo();
1090 bool HasAlloca = MFI->hasVarSizedObjects();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001091 bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001092
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001093 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001094 return;
1095
1096 unsigned LFS = MFI->getLocalFrameSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001097 for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1098 if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1099 continue;
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001100 unsigned S = MFI->getObjectSize(i);
1101 // Reduce the alignment to at most 8. This will require unaligned vector
1102 // stores if they happen here.
1103 unsigned A = std::max(MFI->getObjectAlignment(i), 8U);
1104 MFI->setObjectAlignment(i, 8);
1105 LFS = alignTo(LFS+S, A);
1106 MFI->mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001107 }
1108
1109 MFI->setLocalFrameSize(LFS);
1110 unsigned A = MFI->getLocalFrameMaxAlign();
1111 assert(A <= 8 && "Unexpected local frame alignment");
1112 if (A == 0)
1113 MFI->setLocalFrameMaxAlign(8);
1114 MFI->setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001115
1116 // Set the physical aligned-stack base address register.
1117 unsigned AP = 0;
1118 if (const MachineInstr *AI = getAlignaInstr(MF))
1119 AP = AI->getOperand(0).getReg();
1120 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1121 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001122}
1123
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001124/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001125static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001126 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001127 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001128
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001129 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1130 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1131 if (MRI.isPhysRegUsed(*AI))
1132 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001133 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001134 };
1135
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001136 // Check for an unused caller-saved register. Callee-saved registers
1137 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001138 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001139 if (!IsUsed(*P))
1140 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001141
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001142 // All caller-saved registers are used.
1143 return true;
1144}
1145
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001146
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001147#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001148static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001149 dbgs() << '{';
1150 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1151 unsigned R = x;
1152 dbgs() << ' ' << PrintReg(R, &TRI);
1153 }
1154 dbgs() << " }";
1155}
1156#endif
1157
1158
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001159bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1160 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Krzysztof Parzyszek27ba19a12015-04-23 20:42:20 +00001161 DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001162 << MF.getFunction()->getName() << '\n');
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001163 MachineFrameInfo *MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001164 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001165
1166 // Generate a set of unique, callee-saved registers (SRegs), where each
1167 // register in the set is maximal in terms of sub-/super-register relation,
1168 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1169
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001170 // (1) For each callee-saved register, add that register and all of its
1171 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001172 DEBUG(dbgs() << "Initial CS registers: {");
1173 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1174 unsigned R = CSI[i].getReg();
1175 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1176 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1177 SRegs[*SR] = true;
1178 }
1179 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001180 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001181
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001182 // (2) For each reserved register, remove that register and all of its
1183 // sub- and super-registers from SRegs.
1184 BitVector Reserved = TRI->getReservedRegs(MF);
1185 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1186 unsigned R = x;
1187 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1188 SRegs[*SR] = false;
1189 }
1190 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1191 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1192
1193 // (3) Collect all registers that have at least one sub-register in SRegs,
1194 // and also have no sub-registers that are reserved. These will be the can-
1195 // didates for saving as a whole instead of their individual sub-registers.
1196 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1197 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001198 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1199 unsigned R = x;
1200 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1201 TmpSup[*SR] = true;
1202 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001203 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1204 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001205 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1206 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001207 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001208 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001209 break;
1210 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001211 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001212 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001213
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001214 // (4) Include all super-registers found in (3) into SRegs.
1215 SRegs |= TmpSup;
1216 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001217
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001218 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001219 // remove R from SRegs.
1220 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1221 unsigned R = x;
1222 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1223 if (!SRegs[*SR])
1224 continue;
1225 SRegs[R] = false;
1226 break;
1227 }
1228 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001229 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001230
1231 // Now, for each register that has a fixed stack slot, create the stack
1232 // object for it.
1233 CSI.clear();
1234
1235 typedef TargetFrameLowering::SpillSlot SpillSlot;
1236 unsigned NumFixed;
1237 int MinOffset = 0; // CS offsets are negative.
1238 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1239 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1240 if (!SRegs[S->Reg])
1241 continue;
1242 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1243 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1244 MinOffset = std::min(MinOffset, S->Offset);
1245 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1246 SRegs[S->Reg] = false;
1247 }
1248
1249 // There can be some registers that don't have fixed slots. For example,
1250 // we need to store R0-R3 in functions with exception handling. For each
1251 // such register, create a non-fixed stack object.
1252 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1253 unsigned R = x;
1254 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1255 int Off = MinOffset - RC->getSize();
1256 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1257 assert(isPowerOf2_32(Align));
1258 Off &= -Align;
1259 int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1260 MinOffset = std::min(MinOffset, Off);
1261 CSI.push_back(CalleeSavedInfo(R, FI));
1262 SRegs[R] = false;
1263 }
1264
1265 DEBUG({
1266 dbgs() << "CS information: {";
1267 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1268 int FI = CSI[i].getFrameIdx();
1269 int Off = MFI->getObjectOffset(FI);
1270 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1271 if (Off >= 0)
1272 dbgs() << '+';
1273 dbgs() << Off;
1274 }
1275 dbgs() << " }\n";
1276 });
1277
1278#ifndef NDEBUG
1279 // Verify that all registers were handled.
1280 bool MissedReg = false;
1281 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1282 unsigned R = x;
1283 dbgs() << PrintReg(R, TRI) << ' ';
1284 MissedReg = true;
1285 }
1286 if (MissedReg)
1287 llvm_unreachable("...there are unhandled callee-saved registers!");
1288#endif
1289
1290 return true;
1291}
1292
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001293
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001294bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1295 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1296 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1297 MachineInstr *MI = &*It;
1298 DebugLoc DL = MI->getDebugLoc();
1299 unsigned DstR = MI->getOperand(0).getReg();
1300 unsigned SrcR = MI->getOperand(1).getReg();
1301 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1302 !Hexagon::ModRegsRegClass.contains(SrcR))
1303 return false;
1304
1305 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1306 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1307 .addOperand(MI->getOperand(1));
1308 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1309 .addReg(TmpR, RegState::Kill);
1310
1311 NewRegs.push_back(TmpR);
1312 B.erase(It);
1313 return true;
1314}
1315
1316bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1317 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1318 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1319 MachineInstr *MI = &*It;
1320 DebugLoc DL = MI->getDebugLoc();
1321 unsigned Opc = MI->getOpcode();
1322 unsigned SrcR = MI->getOperand(2).getReg();
1323 bool IsKill = MI->getOperand(2).isKill();
1324
1325 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1326 int FI = MI->getOperand(0).getIndex();
1327
1328 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1329 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1330 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1331 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1332 : Hexagon::A2_tfrcrr;
1333 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1334 .addReg(SrcR, getKillRegState(IsKill));
1335
1336 // S2_storeri_io FI, 0, TmpR
1337 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1338 .addFrameIndex(FI)
1339 .addImm(0)
1340 .addReg(TmpR, RegState::Kill)
1341 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1342
1343 NewRegs.push_back(TmpR);
1344 B.erase(It);
1345 return true;
1346}
1347
1348bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1349 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1350 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1351 MachineInstr *MI = &*It;
1352 DebugLoc DL = MI->getDebugLoc();
1353 unsigned Opc = MI->getOpcode();
1354 unsigned DstR = MI->getOperand(0).getReg();
1355
1356 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1357 int FI = MI->getOperand(1).getIndex();
1358
1359 // TmpR = L2_loadri_io FI, 0
1360 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1361 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1362 .addFrameIndex(FI)
1363 .addImm(0)
1364 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1365
1366 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1367 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1368 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1369 : Hexagon::A2_tfrrcr;
1370 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1371 .addReg(TmpR, RegState::Kill);
1372
1373 NewRegs.push_back(TmpR);
1374 B.erase(It);
1375 return true;
1376}
1377
1378
1379bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1380 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1381 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1382 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1383 MachineInstr *MI = &*It;
1384 DebugLoc DL = MI->getDebugLoc();
1385 unsigned SrcR = MI->getOperand(2).getReg();
1386 bool IsKill = MI->getOperand(2).isKill();
1387
1388 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1389 int FI = MI->getOperand(0).getIndex();
1390
1391 bool Is128B = HST.useHVXDblOps();
1392 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1393 : &Hexagon::VectorRegs128BRegClass;
1394
1395 // Insert transfer to general vector register.
1396 // TmpR0 = A2_tfrsi 0x01010101
1397 // TmpR1 = V6_vandqrt Qx, TmpR0
1398 // store FI, 0, TmpR1
1399 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1400 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1401
1402 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1403 .addImm(0x01010101);
1404
1405 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1406 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1407 .addReg(SrcR, getKillRegState(IsKill))
1408 .addReg(TmpR0, RegState::Kill);
1409
1410 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1411 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1412 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1413
1414 NewRegs.push_back(TmpR0);
1415 NewRegs.push_back(TmpR1);
1416 B.erase(It);
1417 return true;
1418}
1419
1420bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1421 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1422 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1423 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1424 MachineInstr *MI = &*It;
1425 DebugLoc DL = MI->getDebugLoc();
1426 unsigned DstR = MI->getOperand(0).getReg();
1427
1428 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1429 int FI = MI->getOperand(1).getIndex();
1430
1431 bool Is128B = HST.useHVXDblOps();
1432 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1433 : &Hexagon::VectorRegs128BRegClass;
1434
1435 // TmpR0 = A2_tfrsi 0x01010101
1436 // TmpR1 = load FI, 0
1437 // DstR = V6_vandvrt TmpR1, TmpR0
1438 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1439 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1440
1441 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1442 .addImm(0x01010101);
1443 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1444 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1445 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1446
1447 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1448 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1449 .addReg(TmpR1, RegState::Kill)
1450 .addReg(TmpR0, RegState::Kill);
1451
1452 NewRegs.push_back(TmpR0);
1453 NewRegs.push_back(TmpR1);
1454 B.erase(It);
1455 return true;
1456}
1457
1458bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1459 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1460 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1461 MachineFunction &MF = *B.getParent();
1462 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1463 auto &MFI = *MF.getFrameInfo();
1464 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1465 MachineInstr *MI = &*It;
1466 DebugLoc DL = MI->getDebugLoc();
1467
1468 unsigned SrcR = MI->getOperand(2).getReg();
1469 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::subreg_loreg);
1470 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::subreg_hireg);
1471 bool IsKill = MI->getOperand(2).isKill();
1472
1473 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1474 int FI = MI->getOperand(0).getIndex();
1475
1476 bool Is128B = HST.useHVXDblOps();
1477 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1478 : &Hexagon::VectorRegs128BRegClass;
1479 unsigned Size = RC->getSize();
1480 unsigned NeedAlign = RC->getAlignment();
1481 unsigned HasAlign = MFI.getObjectAlignment(FI);
1482 unsigned StoreOpc;
1483
1484 // Store low part.
1485 if (NeedAlign <= HasAlign)
1486 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1487 else
1488 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1489
1490 BuildMI(B, It, DL, HII.get(StoreOpc))
1491 .addFrameIndex(FI)
1492 .addImm(0)
1493 .addReg(SrcLo, getKillRegState(IsKill))
1494 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1495
1496 // Load high part.
1497 if (NeedAlign <= MinAlign(HasAlign, Size))
1498 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1499 else
1500 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1501
1502 BuildMI(B, It, DL, HII.get(StoreOpc))
1503 .addFrameIndex(FI)
1504 .addImm(Size)
1505 .addReg(SrcHi, getKillRegState(IsKill))
1506 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1507
1508 B.erase(It);
1509 return true;
1510}
1511
1512bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1513 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1514 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1515 MachineFunction &MF = *B.getParent();
1516 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1517 auto &MFI = *MF.getFrameInfo();
1518 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1519 MachineInstr *MI = &*It;
1520 DebugLoc DL = MI->getDebugLoc();
1521
1522 unsigned DstR = MI->getOperand(0).getReg();
1523 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::subreg_hireg);
1524 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::subreg_loreg);
1525
1526 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1527 int FI = MI->getOperand(1).getIndex();
1528
1529 bool Is128B = HST.useHVXDblOps();
1530 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1531 : &Hexagon::VectorRegs128BRegClass;
1532 unsigned Size = RC->getSize();
1533 unsigned NeedAlign = RC->getAlignment();
1534 unsigned HasAlign = MFI.getObjectAlignment(FI);
1535 unsigned LoadOpc;
1536
1537 // Load low part.
1538 if (NeedAlign <= HasAlign)
1539 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1540 else
1541 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1542
1543 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1544 .addFrameIndex(FI)
1545 .addImm(0)
1546 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1547
1548 // Load high part.
1549 if (NeedAlign <= MinAlign(HasAlign, Size))
1550 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1551 else
1552 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1553
1554 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1555 .addFrameIndex(FI)
1556 .addImm(Size)
1557 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1558
1559 B.erase(It);
1560 return true;
1561}
1562
1563bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1564 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1565 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1566 MachineFunction &MF = *B.getParent();
1567 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1568 auto &MFI = *MF.getFrameInfo();
1569 MachineInstr *MI = &*It;
1570 DebugLoc DL = MI->getDebugLoc();
1571
1572 unsigned SrcR = MI->getOperand(2).getReg();
1573 bool IsKill = MI->getOperand(2).isKill();
1574
1575 assert(MI->getOperand(0).isFI() && "Expect a frame index");
1576 int FI = MI->getOperand(0).getIndex();
1577
1578 bool Is128B = HST.useHVXDblOps();
1579 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1580 : &Hexagon::VectorRegs128BRegClass;
1581
1582 unsigned NeedAlign = RC->getAlignment();
1583 unsigned HasAlign = MFI.getObjectAlignment(FI);
1584 unsigned StoreOpc;
1585
1586 if (NeedAlign <= HasAlign)
1587 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1588 else
1589 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1590
1591 BuildMI(B, It, DL, HII.get(StoreOpc))
1592 .addFrameIndex(FI)
1593 .addImm(0)
1594 .addReg(SrcR, getKillRegState(IsKill))
1595 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1596
1597 B.erase(It);
1598 return true;
1599}
1600
1601bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1602 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1603 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1604 MachineFunction &MF = *B.getParent();
1605 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1606 auto &MFI = *MF.getFrameInfo();
1607 MachineInstr *MI = &*It;
1608 DebugLoc DL = MI->getDebugLoc();
1609
1610 unsigned DstR = MI->getOperand(0).getReg();
1611
1612 assert(MI->getOperand(1).isFI() && "Expect a frame index");
1613 int FI = MI->getOperand(1).getIndex();
1614
1615 bool Is128B = HST.useHVXDblOps();
1616 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1617 : &Hexagon::VectorRegs128BRegClass;
1618
1619 unsigned NeedAlign = RC->getAlignment();
1620 unsigned HasAlign = MFI.getObjectAlignment(FI);
1621 unsigned LoadOpc;
1622
1623 if (NeedAlign <= HasAlign)
1624 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1625 else
1626 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1627
1628 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1629 .addFrameIndex(FI)
1630 .addImm(0)
1631 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1632
1633 B.erase(It);
1634 return true;
1635}
1636
1637
1638bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1639 SmallVectorImpl<unsigned> &NewRegs) const {
1640 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001641 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001642 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001643 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001644
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001645 for (auto &B : MF) {
1646 // Traverse the basic block.
1647 MachineBasicBlock::iterator NextI;
1648 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1649 MachineInstr *MI = &*I;
1650 NextI = std::next(I);
1651 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001652
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001653 switch (Opc) {
1654 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001655 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001656 break;
1657 case Hexagon::STriw_pred:
1658 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001659 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001660 break;
1661 case Hexagon::LDriw_pred:
1662 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001663 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001664 break;
1665 case Hexagon::STriq_pred_V6:
1666 case Hexagon::STriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001667 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001668 break;
1669 case Hexagon::LDriq_pred_V6:
1670 case Hexagon::LDriq_pred_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001671 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001672 break;
1673 case Hexagon::LDrivv_pseudo_V6:
1674 case Hexagon::LDrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001675 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001676 break;
1677 case Hexagon::STrivv_pseudo_V6:
1678 case Hexagon::STrivv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001679 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001680 break;
1681 case Hexagon::STriv_pseudo_V6:
1682 case Hexagon::STriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001683 Changed |= expandStoreVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001684 break;
1685 case Hexagon::LDriv_pseudo_V6:
1686 case Hexagon::LDriv_pseudo_V6_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001687 Changed |= expandLoadVec(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001688 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001689 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001690 }
1691 }
1692
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001693 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001694}
1695
1696
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001697void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1698 BitVector &SavedRegs,
1699 RegScavenger *RS) const {
1700 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1701 auto &HRI = *HST.getRegisterInfo();
1702
1703 SavedRegs.resize(HRI.getNumRegs());
1704
1705 // If we have a function containing __builtin_eh_return we want to spill and
1706 // restore all callee saved registers. Pretend that they are used.
1707 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1708 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1709 SavedRegs.set(*R);
1710
1711 // Replace predicate register pseudo spill code.
1712 SmallVector<unsigned,8> NewRegs;
1713 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001714 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001715 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001716
1717 // We need to reserve a a spill slot if scavenging could potentially require
1718 // spilling a scavenged register.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001719 if (!NewRegs.empty()) {
1720 MachineFrameInfo &MFI = *MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001721 MachineRegisterInfo &MRI = MF.getRegInfo();
1722 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001723 // Reserve an int register in any case, because it could be used to hold
1724 // the stack offset in case it does not fit into a spill instruction.
1725 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1726
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001727 for (unsigned VR : NewRegs)
1728 SpillRCs.insert(MRI.getRegClass(VR));
1729
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001730 for (auto *RC : SpillRCs) {
1731 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1732 continue;
1733 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1734 unsigned S = RC->getSize(), A = RC->getAlignment();
1735 for (unsigned i = 0; i < Num; i++) {
1736 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001737 RS->addScavengingFrameIndex(NewFI);
1738 }
1739 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001740 }
1741
1742 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1743}
1744
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001745
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001746unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1747 HexagonBlockRanges::IndexRange &FIR,
1748 HexagonBlockRanges::InstrIndexMap &IndexMap,
1749 HexagonBlockRanges::RegToRangeMap &DeadMap,
1750 const TargetRegisterClass *RC) const {
1751 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1752 auto &MRI = MF.getRegInfo();
1753
1754 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1755 auto F = DeadMap.find({Reg,0});
1756 if (F == DeadMap.end())
1757 return false;
1758 for (auto &DR : F->second)
1759 if (DR.contains(FIR))
1760 return true;
1761 return false;
1762 };
1763
1764 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1765 bool Dead = true;
1766 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1767 if (isDead(R.Reg))
1768 continue;
1769 Dead = false;
1770 break;
1771 }
1772 if (Dead)
1773 return Reg;
1774 }
1775 return 0;
1776}
1777
1778void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1779 SmallVectorImpl<unsigned> &VRegs) const {
1780 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1781 auto &HII = *HST.getInstrInfo();
1782 auto &HRI = *HST.getRegisterInfo();
1783 auto &MRI = MF.getRegInfo();
1784 HexagonBlockRanges HBR(MF);
1785
1786 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1787 BlockIndexMap;
1788 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1789 BlockRangeMap;
1790 typedef HexagonBlockRanges::IndexType IndexType;
1791
1792 struct SlotInfo {
1793 BlockRangeMap Map;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001794 unsigned Size;
1795 const TargetRegisterClass *RC;
1796
1797 SlotInfo() : Map(), Size(0), RC(nullptr) {}
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001798 };
1799
1800 BlockIndexMap BlockIndexes;
1801 SmallSet<int,4> BadFIs;
1802 std::map<int,SlotInfo> FIRangeMap;
1803
1804 auto getRegClass = [&MRI,&HRI] (HexagonBlockRanges::RegisterRef R)
1805 -> const TargetRegisterClass* {
1806 if (TargetRegisterInfo::isPhysicalRegister(R.Reg))
1807 assert(R.Sub == 0);
1808 if (TargetRegisterInfo::isVirtualRegister(R.Reg)) {
1809 auto *RCR = MRI.getRegClass(R.Reg);
1810 if (R.Sub == 0)
1811 return RCR;
1812 unsigned PR = *RCR->begin();
1813 R.Reg = HRI.getSubReg(PR, R.Sub);
1814 }
1815 return HRI.getMinimalPhysRegClass(R.Reg);
1816 };
1817 // Accumulate register classes: get a common class for a pre-existing
1818 // class HaveRC and a new class NewRC. Return nullptr if a common class
1819 // cannot be found, otherwise return the resulting class. If HaveRC is
1820 // nullptr, assume that it is still unset.
1821 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1822 const TargetRegisterClass *NewRC)
1823 -> const TargetRegisterClass* {
1824 if (HaveRC == nullptr || HaveRC == NewRC)
1825 return NewRC;
1826 // Different classes, both non-null. Pick the more general one.
1827 if (HaveRC->hasSubClassEq(NewRC))
1828 return HaveRC;
1829 if (NewRC->hasSubClassEq(HaveRC))
1830 return NewRC;
1831 return nullptr;
1832 };
1833
1834 // Scan all blocks in the function. Check all occurrences of frame indexes,
1835 // and collect relevant information.
1836 for (auto &B : MF) {
1837 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00001838 // Emplace appears not to be supported in gcc 4.7.2-4.
1839 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00001840 auto P = BlockIndexes.insert(
1841 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001842 auto &IndexMap = P.first->second;
1843 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
1844 << IndexMap << '\n');
1845
1846 for (auto &In : B) {
1847 int LFI, SFI;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001848 bool Load = HII.isLoadFromStackSlot(&In, LFI) && !HII.isPredicated(In);
1849 bool Store = HII.isStoreToStackSlot(&In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001850 if (Load && Store) {
1851 // If it's both a load and a store, then we won't handle it.
1852 BadFIs.insert(LFI);
1853 BadFIs.insert(SFI);
1854 continue;
1855 }
1856 // Check for register classes of the register used as the source for
1857 // the store, and the register used as the destination for the load.
1858 // Also, only accept base+imm_offset addressing modes. Other addressing
1859 // modes can have side-effects (post-increments, etc.). For stack
1860 // slots they are very unlikely, so there is not much loss due to
1861 // this restriction.
1862 if (Load || Store) {
1863 int TFI = Load ? LFI : SFI;
1864 unsigned AM = HII.getAddrMode(&In);
1865 SlotInfo &SI = FIRangeMap[TFI];
1866 bool Bad = (AM != HexagonII::BaseImmOffset);
1867 if (!Bad) {
1868 // If the addressing mode is ok, check the register class.
1869 const TargetRegisterClass *RC = nullptr;
1870 if (Load) {
1871 MachineOperand &DataOp = In.getOperand(0);
1872 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1873 } else {
1874 MachineOperand &DataOp = In.getOperand(2);
1875 RC = getRegClass({DataOp.getReg(), DataOp.getSubReg()});
1876 }
1877 RC = getCommonRC(SI.RC, RC);
1878 if (RC == nullptr)
1879 Bad = true;
1880 else
1881 SI.RC = RC;
1882 }
1883 if (!Bad) {
1884 // Check sizes.
1885 unsigned S = (1U << (HII.getMemAccessSize(&In) - 1));
1886 if (SI.Size != 0 && SI.Size != S)
1887 Bad = true;
1888 else
1889 SI.Size = S;
1890 }
1891 if (Bad)
1892 BadFIs.insert(TFI);
1893 }
1894
1895 // Locate uses of frame indices.
1896 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
1897 const MachineOperand &Op = In.getOperand(i);
1898 if (!Op.isFI())
1899 continue;
1900 int FI = Op.getIndex();
1901 // Make sure that the following operand is an immediate and that
1902 // it is 0. This is the offset in the stack object.
1903 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
1904 In.getOperand(i+1).getImm() != 0)
1905 BadFIs.insert(FI);
1906 if (BadFIs.count(FI))
1907 continue;
1908
1909 IndexType Index = IndexMap.getIndex(&In);
1910 if (Load) {
1911 if (LastStore[FI] == IndexType::None)
1912 LastStore[FI] = IndexType::Entry;
1913 LastLoad[FI] = Index;
1914 } else if (Store) {
1915 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
1916 if (LastStore[FI] != IndexType::None)
1917 RL.add(LastStore[FI], LastLoad[FI], false, false);
1918 else if (LastLoad[FI] != IndexType::None)
1919 RL.add(IndexType::Entry, LastLoad[FI], false, false);
1920 LastLoad[FI] = IndexType::None;
1921 LastStore[FI] = Index;
1922 } else {
1923 BadFIs.insert(FI);
1924 }
1925 }
1926 }
1927
1928 for (auto &I : LastLoad) {
1929 IndexType LL = I.second;
1930 if (LL == IndexType::None)
1931 continue;
1932 auto &RL = FIRangeMap[I.first].Map[&B];
1933 IndexType &LS = LastStore[I.first];
1934 if (LS != IndexType::None)
1935 RL.add(LS, LL, false, false);
1936 else
1937 RL.add(IndexType::Entry, LL, false, false);
1938 LS = IndexType::None;
1939 }
1940 for (auto &I : LastStore) {
1941 IndexType LS = I.second;
1942 if (LS == IndexType::None)
1943 continue;
1944 auto &RL = FIRangeMap[I.first].Map[&B];
1945 RL.add(LS, IndexType::None, false, false);
1946 }
1947 }
1948
1949 DEBUG({
1950 for (auto &P : FIRangeMap) {
1951 dbgs() << "fi#" << P.first;
1952 if (BadFIs.count(P.first))
1953 dbgs() << " (bad)";
1954 dbgs() << " RC: ";
1955 if (P.second.RC != nullptr)
1956 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
1957 else
1958 dbgs() << "<null>\n";
1959 for (auto &R : P.second.Map)
1960 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
1961 }
1962 });
1963
1964 // When a slot is loaded from in a block without being stored to in the
1965 // same block, it is live-on-entry to this block. To avoid CFG analysis,
1966 // consider this slot to be live-on-exit from all blocks.
1967 SmallSet<int,4> LoxFIs;
1968
1969 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
1970
1971 for (auto &P : FIRangeMap) {
1972 // P = pair(FI, map: BB->RangeList)
1973 if (BadFIs.count(P.first))
1974 continue;
1975 for (auto &B : MF) {
1976 auto F = P.second.Map.find(&B);
1977 // F = pair(BB, RangeList)
1978 if (F == P.second.Map.end() || F->second.empty())
1979 continue;
1980 HexagonBlockRanges::IndexRange &IR = F->second.front();
1981 if (IR.start() == IndexType::Entry)
1982 LoxFIs.insert(P.first);
1983 BlockFIMap[&B].push_back(P.first);
1984 }
1985 }
1986
1987 DEBUG({
1988 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
1989 for (auto &P : BlockFIMap) {
1990 auto &FIs = P.second;
1991 if (FIs.empty())
1992 continue;
1993 dbgs() << " BB#" << P.first->getNumber() << ": {";
1994 for (auto I : FIs) {
1995 dbgs() << " fi#" << I;
1996 if (LoxFIs.count(I))
1997 dbgs() << '*';
1998 }
1999 dbgs() << " }\n";
2000 }
2001 });
2002
2003 // eliminate loads, when all loads eliminated, eliminate all stores.
2004 for (auto &B : MF) {
2005 auto F = BlockIndexes.find(&B);
2006 assert(F != BlockIndexes.end());
2007 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2008 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2009 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2010 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2011 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2012
2013 for (auto FI : BlockFIMap[&B]) {
2014 if (BadFIs.count(FI))
2015 continue;
2016 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2017 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2018 for (auto &Range : RL) {
2019 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2020 if (!IndexType::isInstr(Range.start()) ||
2021 !IndexType::isInstr(Range.end()))
2022 continue;
2023 MachineInstr *SI = IM.getInstr(Range.start());
2024 MachineInstr *EI = IM.getInstr(Range.end());
2025 assert(SI->mayStore() && "Unexpected start instruction");
2026 assert(EI->mayLoad() && "Unexpected end instruction");
2027 MachineOperand &SrcOp = SI->getOperand(2);
2028
2029 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2030 SrcOp.getSubReg() };
2031 auto *RC = getRegClass({SrcOp.getReg(), SrcOp.getSubReg()});
2032 // The this-> is needed to unconfuse MSVC.
2033 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2034 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2035 if (FoundR == 0)
2036 continue;
2037
2038 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2039 MachineBasicBlock::iterator StartIt = SI, NextIt;
2040 MachineInstr *CopyIn = nullptr;
2041 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2042 DebugLoc DL = SI->getDebugLoc();
2043 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2044 .addOperand(SrcOp);
2045 }
2046
2047 ++StartIt;
2048 // Check if this is a last store and the FI is live-on-exit.
2049 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2050 // Update store's source register.
2051 if (unsigned SR = SrcOp.getSubReg())
2052 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2053 else
2054 SrcOp.setReg(FoundR);
2055 SrcOp.setSubReg(0);
2056 // We are keeping this register live.
2057 SrcOp.setIsKill(false);
2058 } else {
2059 B.erase(SI);
2060 IM.replaceInstr(SI, CopyIn);
2061 }
2062
2063 auto EndIt = std::next(MachineBasicBlock::iterator(EI));
2064 for (auto It = StartIt; It != EndIt; It = NextIt) {
2065 MachineInstr *MI = &*It;
2066 NextIt = std::next(It);
2067 int TFI;
2068 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2069 continue;
2070 unsigned DstR = MI->getOperand(0).getReg();
2071 assert(MI->getOperand(0).getSubReg() == 0);
2072 MachineInstr *CopyOut = nullptr;
2073 if (DstR != FoundR) {
2074 DebugLoc DL = MI->getDebugLoc();
2075 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2076 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2077 unsigned CopyOpc = TargetOpcode::COPY;
2078 if (HII.isSignExtendingLoad(MI))
2079 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2080 else if (HII.isZeroExtendingLoad(MI))
2081 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2082 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2083 .addReg(FoundR, getKillRegState(MI == EI));
2084 }
2085 IM.replaceInstr(MI, CopyOut);
2086 B.erase(It);
2087 }
2088
2089 // Update the dead map.
2090 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2091 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2092 DM[RR].subtract(Range);
2093 } // for Range in range list
2094 }
2095 }
2096}
2097
2098
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002099void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002100 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002101 MachineBasicBlock &MB = *AI->getParent();
2102 DebugLoc DL = AI->getDebugLoc();
2103 unsigned A = AI->getOperand(2).getImm();
2104
2105 // Have
2106 // Rd = alloca Rs, #A
2107 //
2108 // If Rs and Rd are different registers, use this sequence:
2109 // Rd = sub(r29, Rs)
2110 // r29 = sub(r29, Rs)
2111 // Rd = and(Rd, #-A) ; if necessary
2112 // r29 = and(r29, #-A) ; if necessary
2113 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2114 // otherwise, do
2115 // Rd = sub(r29, Rs)
2116 // Rd = and(Rd, #-A) ; if necessary
2117 // r29 = Rd
2118 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2119
2120 MachineOperand &RdOp = AI->getOperand(0);
2121 MachineOperand &RsOp = AI->getOperand(1);
2122 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2123
2124 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002125 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002126 .addReg(SP)
2127 .addReg(Rs);
2128 if (Rs != Rd) {
2129 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002130 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002131 .addReg(SP)
2132 .addReg(Rs);
2133 }
2134 if (A > 8) {
2135 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002136 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002137 .addReg(Rd)
2138 .addImm(-int64_t(A));
2139 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002140 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002141 .addReg(SP)
2142 .addImm(-int64_t(A));
2143 }
2144 if (Rs == Rd) {
2145 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002146 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002147 .addReg(Rd);
2148 }
2149 if (CF > 0) {
2150 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002151 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002152 .addReg(Rd)
2153 .addImm(CF);
2154 }
2155}
2156
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002157
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002158bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2159 const MachineFrameInfo *MFI = MF.getFrameInfo();
2160 if (!MFI->hasVarSizedObjects())
2161 return false;
2162 unsigned MaxA = MFI->getMaxAlignment();
2163 if (MaxA <= getStackAlignment())
2164 return false;
2165 return true;
2166}
2167
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002168
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002169const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2170 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002171 for (auto &B : MF)
2172 for (auto &I : B)
2173 if (I.getOpcode() == Hexagon::ALIGNA)
2174 return &I;
2175 return nullptr;
2176}
2177
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002178
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002179/// Adds all callee-saved registers as implicit uses or defs to the
2180/// instruction.
2181void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2182 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2183 // Add the callee-saved registers as implicit uses.
2184 for (auto &R : CSI)
2185 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2186}
2187
2188
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002189/// Determine whether the callee-saved register saves and restores should
2190/// be generated via inline code. If this function returns "true", inline
2191/// code will be generated. If this function returns "false", additional
2192/// checks are performed, which may still lead to the inline code.
2193bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2194 const CSIVect &CSI) const {
2195 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2196 return true;
2197 if (!isOptSize(MF) && !isMinSize(MF))
2198 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2199 return true;
2200
2201 // Check if CSI only has double registers, and if the registers form
2202 // a contiguous block starting from D8.
2203 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2204 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2205 unsigned R = CSI[i].getReg();
2206 if (!Hexagon::DoubleRegsRegClass.contains(R))
2207 return true;
2208 Regs[R] = true;
2209 }
2210 int F = Regs.find_first();
2211 if (F != Hexagon::D8)
2212 return true;
2213 while (F >= 0) {
2214 int N = Regs.find_next(F);
2215 if (N >= 0 && N != F+1)
2216 return true;
2217 F = N;
2218 }
2219
2220 return false;
2221}
2222
2223
2224bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2225 const CSIVect &CSI) const {
2226 if (shouldInlineCSR(MF, CSI))
2227 return false;
2228 unsigned NumCSI = CSI.size();
2229 if (NumCSI <= 1)
2230 return false;
2231
2232 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2233 : SpillFuncThreshold;
2234 return Threshold < NumCSI;
2235}
2236
2237
2238bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2239 const CSIVect &CSI) const {
2240 if (shouldInlineCSR(MF, CSI))
2241 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002242 // The restore functions do a bit more than just restoring registers.
2243 // The non-returning versions will go back directly to the caller's
2244 // caller, others will clean up the stack frame in preparation for
2245 // a tail call. Using them can still save code size even if only one
2246 // register is getting restores. Make the decision based on -Oz:
2247 // using -Os will use inline restore for a single register.
2248 if (isMinSize(MF))
2249 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002250 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002251 if (NumCSI <= 1)
2252 return false;
2253
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002254 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2255 : SpillFuncThreshold;
2256 return Threshold < NumCSI;
2257}