blob: e13bbacd43d9a810a666a63a4c755ac889376f26 [file] [log] [blame]
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +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
Craig Topperb25fda92012-03-17 18:46:09 +000011#include "HexagonFrameLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "HexagonBlockRanges.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000013#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonRegisterInfo.h"
16#include "HexagonSubtarget.h"
17#include "HexagonTargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000018#include "MCTargetDesc/HexagonBaseInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000019#include "llvm/ADT/BitVector.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000023#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000024#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/SmallVector.h"
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +000027#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000028#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000029#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000030#include "llvm/CodeGen/MachineFrameInfo.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000033#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000035#include "llvm/CodeGen/MachineMemOperand.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000036#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000037#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000038#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
40#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000041#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +000042#include "llvm/IR/Attributes.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000043#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000045#include "llvm/MC/MCDwarf.h"
46#include "llvm/MC/MCRegisterInfo.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/CodeGen.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +000050#include "llvm/Support/Compiler.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000051#include "llvm/Support/Debug.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000052#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/MathExtras.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000054#include "llvm/Support/raw_ostream.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000055#include "llvm/Target/TargetMachine.h"
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +000056#include "llvm/Target/TargetOptions.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000057#include <algorithm>
58#include <cassert>
59#include <cstdint>
60#include <iterator>
61#include <limits>
62#include <map>
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000063#include <utility>
64#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000065
Jakub Kuderski34327d22017-07-13 20:26:45 +000066#define DEBUG_TYPE "hexagon-pei"
67
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000068// Hexagon stack frame layout as defined by the ABI:
69//
70// Incoming arguments
71// passed via stack
72// |
73// |
74// SP during function's FP during function's |
75// +-- runtime (top of stack) runtime (bottom) --+ |
76// | | |
77// --++---------------------+------------------+-----------------++-+-------
78// | parameter area for | variable-size | fixed-size |LR| arg
79// | called functions | local objects | local objects |FP|
80// --+----------------------+------------------+-----------------+--+-------
81// <- size known -> <- size unknown -> <- size known ->
82//
83// Low address High address
84//
85// <--- stack growth
86//
87//
88// - In any circumstances, the outgoing function arguments are always accessi-
89// ble using the SP, and the incoming arguments are accessible using the FP.
90// - If the local objects are not aligned, they can always be accessed using
91// the FP.
92// - If there are no variable-sized objects, the local objects can always be
93// accessed using the SP, regardless whether they are aligned or not. (The
94// alignment padding will be at the bottom of the stack (highest address),
95// and so the offset with respect to the SP will be known at the compile-
96// -time.)
97//
98// The only complication occurs if there are both, local aligned objects, and
99// dynamically allocated (variable-sized) objects. The alignment pad will be
100// placed between the FP and the local objects, thus preventing the use of the
101// FP to access the local objects. At the same time, the variable-sized objects
102// will be between the SP and the local objects, thus introducing an unknown
103// distance from the SP to the locals.
104//
105// To avoid this problem, a new register is created that holds the aligned
106// address of the bottom of the stack, referred in the sources as AP (aligned
107// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
108// that aligns AP to the required boundary (a maximum of the alignments of
109// all stack objects, fixed- and variable-sized). All local objects[1] will
110// then use AP as the base pointer.
111// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
112// their name from being allocated at fixed locations on the stack, relative
113// to the FP. In the presence of dynamic allocation and local alignment, such
114// objects can only be accessed through the FP.
115//
116// Illustration of the AP:
117// FP --+
118// |
119// ---------------+---------------------+-----+-----------------------++-+--
120// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
121// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
122// ---------------+---------------------+-----+-----------------+-----+--+--
123// |<-- Multiple of the -->|
124// stack alignment +-- AP
125//
126// The AP is set up at the beginning of the function. Since it is not a dedi-
127// cated (reserved) register, it needs to be kept live throughout the function
128// to be available as the base register for local object accesses.
129// Normally, an address of a stack objects is obtained by a pseudo-instruction
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000130// PS_fi. To access local objects with the AP register present, a different
131// pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
132// argument compared to PS_fi: the first input register is the AP register.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000133// This keeps the register live between its definition and its uses.
134
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000135// The AP register is originally set up using pseudo-instruction PS_aligna:
136// AP = PS_aligna A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000137// where
138// A - required stack alignment
139// The alignment value must be the maximum of all alignments required by
140// any stack object.
141
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000142// The dynamic allocation uses a pseudo-instruction PS_alloca:
143// Rd = PS_alloca Rs, A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000144// where
145// Rd - address of the allocated space
146// Rs - minimum size (the actual allocated can be larger to accommodate
147// alignment)
148// A - required alignment
149
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000150using namespace llvm;
151
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000152static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
153 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000154
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +0000155static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000156 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
157 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000158
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000159static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000160 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
161 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000162
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000163static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000164 cl::Hidden, cl::desc("Specify Os spill func threshold"),
165 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000166
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000167static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
168 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
169 cl::init(false), cl::ZeroOrMore);
170
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000171static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
172 cl::init(true), cl::Hidden, cl::ZeroOrMore,
173 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000174
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000175static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
176 cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore,
177 cl::desc("Max count of stack frame shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000178
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000179static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
180 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
181 cl::init(false), cl::ZeroOrMore);
182
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000183static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true),
184 cl::Hidden, cl::desc("Refrain from using FP whenever possible"));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000185
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000186static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
187 cl::init(true), cl::desc("Optimize spill slots"));
188
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000189#ifndef NDEBUG
190static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000191 cl::init(std::numeric_limits<unsigned>::max()));
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000192static unsigned SpillOptCount = 0;
193#endif
194
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000195namespace llvm {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000196
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000197 void initializeHexagonCallFrameInformationPass(PassRegistry&);
198 FunctionPass *createHexagonCallFrameInformation();
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000199
200} // end namespace llvm
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000201
202namespace {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000203
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000204 class HexagonCallFrameInformation : public MachineFunctionPass {
205 public:
206 static char ID;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000207
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000208 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
209 PassRegistry &PR = *PassRegistry::getPassRegistry();
210 initializeHexagonCallFrameInformationPass(PR);
211 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000212
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000213 bool runOnMachineFunction(MachineFunction &MF) override;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000214
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000215 MachineFunctionProperties getRequiredProperties() const override {
216 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000217 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000218 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000219 };
220
221 char HexagonCallFrameInformation::ID = 0;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000222
223} // end anonymous namespace
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000224
225bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
226 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
227 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
228 MF.getFunction()->needsUnwindTableEntry();
229
230 if (!NeedCFI)
231 return false;
232 HFI.insertCFIInstructions(MF);
233 return true;
234}
235
236INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
237 "Hexagon call frame information", false, false)
238
239FunctionPass *llvm::createHexagonCallFrameInformation() {
240 return new HexagonCallFrameInformation();
241}
242
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000243/// Map a register pair Reg to the subregister that has the greater "number",
244/// i.e. D3 (aka R7:6) will be mapped to R7, etc.
245static unsigned getMax32BitSubRegister(unsigned Reg,
246 const TargetRegisterInfo &TRI,
247 bool hireg = true) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000248 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
249 return Reg;
250
251 unsigned RegNo = 0;
252 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
253 if (hireg) {
254 if (*SubRegs > RegNo)
255 RegNo = *SubRegs;
256 } else {
257 if (!RegNo || *SubRegs < RegNo)
258 RegNo = *SubRegs;
259 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000260 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000261 return RegNo;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000262}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000263
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000264/// Returns the callee saved register with the largest id in the vector.
265static unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
266 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000267 static_assert(Hexagon::R1 > 0,
268 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000269 if (CSI.empty())
270 return 0;
271
272 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
273 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
274 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
275 if (Reg > Max)
276 Max = Reg;
277 }
278 return Max;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000279}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000280
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000281/// Checks if the basic block contains any instruction that needs a stack
282/// frame to be already in place.
283static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
284 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000285 for (auto &I : MBB) {
286 const MachineInstr *MI = &I;
287 if (MI->isCall())
288 return true;
289 unsigned Opc = MI->getOpcode();
290 switch (Opc) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000291 case Hexagon::PS_alloca:
292 case Hexagon::PS_aligna:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000293 return true;
294 default:
295 break;
296 }
297 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000298 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000299 // While the presence of a frame index does not prove that a stack
300 // frame will be required, all frame indexes should be within alloc-
301 // frame/deallocframe. Otherwise, the code that translates a frame
302 // index into an offset would have to be aware of the placement of
303 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000304 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000305 return true;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000306 if (MO.isReg()) {
307 unsigned R = MO.getReg();
308 // Virtual registers will need scavenging, which then may require
309 // a stack slot.
310 if (TargetRegisterInfo::isVirtualRegister(R))
Rafael Espindola6eab4042017-02-17 02:08:58 +0000311 return true;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000312 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
313 if (CSR[*S])
314 return true;
315 continue;
316 }
317 if (MO.isRegMask()) {
318 // A regmask would normally have all callee-saved registers marked
319 // as preserved, so this check would not be needed, but in case of
320 // ever having other regmasks (for other calling conventions),
321 // make sure they would be processed correctly.
322 const uint32_t *BM = MO.getRegMask();
323 for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) {
324 unsigned R = x;
325 // If this regmask does not preserve a CSR, a frame will be needed.
326 if (!(BM[R/32] & (1u << (R%32))))
327 return true;
328 }
329 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000330 }
331 }
332 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000333}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000334
335 /// Returns true if MBB has a machine instructions that indicates a tail call
336 /// in the block.
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000337static bool hasTailCall(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000338 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
339 unsigned RetOpc = I->getOpcode();
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000340 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000341}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000342
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000343/// Returns true if MBB contains an instruction that returns.
344static bool hasReturn(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000345 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
346 if (I->isReturn())
347 return true;
348 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000349}
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000350
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000351/// Returns the "return" instruction from this block, or nullptr if there
352/// isn't any.
353static MachineInstr *getReturn(MachineBasicBlock &MBB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000354 for (auto &I : MBB)
355 if (I.isReturn())
356 return &I;
357 return nullptr;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000358}
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000359
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000360static bool isRestoreCall(unsigned Opc) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000361 switch (Opc) {
362 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
363 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000364 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
365 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
366 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
367 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000368 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
369 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
370 return true;
371 }
372 return false;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000373}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000374
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000375static inline bool isOptNone(const MachineFunction &MF) {
376 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
377 MF.getTarget().getOptLevel() == CodeGenOpt::None;
378}
379
380static inline bool isOptSize(const MachineFunction &MF) {
381 const Function &F = *MF.getFunction();
382 return F.optForSize() && !F.optForMinSize();
383}
384
385static inline bool isMinSize(const MachineFunction &MF) {
386 return MF.getFunction()->optForMinSize();
387}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000388
389/// Implements shrink-wrapping of the stack frame. By default, stack frame
390/// is created in the function entry block, and is cleaned up in every block
391/// that returns. This function finds alternate blocks: one for the frame
392/// setup (prolog) and one for the cleanup (epilog).
393void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
394 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
395 static unsigned ShrinkCounter = 0;
396
397 if (ShrinkLimit.getPosition()) {
398 if (ShrinkCounter >= ShrinkLimit)
399 return;
400 ShrinkCounter++;
401 }
402
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000403 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000404
405 MachineDominatorTree MDT;
406 MDT.runOnMachineFunction(MF);
407 MachinePostDominatorTree MPT;
408 MPT.runOnMachineFunction(MF);
409
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +0000410 using UnsignedMap = DenseMap<unsigned, unsigned>;
411 using RPOTType = ReversePostOrderTraversal<const MachineFunction *>;
412
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000413 UnsignedMap RPO;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000414 RPOTType RPOT(&MF);
415 unsigned RPON = 0;
416 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
417 RPO[(*I)->getNumber()] = RPON++;
418
419 // Don't process functions that have loops, at least for now. Placement
420 // of prolog and epilog must take loop structure into account. For simpli-
421 // city don't do it right now.
422 for (auto &I : MF) {
423 unsigned BN = RPO[I.getNumber()];
424 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
425 // If found a back-edge, return.
426 if (RPO[(*SI)->getNumber()] <= BN)
427 return;
428 }
429 }
430
431 // Collect the set of blocks that need a stack frame to execute. Scan
432 // each block for uses/defs of callee-saved registers, calls, etc.
433 SmallVector<MachineBasicBlock*,16> SFBlocks;
434 BitVector CSR(Hexagon::NUM_TARGET_REGS);
435 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000436 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
437 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000438
439 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000440 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000441 SFBlocks.push_back(&I);
442
443 DEBUG({
444 dbgs() << "Blocks needing SF: {";
445 for (auto &B : SFBlocks)
446 dbgs() << " BB#" << B->getNumber();
447 dbgs() << " }\n";
448 });
449 // No frame needed?
450 if (SFBlocks.empty())
451 return;
452
453 // Pick a common dominator and a common post-dominator.
454 MachineBasicBlock *DomB = SFBlocks[0];
455 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
456 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
457 if (!DomB)
458 break;
459 }
460 MachineBasicBlock *PDomB = SFBlocks[0];
461 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
462 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
463 if (!PDomB)
464 break;
465 }
466 DEBUG({
467 dbgs() << "Computed dom block: BB#";
468 if (DomB) dbgs() << DomB->getNumber();
469 else dbgs() << "<null>";
470 dbgs() << ", computed pdom block: BB#";
471 if (PDomB) dbgs() << PDomB->getNumber();
472 else dbgs() << "<null>";
473 dbgs() << "\n";
474 });
475 if (!DomB || !PDomB)
476 return;
477
478 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
479 if (!MDT.dominates(DomB, PDomB)) {
480 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
481 return;
482 }
483 if (!MPT.dominates(PDomB, DomB)) {
484 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
485 return;
486 }
487
488 // Finally, everything seems right.
489 PrologB = DomB;
490 EpilogB = PDomB;
491}
492
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000493/// Perform most of the PEI work here:
494/// - saving/restoring of the callee-saved registers,
495/// - stack frame creation and destruction.
496/// Normally, this work is distributed among various functions, but doing it
497/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000498void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
499 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000500 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000501
Matthias Braun941a7052016-07-28 18:40:00 +0000502 MachineFrameInfo &MFI = MF.getFrameInfo();
503 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000504
505 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
506 if (EnableShrinkWrapping)
507 findShrunkPrologEpilog(MF, PrologB, EpilogB);
508
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000509 bool PrologueStubs = false;
510 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
511 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000512 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000513
514 if (EpilogB) {
515 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
516 insertEpilogueInBlock(*EpilogB);
517 } else {
518 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000519 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000520 insertCSRRestoresInBlock(B, CSI, HRI);
521
522 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000523 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000524 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000525
526 for (auto &B : MF) {
527 if (B.empty())
528 continue;
529 MachineInstr *RetI = getReturn(B);
530 if (!RetI || isRestoreCall(RetI->getOpcode()))
531 continue;
532 for (auto &R : CSI)
533 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
534 }
535 }
536
537 if (EpilogB) {
538 // If there is an epilog block, it may not have a return instruction.
539 // In such case, we need to add the callee-saved registers as live-ins
540 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000541 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000542 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000543 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000544 }
545}
546
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000547void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
548 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000549 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000550 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000551 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000552 auto &HII = *HST.getInstrInfo();
553 auto &HRI = *HST.getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000554
Krzysztof Parzyszek71702172017-06-23 19:47:04 +0000555 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000556
557 // Calculate the total stack frame size.
558 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000559 unsigned FrameSize = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000560 // Round up the max call frame size to the max alignment on the stack.
Matthias Braun941a7052016-07-28 18:40:00 +0000561 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
562 MFI.setMaxCallFrameSize(MaxCFA);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000563
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000564 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Matthias Braun941a7052016-07-28 18:40:00 +0000565 MFI.setStackSize(FrameSize);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000566
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000567 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000568
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000569 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000570 unsigned NumBytes = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000571 unsigned SP = HRI.getStackRegister();
Matthias Braun941a7052016-07-28 18:40:00 +0000572 unsigned MaxCF = MFI.getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000573 MachineBasicBlock::iterator InsertPt = MBB.begin();
574
Krzysztof Parzyszek8849a512016-08-19 18:46:13 +0000575 SmallVector<MachineInstr *, 4> AdjustRegs;
576 for (auto &MBB : MF)
577 for (auto &MI : MBB)
578 if (MI.getOpcode() == Hexagon::PS_alloca)
579 AdjustRegs.push_back(&MI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000580
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000581 for (auto MI : AdjustRegs) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000582 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000583 expandAlloca(MI, HII, SP, MaxCF);
584 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000585 }
586
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000587 DebugLoc dl = MBB.findDebugLoc(InsertPt);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000588
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000589 if (hasFP(MF)) {
590 insertAllocframe(MBB, InsertPt, NumBytes);
591 if (AlignStack) {
592 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
593 .addReg(SP)
594 .addImm(-int64_t(MaxAlign));
595 }
596 // If the stack-checking is enabled, and we spilled the callee-saved
597 // registers inline (i.e. did not use a spill function), then call
598 // the stack checker directly.
599 if (EnableStackOVFSanitizer && !PrologueStubs)
600 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
601 .addExternalSymbol("__runtime_stack_check");
602 } else if (NumBytes > 0) {
603 assert(alignTo(NumBytes, 8) == NumBytes);
604 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000605 .addReg(SP)
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000606 .addImm(-int(NumBytes));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000607 }
608}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000609
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000610void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
611 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000612 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000613 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000614 auto &HRI = *HST.getRegisterInfo();
615 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000616
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000617 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
618 DebugLoc dl = MBB.findDebugLoc(InsertPt);
619
620 if (!hasFP(MF)) {
621 MachineFrameInfo &MFI = MF.getFrameInfo();
622 if (unsigned NumBytes = MFI.getStackSize()) {
623 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
624 .addReg(SP)
625 .addImm(NumBytes);
626 }
627 return;
628 }
629
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000630 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000631 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
632
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000633 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000634 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000635 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
636 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000637 .addReg(SP)
638 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000639 return;
640 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000641
642 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
643 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000644 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000645 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
646 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
647 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000648 MachineBasicBlock::iterator It = RetI;
649 ++It;
650 // Delete all instructions after the RESTORE (except labels).
651 while (It != MBB.end()) {
652 if (!It->isLabel())
653 It = MBB.erase(It);
654 else
655 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000656 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000657 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000658 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000659
660 // It is possible that the restoring code is a call to a library function.
661 // All of the restore* functions include "deallocframe", so we need to make
662 // sure that we don't add an extra one.
663 bool NeedsDeallocframe = true;
664 if (!MBB.empty() && InsertPt != MBB.begin()) {
665 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
666 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000667 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000668 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
669 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
670 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000671 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000672 NeedsDeallocframe = false;
673 }
674
675 if (!NeedsDeallocframe)
676 return;
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000677 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000678 // otherwise just add deallocframe. The function could be returning via a
679 // tail call.
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000680 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000681 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000682 return;
683 }
684 unsigned NewOpc = Hexagon::L4_return;
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000685 MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc));
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000686 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000687 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000688 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000689}
690
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000691void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
692 MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
693 MachineFunction &MF = *MBB.getParent();
694 auto &HST = MF.getSubtarget<HexagonSubtarget>();
695 auto &HII = *HST.getInstrInfo();
696 auto &HRI = *HST.getRegisterInfo();
697
698 // Check for overflow.
699 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
700 const unsigned int ALLOCFRAME_MAX = 16384;
701
702 // Create a dummy memory operand to avoid allocframe from being treated as
703 // a volatile memory reference.
704 auto *MMO = MF.getMachineMemOperand(MachinePointerInfo::getStack(MF, 0),
705 MachineMemOperand::MOStore, 4, 4);
706
707 DebugLoc dl = MBB.findDebugLoc(InsertPt);
708
709 if (NumBytes >= ALLOCFRAME_MAX) {
710 // Emit allocframe(#0).
711 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
712 .addImm(0)
713 .addMemOperand(MMO);
714
715 // Subtract the size from the stack pointer.
716 unsigned SP = HRI.getStackRegister();
717 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
718 .addReg(SP)
719 .addImm(-int(NumBytes));
720 } else {
721 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
722 .addImm(NumBytes)
723 .addMemOperand(MMO);
724 }
725}
726
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000727void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
728 MachineBasicBlock &SaveB) const {
729 SetVector<unsigned> Worklist;
730
731 MachineBasicBlock &EntryB = MF.front();
732 Worklist.insert(EntryB.getNumber());
733
734 unsigned SaveN = SaveB.getNumber();
Matthias Braun941a7052016-07-28 18:40:00 +0000735 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000736
737 for (unsigned i = 0; i < Worklist.size(); ++i) {
738 unsigned BN = Worklist[i];
739 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
740 for (auto &R : CSI)
741 if (!MBB.isLiveIn(R.getReg()))
742 MBB.addLiveIn(R.getReg());
743 if (BN != SaveN)
744 for (auto &SB : MBB.successors())
745 Worklist.insert(SB->getNumber());
746 }
747}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000748
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000749bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000750 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000751 BitVector &Path) const {
752 assert(MBB.getNumber() >= 0);
753 unsigned BN = MBB.getNumber();
754 if (Path[BN] || DoneF[BN])
755 return false;
756 if (DoneT[BN])
757 return true;
758
Matthias Braun941a7052016-07-28 18:40:00 +0000759 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000760
761 Path[BN] = true;
762 bool ReachedExit = false;
763 for (auto &SB : MBB.successors())
764 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
765
766 if (!MBB.empty() && MBB.back().isReturn()) {
767 // Add implicit uses of all callee-saved registers to the reached
768 // return instructions. This is to prevent the anti-dependency breaker
769 // from renaming these registers.
770 MachineInstr &RetI = MBB.back();
771 if (!isRestoreCall(RetI.getOpcode()))
772 for (auto &R : CSI)
773 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
774 ReachedExit = true;
775 }
776
777 // We don't want to add unnecessary live-ins to the restore block: since
778 // the callee-saved registers are being defined in it, the entry of the
779 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000780 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000781 for (auto &R : CSI)
782 if (!MBB.isLiveIn(R.getReg()))
783 MBB.addLiveIn(R.getReg());
784 DoneT[BN] = true;
785 }
786 if (!ReachedExit)
787 DoneF[BN] = true;
788
789 Path[BN] = false;
790 return ReachedExit;
791}
792
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000793static Optional<MachineBasicBlock::iterator>
794findCFILocation(MachineBasicBlock &B) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000795 // The CFI instructions need to be inserted right after allocframe.
796 // An exception to this is a situation where allocframe is bundled
797 // with a call: then the CFI instructions need to be inserted before
798 // the packet with the allocframe+call (in case the call throws an
799 // exception).
800 auto End = B.instr_end();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000801
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000802 for (MachineInstr &I : B) {
803 MachineBasicBlock::iterator It = I.getIterator();
804 if (!I.isBundle()) {
805 if (I.getOpcode() == Hexagon::S2_allocframe)
806 return std::next(It);
807 continue;
808 }
809 // I is a bundle.
810 bool HasCall = false, HasAllocFrame = false;
811 auto T = It.getInstrIterator();
812 while (++T != End && T->isBundled()) {
813 if (T->getOpcode() == Hexagon::S2_allocframe)
814 HasAllocFrame = true;
815 else if (T->isCall())
816 HasCall = true;
817 }
818 if (HasAllocFrame)
819 return HasCall ? It : std::next(It);
820 }
821 return None;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000822}
823
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000824void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
825 for (auto &B : MF) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000826 auto At = findCFILocation(B);
827 if (At.hasValue())
828 insertCFIInstructionsAt(B, At.getValue());
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000829 }
830}
831
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000832void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
833 MachineBasicBlock::iterator At) const {
834 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000835 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000836 MachineModuleInfo &MMI = MF.getMMI();
837 auto &HST = MF.getSubtarget<HexagonSubtarget>();
838 auto &HII = *HST.getInstrInfo();
839 auto &HRI = *HST.getRegisterInfo();
840
841 // If CFI instructions have debug information attached, something goes
842 // wrong with the final assembly generation: the prolog_end is placed
843 // in a wrong location.
844 DebugLoc DL;
845 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
846
847 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000848 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000849
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000850 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000851 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
852 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000853
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000854 // Define CFA via an offset from the value of FP.
855 //
856 // -8 -4 0 (SP)
857 // --+----+----+---------------------
858 // | FP | LR | increasing addresses -->
859 // --+----+----+---------------------
860 // | +-- Old SP (before allocframe)
861 // +-- New FP (after allocframe)
862 //
863 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
864 // MCCFIInstruction::createOffset takes the offset without sign change.
865 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
866 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000867 .addCFIIndex(MF.addFrameInst(DefCfa));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000868 // R31 (return addr) = CFA - 4
869 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
870 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000871 .addCFIIndex(MF.addFrameInst(OffR31));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000872 // R30 (frame ptr) = CFA - 8
873 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
874 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000875 .addCFIIndex(MF.addFrameInst(OffR30));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000876 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000877
878 static unsigned int RegsToMove[] = {
879 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
880 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
881 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
882 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
883 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
884 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
885 Hexagon::NoRegister
886 };
887
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000888 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000889
890 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
891 unsigned Reg = RegsToMove[i];
892 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
893 return C.getReg() == Reg;
894 };
David Majnemer562e8292016-08-12 00:18:03 +0000895 auto F = find_if(CSI, IfR);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000896 if (F == CSI.end())
897 continue;
898
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000899 int64_t Offset;
900 if (HasFP) {
901 // If the function has a frame pointer (i.e. has an allocframe),
902 // then the CFA has been defined in terms of FP. Any offsets in
903 // the following CFI instructions have to be defined relative
904 // to FP, which points to the bottom of the stack frame.
905 // The function getFrameIndexReference can still choose to use SP
906 // for the offset calculation, so we cannot simply call it here.
907 // Instead, get the offset (relative to the FP) directly.
908 Offset = MFI.getObjectOffset(F->getFrameIdx());
909 } else {
910 unsigned FrameReg;
911 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
912 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000913 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000914 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000915
916 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
917 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
918 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
919 Offset);
920 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000921 .addCFIIndex(MF.addFrameInst(OffReg));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000922 } else {
923 // Split the double regs into subregs, and generate appropriate
924 // cfi_offsets.
925 // The only reason, we are split double regs is, llvm-mc does not
926 // understand paired registers for cfi_offset.
927 // Eg .cfi_offset r1:0, -64
928
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000929 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
930 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000931 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
932 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
933 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
934 Offset+4);
935 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000936 .addCFIIndex(MF.addFrameInst(OffHi));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000937 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
938 Offset);
939 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000940 .addCFIIndex(MF.addFrameInst(OffLo));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000941 }
942 }
943}
944
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000945bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000946 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
947 return false;
948
Matthias Braun941a7052016-07-28 18:40:00 +0000949 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000950 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000951 bool HasExtraAlign = HRI.needsStackRealignment(MF);
952 bool HasAlloca = MFI.hasVarSizedObjects();
953
954 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
955 // that this shouldn't be required, but doing so now because gcc does and
956 // gdb can't break at the start of the function without it. Will remove if
957 // this turns out to be a gdb bug.
958 //
959 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
960 return true;
961
962 // By default we want to use SP (since it's always there). FP requires
963 // some setup (i.e. ALLOCFRAME).
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000964 // Both, alloca and stack alignment modify the stack pointer by an
965 // undetermined value, so we need to save it at the entry to the function
966 // (i.e. use allocframe).
967 if (HasAlloca || HasExtraAlign)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000968 return true;
969
970 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000971 // If FP-elimination is disabled, we have to use FP at this point.
972 const TargetMachine &TM = MF.getTarget();
973 if (TM.Options.DisableFramePointerElim(MF) || !EliminateFramePointer)
974 return true;
975 if (EnableStackOVFSanitizer)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000976 return true;
977 }
978
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000979 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
980 if (MFI.hasCalls() || HMFI.hasClobberLR())
981 return true;
982
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000983 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000984}
985
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000986enum SpillKind {
987 SK_ToMem,
988 SK_FromMem,
989 SK_FromMemTailcall
990};
991
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000992static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
993 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000994 const char * V4SpillToMemoryFunctions[] = {
995 "__save_r16_through_r17",
996 "__save_r16_through_r19",
997 "__save_r16_through_r21",
998 "__save_r16_through_r23",
999 "__save_r16_through_r25",
1000 "__save_r16_through_r27" };
1001
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001002 const char * V4SpillToMemoryStkchkFunctions[] = {
1003 "__save_r16_through_r17_stkchk",
1004 "__save_r16_through_r19_stkchk",
1005 "__save_r16_through_r21_stkchk",
1006 "__save_r16_through_r23_stkchk",
1007 "__save_r16_through_r25_stkchk",
1008 "__save_r16_through_r27_stkchk" };
1009
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001010 const char * V4SpillFromMemoryFunctions[] = {
1011 "__restore_r16_through_r17_and_deallocframe",
1012 "__restore_r16_through_r19_and_deallocframe",
1013 "__restore_r16_through_r21_and_deallocframe",
1014 "__restore_r16_through_r23_and_deallocframe",
1015 "__restore_r16_through_r25_and_deallocframe",
1016 "__restore_r16_through_r27_and_deallocframe" };
1017
1018 const char * V4SpillFromMemoryTailcallFunctions[] = {
1019 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1020 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1021 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1022 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1023 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1024 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1025 };
1026
1027 const char **SpillFunc = nullptr;
1028
1029 switch(SpillType) {
1030 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001031 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1032 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001033 break;
1034 case SK_FromMem:
1035 SpillFunc = V4SpillFromMemoryFunctions;
1036 break;
1037 case SK_FromMemTailcall:
1038 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1039 break;
1040 }
1041 assert(SpillFunc && "Unknown spill kind");
1042
1043 // Spill all callee-saved registers up to the highest register used.
1044 switch (MaxReg) {
1045 case Hexagon::R17:
1046 return SpillFunc[0];
1047 case Hexagon::R19:
1048 return SpillFunc[1];
1049 case Hexagon::R21:
1050 return SpillFunc[2];
1051 case Hexagon::R23:
1052 return SpillFunc[3];
1053 case Hexagon::R25:
1054 return SpillFunc[4];
1055 case Hexagon::R27:
1056 return SpillFunc[5];
1057 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001058 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001059 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001060 return nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001061}
1062
James Y Knight5567baf2015-08-15 02:32:35 +00001063int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001064 int FI, unsigned &FrameReg) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001065 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001066 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001067
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001068 int Offset = MFI.getObjectOffset(FI);
1069 bool HasAlloca = MFI.hasVarSizedObjects();
1070 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1071 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001072
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001073 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00001074 unsigned FrameSize = MFI.getStackSize();
1075 unsigned SP = HRI.getStackRegister();
1076 unsigned FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001077 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek918e6d72017-06-26 14:17:58 +00001078 // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1079 // is true. HasExtraAlign may be set because of vector spills, without
1080 // aligned locals or aligned outgoing function arguments. Since vector
1081 // spills will ultimately be "unaligned", it is safe to use FP as the
1082 // base register.
1083 // In fact, in such a scenario the stack is actually not required to be
1084 // aligned, although it may end up being aligned anyway, since this
1085 // particular case is not easily detectable. The alignment will be
1086 // unnecessary, but not incorrect.
1087 // Unfortunately there is no quick way to verify that the above is
1088 // indeed the case (and that it's not a result of an error), so just
1089 // assume that missing AP will be replaced by FP.
1090 // (A better fix would be to rematerialize AP from FP and always align
1091 // vector spills.)
1092 if (AP == 0)
1093 AP = FP;
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001094
1095 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1096 // Use FP at -O0, except when there are objects with extra alignment.
1097 // That additional alignment requirement may cause a pad to be inserted,
1098 // which will make it impossible to use FP to access objects located
1099 // past the pad.
1100 if (NoOpt && !HasExtraAlign)
1101 UseFP = true;
1102 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1103 // Fixed and preallocated objects will be located before any padding
1104 // so FP must be used to access them.
1105 UseFP |= (HasAlloca || HasExtraAlign);
1106 } else {
1107 if (HasAlloca) {
1108 if (HasExtraAlign)
1109 UseAP = true;
1110 else
1111 UseFP = true;
1112 }
1113 }
1114
1115 // If FP was picked, then there had better be FP.
1116 bool HasFP = hasFP(MF);
1117 assert((HasFP || !UseFP) && "This function must have frame pointer");
1118
1119 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1120 // FP/LR. If the base register is used to access an object across these
1121 // 8 bytes, then the offset will need to be adjusted by 8.
1122 //
1123 // After allocframe:
1124 // HexagonISelLowering adds 8 to ---+
1125 // the offsets of all stack-based |
1126 // arguments (*) |
1127 // |
1128 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1129 // ------------------------+-----+------------------------> increasing
1130 // <local objects> |FP/LR| <input arguments> addresses
1131 // -----------------+------+-----+------------------------>
1132 // | |
1133 // SP/AP point --+ +-- FP points here (**)
1134 // somewhere on
1135 // this side of FP/LR
1136 //
1137 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1138 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1139
1140 // The lowering assumes that FP/LR is present, and so the offsets of
1141 // the formal arguments start at 8. If FP/LR is not there we need to
1142 // reduce the offset by 8.
1143 if (Offset > 0 && !HasFP)
1144 Offset -= 8;
1145
1146 if (UseFP)
1147 FrameReg = FP;
1148 else if (UseAP)
1149 FrameReg = AP;
1150 else
1151 FrameReg = SP;
1152
1153 // Calculate the actual offset in the instruction. If there is no FP
1154 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1155 // there will be no SP -= FrameSize), so the frame size should not be
1156 // added to the calculated offset.
1157 int RealOffset = Offset;
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00001158 if (!UseFP && !UseAP)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001159 RealOffset = FrameSize+Offset;
1160 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001161}
1162
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001163bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001164 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1165 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001166 if (CSI.empty())
1167 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001168
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001169 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001170 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001171 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001172 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1173 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001174
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001175 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001176 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001177 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001178 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1179 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1180 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001181 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001182 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001183 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001184
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001185 // Call spill function.
1186 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001187 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001188 if (StkOvrFlowEnabled) {
1189 if (LongCalls)
1190 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1191 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1192 else
1193 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1194 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1195 } else {
1196 if (LongCalls)
1197 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1198 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1199 else
1200 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1201 : Hexagon::SAVE_REGISTERS_CALL_V4;
1202 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001203
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001204 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001205 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001206 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001207
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001208 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001209 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001210 // Add live in registers.
1211 for (unsigned I = 0; I < CSI.size(); ++I)
1212 MBB.addLiveIn(CSI[I].getReg());
1213 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001214 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001215
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001216 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001217 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001218 // Add live in registers. We treat eh_return callee saved register r0 - r3
1219 // specially. They are not really callee saved registers as they are not
1220 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001221 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1222 int FI = CSI[i].getFrameIdx();
1223 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001224 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001225 if (IsKill)
1226 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001227 }
1228 return true;
1229}
1230
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001231bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1232 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1233 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001234 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001235
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001236 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1237 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001238 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1239 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001240
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001241 if (useRestoreFunction(MF, CSI)) {
1242 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1243 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1244 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1245 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001246 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001247 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001248 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001249
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001250 // Call spill function.
1251 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1252 : MBB.getLastNonDebugInstr()->getDebugLoc();
1253 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001254
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001255 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001256 unsigned RetOpc;
1257 if (LongCalls)
1258 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1259 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1260 else
1261 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1262 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1263 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001264 .addExternalSymbol(RestoreFn);
1265 } else {
1266 // The block has a return.
1267 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1268 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001269 unsigned RetOpc;
1270 if (LongCalls)
1271 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1272 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1273 else
1274 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1275 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1276 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001277 .addExternalSymbol(RestoreFn);
1278 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001279 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001280 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001281 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001282 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001283 }
1284
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001285 for (unsigned i = 0; i < CSI.size(); ++i) {
1286 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001287 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1288 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001289 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001290 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001291
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001292 return true;
1293}
1294
Hans Wennborge1a2e902016-03-31 18:33:38 +00001295MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1296 MachineFunction &MF, MachineBasicBlock &MBB,
1297 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001298 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001299 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001300 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001301 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1302 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001303 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001304}
1305
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001306void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1307 MachineFunction &MF, RegScavenger *RS) const {
1308 // If this function has uses aligned stack and also has variable sized stack
1309 // objects, then we need to map all spill slots to fixed positions, so that
1310 // they can be accessed through FP. Otherwise they would have to be accessed
1311 // via AP, which may not be available at the particular place in the program.
Matthias Braun941a7052016-07-28 18:40:00 +00001312 MachineFrameInfo &MFI = MF.getFrameInfo();
1313 bool HasAlloca = MFI.hasVarSizedObjects();
1314 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001315
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001316 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001317 return;
1318
Matthias Braun941a7052016-07-28 18:40:00 +00001319 unsigned LFS = MFI.getLocalFrameSize();
1320 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1321 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001322 continue;
Matthias Braun941a7052016-07-28 18:40:00 +00001323 unsigned S = MFI.getObjectSize(i);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001324 // Reduce the alignment to at most 8. This will require unaligned vector
1325 // stores if they happen here.
Matthias Braun941a7052016-07-28 18:40:00 +00001326 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1327 MFI.setObjectAlignment(i, 8);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001328 LFS = alignTo(LFS+S, A);
Matthias Braun941a7052016-07-28 18:40:00 +00001329 MFI.mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001330 }
1331
Matthias Braun941a7052016-07-28 18:40:00 +00001332 MFI.setLocalFrameSize(LFS);
1333 unsigned A = MFI.getLocalFrameMaxAlign();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001334 assert(A <= 8 && "Unexpected local frame alignment");
1335 if (A == 0)
Matthias Braun941a7052016-07-28 18:40:00 +00001336 MFI.setLocalFrameMaxAlign(8);
1337 MFI.setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001338
1339 // Set the physical aligned-stack base address register.
1340 unsigned AP = 0;
1341 if (const MachineInstr *AI = getAlignaInstr(MF))
1342 AP = AI->getOperand(0).getReg();
1343 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1344 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001345}
1346
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001347/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001348static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001349 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001350 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001351
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001352 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1353 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1354 if (MRI.isPhysRegUsed(*AI))
1355 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001356 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001357 };
1358
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001359 // Check for an unused caller-saved register. Callee-saved registers
1360 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001361 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001362 if (!IsUsed(*P))
1363 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001364
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001365 // All caller-saved registers are used.
1366 return true;
1367}
1368
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001369#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001370static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001371 dbgs() << '{';
1372 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1373 unsigned R = x;
1374 dbgs() << ' ' << PrintReg(R, &TRI);
1375 }
1376 dbgs() << " }";
1377}
1378#endif
1379
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001380bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1381 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Reid Kleckner40d72302016-10-20 00:22:23 +00001382 DEBUG(dbgs() << __func__ << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001383 << MF.getFunction()->getName() << '\n');
Matthias Braun941a7052016-07-28 18:40:00 +00001384 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001385 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001386
1387 // Generate a set of unique, callee-saved registers (SRegs), where each
1388 // register in the set is maximal in terms of sub-/super-register relation,
1389 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1390
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001391 // (1) For each callee-saved register, add that register and all of its
1392 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001393 DEBUG(dbgs() << "Initial CS registers: {");
1394 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1395 unsigned R = CSI[i].getReg();
1396 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1397 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1398 SRegs[*SR] = true;
1399 }
1400 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001401 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001402
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001403 // (2) For each reserved register, remove that register and all of its
1404 // sub- and super-registers from SRegs.
1405 BitVector Reserved = TRI->getReservedRegs(MF);
1406 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1407 unsigned R = x;
1408 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1409 SRegs[*SR] = false;
1410 }
1411 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1412 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1413
1414 // (3) Collect all registers that have at least one sub-register in SRegs,
1415 // and also have no sub-registers that are reserved. These will be the can-
1416 // didates for saving as a whole instead of their individual sub-registers.
1417 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1418 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001419 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1420 unsigned R = x;
1421 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1422 TmpSup[*SR] = true;
1423 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001424 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1425 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001426 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1427 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001428 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001429 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001430 break;
1431 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001432 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001433 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001434
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001435 // (4) Include all super-registers found in (3) into SRegs.
1436 SRegs |= TmpSup;
1437 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001438
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001439 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001440 // remove R from SRegs.
1441 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1442 unsigned R = x;
1443 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1444 if (!SRegs[*SR])
1445 continue;
1446 SRegs[R] = false;
1447 break;
1448 }
1449 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001450 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001451
1452 // Now, for each register that has a fixed stack slot, create the stack
1453 // object for it.
1454 CSI.clear();
1455
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +00001456 using SpillSlot = TargetFrameLowering::SpillSlot;
1457
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001458 unsigned NumFixed;
1459 int MinOffset = 0; // CS offsets are negative.
1460 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1461 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1462 if (!SRegs[S->Reg])
1463 continue;
1464 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001465 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001466 MinOffset = std::min(MinOffset, S->Offset);
1467 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1468 SRegs[S->Reg] = false;
1469 }
1470
1471 // There can be some registers that don't have fixed slots. For example,
1472 // we need to store R0-R3 in functions with exception handling. For each
1473 // such register, create a non-fixed stack object.
1474 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1475 unsigned R = x;
1476 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001477 unsigned Size = TRI->getSpillSize(*RC);
1478 int Off = MinOffset - Size;
1479 unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001480 assert(isPowerOf2_32(Align));
1481 Off &= -Align;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001482 int FI = MFI.CreateFixedSpillStackObject(Size, Off);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001483 MinOffset = std::min(MinOffset, Off);
1484 CSI.push_back(CalleeSavedInfo(R, FI));
1485 SRegs[R] = false;
1486 }
1487
1488 DEBUG({
1489 dbgs() << "CS information: {";
1490 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1491 int FI = CSI[i].getFrameIdx();
Matthias Braun941a7052016-07-28 18:40:00 +00001492 int Off = MFI.getObjectOffset(FI);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001493 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1494 if (Off >= 0)
1495 dbgs() << '+';
1496 dbgs() << Off;
1497 }
1498 dbgs() << " }\n";
1499 });
1500
1501#ifndef NDEBUG
1502 // Verify that all registers were handled.
1503 bool MissedReg = false;
1504 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1505 unsigned R = x;
1506 dbgs() << PrintReg(R, TRI) << ' ';
1507 MissedReg = true;
1508 }
1509 if (MissedReg)
1510 llvm_unreachable("...there are unhandled callee-saved registers!");
1511#endif
1512
1513 return true;
1514}
1515
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001516bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1517 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1518 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1519 MachineInstr *MI = &*It;
1520 DebugLoc DL = MI->getDebugLoc();
1521 unsigned DstR = MI->getOperand(0).getReg();
1522 unsigned SrcR = MI->getOperand(1).getReg();
1523 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1524 !Hexagon::ModRegsRegClass.contains(SrcR))
1525 return false;
1526
1527 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
Diana Picus116bbab2017-01-13 09:58:52 +00001528 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001529 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1530 .addReg(TmpR, RegState::Kill);
1531
1532 NewRegs.push_back(TmpR);
1533 B.erase(It);
1534 return true;
1535}
1536
1537bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1538 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1539 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1540 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001541 if (!MI->getOperand(0).isFI())
1542 return false;
1543
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001544 DebugLoc DL = MI->getDebugLoc();
1545 unsigned Opc = MI->getOpcode();
1546 unsigned SrcR = MI->getOperand(2).getReg();
1547 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001548 int FI = MI->getOperand(0).getIndex();
1549
1550 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1551 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1552 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1553 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1554 : Hexagon::A2_tfrcrr;
1555 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1556 .addReg(SrcR, getKillRegState(IsKill));
1557
1558 // S2_storeri_io FI, 0, TmpR
1559 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1560 .addFrameIndex(FI)
1561 .addImm(0)
1562 .addReg(TmpR, RegState::Kill)
1563 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1564
1565 NewRegs.push_back(TmpR);
1566 B.erase(It);
1567 return true;
1568}
1569
1570bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1571 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1572 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1573 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001574 if (!MI->getOperand(1).isFI())
1575 return false;
1576
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001577 DebugLoc DL = MI->getDebugLoc();
1578 unsigned Opc = MI->getOpcode();
1579 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001580 int FI = MI->getOperand(1).getIndex();
1581
1582 // TmpR = L2_loadri_io FI, 0
1583 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1584 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1585 .addFrameIndex(FI)
1586 .addImm(0)
1587 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1588
1589 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1590 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1591 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1592 : Hexagon::A2_tfrrcr;
1593 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1594 .addReg(TmpR, RegState::Kill);
1595
1596 NewRegs.push_back(TmpR);
1597 B.erase(It);
1598 return true;
1599}
1600
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001601bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1602 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1603 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001604 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001605 if (!MI->getOperand(0).isFI())
1606 return false;
1607
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001608 DebugLoc DL = MI->getDebugLoc();
1609 unsigned SrcR = MI->getOperand(2).getReg();
1610 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001611 int FI = MI->getOperand(0).getIndex();
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001612 auto *RC = &Hexagon::HvxVRRegClass;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001613
1614 // Insert transfer to general vector register.
1615 // TmpR0 = A2_tfrsi 0x01010101
1616 // TmpR1 = V6_vandqrt Qx, TmpR0
1617 // store FI, 0, TmpR1
1618 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1619 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1620
1621 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1622 .addImm(0x01010101);
1623
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001624 BuildMI(B, It, DL, HII.get(Hexagon::V6_vandqrt), TmpR1)
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001625 .addReg(SrcR, getKillRegState(IsKill))
1626 .addReg(TmpR0, RegState::Kill);
1627
1628 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1629 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1630 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1631
1632 NewRegs.push_back(TmpR0);
1633 NewRegs.push_back(TmpR1);
1634 B.erase(It);
1635 return true;
1636}
1637
1638bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1639 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1640 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001641 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001642 if (!MI->getOperand(1).isFI())
1643 return false;
1644
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001645 DebugLoc DL = MI->getDebugLoc();
1646 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001647 int FI = MI->getOperand(1).getIndex();
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001648 auto *RC = &Hexagon::HvxVRRegClass;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001649
1650 // TmpR0 = A2_tfrsi 0x01010101
1651 // TmpR1 = load FI, 0
1652 // DstR = V6_vandvrt TmpR1, TmpR0
1653 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1654 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1655
1656 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1657 .addImm(0x01010101);
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001658 MachineFunction &MF = *B.getParent();
1659 auto *HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001660 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1661 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1662
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001663 BuildMI(B, It, DL, HII.get(Hexagon::V6_vandvrt), DstR)
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001664 .addReg(TmpR1, RegState::Kill)
1665 .addReg(TmpR0, RegState::Kill);
1666
1667 NewRegs.push_back(TmpR0);
1668 NewRegs.push_back(TmpR1);
1669 B.erase(It);
1670 return true;
1671}
1672
1673bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1674 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1675 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1676 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001677 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001678 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1679 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001680 if (!MI->getOperand(0).isFI())
1681 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001682
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001683 // It is possible that the double vector being stored is only partially
1684 // defined. From the point of view of the liveness tracking, it is ok to
1685 // store it as a whole, but if we break it up we may end up storing a
1686 // register that is entirely undefined.
Matthias Braunac4307c2017-05-26 21:51:00 +00001687 LivePhysRegs LPR(HRI);
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001688 LPR.addLiveIns(B);
1689 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001690 for (auto R = B.begin(); R != It; ++R) {
1691 Clobbers.clear();
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001692 LPR.stepForward(*R, Clobbers);
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001693 // Dead defs are recorded in Clobbers, but are not automatically removed
1694 // from the live set.
1695 for (auto &C : Clobbers)
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +00001696 if (C.second->isReg() && C.second->isDead())
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001697 LPR.removeReg(C.first);
1698 }
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001699
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001700 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001701 unsigned SrcR = MI->getOperand(2).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001702 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1703 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001704 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001705 int FI = MI->getOperand(0).getIndex();
1706
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001707 unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1708 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001709 unsigned HasAlign = MFI.getObjectAlignment(FI);
1710 unsigned StoreOpc;
1711
1712 // Store low part.
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001713 if (LPR.contains(SrcLo)) {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001714 StoreOpc = NeedAlign <= HasAlign ? Hexagon::V6_vS32b_ai
1715 : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001716 BuildMI(B, It, DL, HII.get(StoreOpc))
1717 .addFrameIndex(FI)
1718 .addImm(0)
1719 .addReg(SrcLo, getKillRegState(IsKill))
1720 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1721 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001722
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001723 // Store high part.
1724 if (LPR.contains(SrcHi)) {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001725 StoreOpc = NeedAlign <= MinAlign(HasAlign, Size) ? Hexagon::V6_vS32b_ai
1726 : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001727 BuildMI(B, It, DL, HII.get(StoreOpc))
1728 .addFrameIndex(FI)
1729 .addImm(Size)
1730 .addReg(SrcHi, getKillRegState(IsKill))
1731 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1732 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001733
1734 B.erase(It);
1735 return true;
1736}
1737
1738bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1739 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1740 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1741 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001742 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001743 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1744 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001745 if (!MI->getOperand(1).isFI())
1746 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001747
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001748 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001749 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001750 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1751 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001752 int FI = MI->getOperand(1).getIndex();
1753
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001754 unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1755 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001756 unsigned HasAlign = MFI.getObjectAlignment(FI);
1757 unsigned LoadOpc;
1758
1759 // Load low part.
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001760 LoadOpc = NeedAlign <= HasAlign ? Hexagon::V6_vL32b_ai
1761 : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001762 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1763 .addFrameIndex(FI)
1764 .addImm(0)
1765 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1766
1767 // Load high part.
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001768 LoadOpc = NeedAlign <= MinAlign(HasAlign, Size) ? Hexagon::V6_vL32b_ai
1769 : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001770 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1771 .addFrameIndex(FI)
1772 .addImm(Size)
1773 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1774
1775 B.erase(It);
1776 return true;
1777}
1778
1779bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1780 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1781 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1782 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001783 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001784 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001785 if (!MI->getOperand(0).isFI())
1786 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001787
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001788 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001789 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001790 unsigned SrcR = MI->getOperand(2).getReg();
1791 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001792 int FI = MI->getOperand(0).getIndex();
1793
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001794 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001795 unsigned HasAlign = MFI.getObjectAlignment(FI);
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001796 unsigned StoreOpc = NeedAlign <= HasAlign ? Hexagon::V6_vS32b_ai
1797 : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001798 BuildMI(B, It, DL, HII.get(StoreOpc))
1799 .addFrameIndex(FI)
1800 .addImm(0)
1801 .addReg(SrcR, getKillRegState(IsKill))
1802 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1803
1804 B.erase(It);
1805 return true;
1806}
1807
1808bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1809 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1810 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1811 MachineFunction &MF = *B.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +00001812 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001813 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001814 if (!MI->getOperand(1).isFI())
1815 return false;
1816
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001817 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001818 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001819 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001820 int FI = MI->getOperand(1).getIndex();
1821
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001822 unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001823 unsigned HasAlign = MFI.getObjectAlignment(FI);
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001824 unsigned LoadOpc = NeedAlign <= HasAlign ? Hexagon::V6_vL32b_ai
1825 : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001826 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1827 .addFrameIndex(FI)
1828 .addImm(0)
1829 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1830
1831 B.erase(It);
1832 return true;
1833}
1834
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001835bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1836 SmallVectorImpl<unsigned> &NewRegs) const {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001837 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001838 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001839 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001840
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001841 for (auto &B : MF) {
1842 // Traverse the basic block.
1843 MachineBasicBlock::iterator NextI;
1844 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1845 MachineInstr *MI = &*I;
1846 NextI = std::next(I);
1847 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001848
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001849 switch (Opc) {
1850 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001851 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001852 break;
1853 case Hexagon::STriw_pred:
1854 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001855 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001856 break;
1857 case Hexagon::LDriw_pred:
1858 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001859 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001860 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001861 case Hexagon::PS_vstorerq_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001862 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001863 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001864 case Hexagon::PS_vloadrq_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001865 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001866 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001867 case Hexagon::PS_vloadrw_ai:
1868 case Hexagon::PS_vloadrwu_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001869 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001870 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001871 case Hexagon::PS_vstorerw_ai:
1872 case Hexagon::PS_vstorerwu_ai:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001873 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001874 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001875 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001876 }
1877 }
1878
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001879 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001880}
1881
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001882void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1883 BitVector &SavedRegs,
1884 RegScavenger *RS) const {
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001885 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001886
1887 SavedRegs.resize(HRI.getNumRegs());
1888
1889 // If we have a function containing __builtin_eh_return we want to spill and
1890 // restore all callee saved registers. Pretend that they are used.
1891 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1892 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1893 SavedRegs.set(*R);
1894
1895 // Replace predicate register pseudo spill code.
1896 SmallVector<unsigned,8> NewRegs;
1897 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001898 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001899 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001900
1901 // We need to reserve a a spill slot if scavenging could potentially require
1902 // spilling a scavenged register.
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00001903 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +00001904 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001905 MachineRegisterInfo &MRI = MF.getRegInfo();
1906 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001907 // Reserve an int register in any case, because it could be used to hold
1908 // the stack offset in case it does not fit into a spill instruction.
1909 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1910
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001911 for (unsigned VR : NewRegs)
1912 SpillRCs.insert(MRI.getRegClass(VR));
1913
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001914 for (auto *RC : SpillRCs) {
1915 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1916 continue;
1917 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001918 unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001919 for (unsigned i = 0; i < Num; i++) {
1920 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001921 RS->addScavengingFrameIndex(NewFI);
1922 }
1923 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001924 }
1925
1926 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1927}
1928
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001929unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1930 HexagonBlockRanges::IndexRange &FIR,
1931 HexagonBlockRanges::InstrIndexMap &IndexMap,
1932 HexagonBlockRanges::RegToRangeMap &DeadMap,
1933 const TargetRegisterClass *RC) const {
1934 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1935 auto &MRI = MF.getRegInfo();
1936
1937 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1938 auto F = DeadMap.find({Reg,0});
1939 if (F == DeadMap.end())
1940 return false;
1941 for (auto &DR : F->second)
1942 if (DR.contains(FIR))
1943 return true;
1944 return false;
1945 };
1946
1947 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1948 bool Dead = true;
1949 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1950 if (isDead(R.Reg))
1951 continue;
1952 Dead = false;
1953 break;
1954 }
1955 if (Dead)
1956 return Reg;
1957 }
1958 return 0;
1959}
1960
1961void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1962 SmallVectorImpl<unsigned> &VRegs) const {
1963 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1964 auto &HII = *HST.getInstrInfo();
1965 auto &HRI = *HST.getRegisterInfo();
1966 auto &MRI = MF.getRegInfo();
1967 HexagonBlockRanges HBR(MF);
1968
Eugene Zelenkoe4fc6ee2017-07-26 23:20:35 +00001969 using BlockIndexMap =
1970 std::map<MachineBasicBlock *, HexagonBlockRanges::InstrIndexMap>;
1971 using BlockRangeMap =
1972 std::map<MachineBasicBlock *, HexagonBlockRanges::RangeList>;
1973 using IndexType = HexagonBlockRanges::IndexType;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001974
1975 struct SlotInfo {
1976 BlockRangeMap Map;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001977 unsigned Size = 0;
1978 const TargetRegisterClass *RC = nullptr;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001979
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001980 SlotInfo() = default;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001981 };
1982
1983 BlockIndexMap BlockIndexes;
1984 SmallSet<int,4> BadFIs;
1985 std::map<int,SlotInfo> FIRangeMap;
1986
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001987 // Accumulate register classes: get a common class for a pre-existing
1988 // class HaveRC and a new class NewRC. Return nullptr if a common class
1989 // cannot be found, otherwise return the resulting class. If HaveRC is
1990 // nullptr, assume that it is still unset.
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001991 auto getCommonRC =
1992 [](const TargetRegisterClass *HaveRC,
1993 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001994 if (HaveRC == nullptr || HaveRC == NewRC)
1995 return NewRC;
1996 // Different classes, both non-null. Pick the more general one.
1997 if (HaveRC->hasSubClassEq(NewRC))
1998 return HaveRC;
1999 if (NewRC->hasSubClassEq(HaveRC))
2000 return NewRC;
2001 return nullptr;
2002 };
2003
2004 // Scan all blocks in the function. Check all occurrences of frame indexes,
2005 // and collect relevant information.
2006 for (auto &B : MF) {
2007 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00002008 // Emplace appears not to be supported in gcc 4.7.2-4.
2009 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00002010 auto P = BlockIndexes.insert(
2011 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002012 auto &IndexMap = P.first->second;
2013 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2014 << IndexMap << '\n');
2015
2016 for (auto &In : B) {
2017 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002018 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2019 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002020 if (Load && Store) {
2021 // If it's both a load and a store, then we won't handle it.
2022 BadFIs.insert(LFI);
2023 BadFIs.insert(SFI);
2024 continue;
2025 }
2026 // Check for register classes of the register used as the source for
2027 // the store, and the register used as the destination for the load.
2028 // Also, only accept base+imm_offset addressing modes. Other addressing
2029 // modes can have side-effects (post-increments, etc.). For stack
2030 // slots they are very unlikely, so there is not much loss due to
2031 // this restriction.
2032 if (Load || Store) {
2033 int TFI = Load ? LFI : SFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002034 unsigned AM = HII.getAddrMode(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002035 SlotInfo &SI = FIRangeMap[TFI];
2036 bool Bad = (AM != HexagonII::BaseImmOffset);
2037 if (!Bad) {
2038 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002039 unsigned OpNum = Load ? 0 : 2;
2040 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002041 RC = getCommonRC(SI.RC, RC);
2042 if (RC == nullptr)
2043 Bad = true;
2044 else
2045 SI.RC = RC;
2046 }
2047 if (!Bad) {
2048 // Check sizes.
Krzysztof Parzyszek473d02d2017-09-14 12:06:40 +00002049 unsigned S = HII.getMemAccessSize(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002050 if (SI.Size != 0 && SI.Size != S)
2051 Bad = true;
2052 else
2053 SI.Size = S;
2054 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002055 if (!Bad) {
2056 for (auto *Mo : In.memoperands()) {
2057 if (!Mo->isVolatile())
2058 continue;
2059 Bad = true;
2060 break;
2061 }
2062 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002063 if (Bad)
2064 BadFIs.insert(TFI);
2065 }
2066
2067 // Locate uses of frame indices.
2068 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2069 const MachineOperand &Op = In.getOperand(i);
2070 if (!Op.isFI())
2071 continue;
2072 int FI = Op.getIndex();
2073 // Make sure that the following operand is an immediate and that
2074 // it is 0. This is the offset in the stack object.
2075 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2076 In.getOperand(i+1).getImm() != 0)
2077 BadFIs.insert(FI);
2078 if (BadFIs.count(FI))
2079 continue;
2080
2081 IndexType Index = IndexMap.getIndex(&In);
2082 if (Load) {
2083 if (LastStore[FI] == IndexType::None)
2084 LastStore[FI] = IndexType::Entry;
2085 LastLoad[FI] = Index;
2086 } else if (Store) {
2087 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2088 if (LastStore[FI] != IndexType::None)
2089 RL.add(LastStore[FI], LastLoad[FI], false, false);
2090 else if (LastLoad[FI] != IndexType::None)
2091 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2092 LastLoad[FI] = IndexType::None;
2093 LastStore[FI] = Index;
2094 } else {
2095 BadFIs.insert(FI);
2096 }
2097 }
2098 }
2099
2100 for (auto &I : LastLoad) {
2101 IndexType LL = I.second;
2102 if (LL == IndexType::None)
2103 continue;
2104 auto &RL = FIRangeMap[I.first].Map[&B];
2105 IndexType &LS = LastStore[I.first];
2106 if (LS != IndexType::None)
2107 RL.add(LS, LL, false, false);
2108 else
2109 RL.add(IndexType::Entry, LL, false, false);
2110 LS = IndexType::None;
2111 }
2112 for (auto &I : LastStore) {
2113 IndexType LS = I.second;
2114 if (LS == IndexType::None)
2115 continue;
2116 auto &RL = FIRangeMap[I.first].Map[&B];
2117 RL.add(LS, IndexType::None, false, false);
2118 }
2119 }
2120
2121 DEBUG({
2122 for (auto &P : FIRangeMap) {
2123 dbgs() << "fi#" << P.first;
2124 if (BadFIs.count(P.first))
2125 dbgs() << " (bad)";
2126 dbgs() << " RC: ";
2127 if (P.second.RC != nullptr)
2128 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2129 else
2130 dbgs() << "<null>\n";
2131 for (auto &R : P.second.Map)
2132 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2133 }
2134 });
2135
2136 // When a slot is loaded from in a block without being stored to in the
2137 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2138 // consider this slot to be live-on-exit from all blocks.
2139 SmallSet<int,4> LoxFIs;
2140
2141 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2142
2143 for (auto &P : FIRangeMap) {
2144 // P = pair(FI, map: BB->RangeList)
2145 if (BadFIs.count(P.first))
2146 continue;
2147 for (auto &B : MF) {
2148 auto F = P.second.Map.find(&B);
2149 // F = pair(BB, RangeList)
2150 if (F == P.second.Map.end() || F->second.empty())
2151 continue;
2152 HexagonBlockRanges::IndexRange &IR = F->second.front();
2153 if (IR.start() == IndexType::Entry)
2154 LoxFIs.insert(P.first);
2155 BlockFIMap[&B].push_back(P.first);
2156 }
2157 }
2158
2159 DEBUG({
2160 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2161 for (auto &P : BlockFIMap) {
2162 auto &FIs = P.second;
2163 if (FIs.empty())
2164 continue;
2165 dbgs() << " BB#" << P.first->getNumber() << ": {";
2166 for (auto I : FIs) {
2167 dbgs() << " fi#" << I;
2168 if (LoxFIs.count(I))
2169 dbgs() << '*';
2170 }
2171 dbgs() << " }\n";
2172 }
2173 });
2174
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002175#ifndef NDEBUG
2176 bool HasOptLimit = SpillOptMax.getPosition();
2177#endif
2178
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002179 // eliminate loads, when all loads eliminated, eliminate all stores.
2180 for (auto &B : MF) {
2181 auto F = BlockIndexes.find(&B);
2182 assert(F != BlockIndexes.end());
2183 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2184 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2185 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2186 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2187 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2188
2189 for (auto FI : BlockFIMap[&B]) {
2190 if (BadFIs.count(FI))
2191 continue;
2192 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2193 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2194 for (auto &Range : RL) {
2195 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2196 if (!IndexType::isInstr(Range.start()) ||
2197 !IndexType::isInstr(Range.end()))
2198 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002199 MachineInstr &SI = *IM.getInstr(Range.start());
2200 MachineInstr &EI = *IM.getInstr(Range.end());
2201 assert(SI.mayStore() && "Unexpected start instruction");
2202 assert(EI.mayLoad() && "Unexpected end instruction");
2203 MachineOperand &SrcOp = SI.getOperand(2);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002204
2205 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2206 SrcOp.getSubReg() };
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002207 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002208 // The this-> is needed to unconfuse MSVC.
2209 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2210 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2211 if (FoundR == 0)
2212 continue;
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002213#ifndef NDEBUG
2214 if (HasOptLimit) {
2215 if (SpillOptCount >= SpillOptMax)
2216 return;
2217 SpillOptCount++;
2218 }
2219#endif
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002220
2221 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002222 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002223 MachineInstr *CopyIn = nullptr;
2224 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002225 const DebugLoc &DL = SI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002226 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
Diana Picus116bbab2017-01-13 09:58:52 +00002227 .add(SrcOp);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002228 }
2229
2230 ++StartIt;
2231 // Check if this is a last store and the FI is live-on-exit.
2232 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2233 // Update store's source register.
2234 if (unsigned SR = SrcOp.getSubReg())
2235 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2236 else
2237 SrcOp.setReg(FoundR);
2238 SrcOp.setSubReg(0);
2239 // We are keeping this register live.
2240 SrcOp.setIsKill(false);
2241 } else {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002242 B.erase(&SI);
2243 IM.replaceInstr(&SI, CopyIn);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002244 }
2245
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002246 auto EndIt = std::next(EI.getIterator());
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002247 for (auto It = StartIt; It != EndIt; It = NextIt) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002248 MachineInstr &MI = *It;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002249 NextIt = std::next(It);
2250 int TFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002251 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002252 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002253 unsigned DstR = MI.getOperand(0).getReg();
2254 assert(MI.getOperand(0).getSubReg() == 0);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002255 MachineInstr *CopyOut = nullptr;
2256 if (DstR != FoundR) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002257 DebugLoc DL = MI.getDebugLoc();
Krzysztof Parzyszek473d02d2017-09-14 12:06:40 +00002258 unsigned MemSize = HII.getMemAccessSize(MI);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002259 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2260 unsigned CopyOpc = TargetOpcode::COPY;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002261 if (HII.isSignExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002262 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002263 else if (HII.isZeroExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002264 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2265 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002266 .addReg(FoundR, getKillRegState(&MI == &EI));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002267 }
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002268 IM.replaceInstr(&MI, CopyOut);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002269 B.erase(It);
2270 }
2271
2272 // Update the dead map.
2273 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2274 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2275 DM[RR].subtract(Range);
2276 } // for Range in range list
2277 }
2278 }
2279}
2280
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002281void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002282 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002283 MachineBasicBlock &MB = *AI->getParent();
2284 DebugLoc DL = AI->getDebugLoc();
2285 unsigned A = AI->getOperand(2).getImm();
2286
2287 // Have
2288 // Rd = alloca Rs, #A
2289 //
2290 // If Rs and Rd are different registers, use this sequence:
2291 // Rd = sub(r29, Rs)
2292 // r29 = sub(r29, Rs)
2293 // Rd = and(Rd, #-A) ; if necessary
2294 // r29 = and(r29, #-A) ; if necessary
2295 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2296 // otherwise, do
2297 // Rd = sub(r29, Rs)
2298 // Rd = and(Rd, #-A) ; if necessary
2299 // r29 = Rd
2300 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2301
2302 MachineOperand &RdOp = AI->getOperand(0);
2303 MachineOperand &RsOp = AI->getOperand(1);
2304 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2305
2306 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002307 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002308 .addReg(SP)
2309 .addReg(Rs);
2310 if (Rs != Rd) {
2311 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002312 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002313 .addReg(SP)
2314 .addReg(Rs);
2315 }
2316 if (A > 8) {
2317 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002318 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002319 .addReg(Rd)
2320 .addImm(-int64_t(A));
2321 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002322 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002323 .addReg(SP)
2324 .addImm(-int64_t(A));
2325 }
2326 if (Rs == Rd) {
2327 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002328 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002329 .addReg(Rd);
2330 }
2331 if (CF > 0) {
2332 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002333 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002334 .addReg(Rd)
2335 .addImm(CF);
2336 }
2337}
2338
2339bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +00002340 const MachineFrameInfo &MFI = MF.getFrameInfo();
2341 if (!MFI.hasVarSizedObjects())
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002342 return false;
Krzysztof Parzyszek71702172017-06-23 19:47:04 +00002343 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002344 if (MaxA <= getStackAlignment())
2345 return false;
2346 return true;
2347}
2348
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002349const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2350 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002351 for (auto &B : MF)
2352 for (auto &I : B)
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00002353 if (I.getOpcode() == Hexagon::PS_aligna)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002354 return &I;
2355 return nullptr;
2356}
2357
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002358/// Adds all callee-saved registers as implicit uses or defs to the
2359/// instruction.
2360void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2361 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2362 // Add the callee-saved registers as implicit uses.
2363 for (auto &R : CSI)
2364 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2365}
2366
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002367/// Determine whether the callee-saved register saves and restores should
2368/// be generated via inline code. If this function returns "true", inline
2369/// code will be generated. If this function returns "false", additional
2370/// checks are performed, which may still lead to the inline code.
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002371bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002372 const CSIVect &CSI) const {
2373 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2374 return true;
Krzysztof Parzyszekf67cd822017-07-11 17:11:54 +00002375 if (!hasFP(MF))
2376 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002377 if (!isOptSize(MF) && !isMinSize(MF))
2378 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2379 return true;
2380
2381 // Check if CSI only has double registers, and if the registers form
2382 // a contiguous block starting from D8.
2383 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2384 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2385 unsigned R = CSI[i].getReg();
2386 if (!Hexagon::DoubleRegsRegClass.contains(R))
2387 return true;
2388 Regs[R] = true;
2389 }
2390 int F = Regs.find_first();
2391 if (F != Hexagon::D8)
2392 return true;
2393 while (F >= 0) {
2394 int N = Regs.find_next(F);
2395 if (N >= 0 && N != F+1)
2396 return true;
2397 F = N;
2398 }
2399
2400 return false;
2401}
2402
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002403bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002404 const CSIVect &CSI) const {
2405 if (shouldInlineCSR(MF, CSI))
2406 return false;
2407 unsigned NumCSI = CSI.size();
2408 if (NumCSI <= 1)
2409 return false;
2410
2411 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2412 : SpillFuncThreshold;
2413 return Threshold < NumCSI;
2414}
2415
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002416bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002417 const CSIVect &CSI) const {
2418 if (shouldInlineCSR(MF, CSI))
2419 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002420 // The restore functions do a bit more than just restoring registers.
2421 // The non-returning versions will go back directly to the caller's
2422 // caller, others will clean up the stack frame in preparation for
2423 // a tail call. Using them can still save code size even if only one
2424 // register is getting restores. Make the decision based on -Oz:
2425 // using -Os will use inline restore for a single register.
2426 if (isMinSize(MF))
2427 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002428 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002429 if (NumCSI <= 1)
2430 return false;
2431
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002432 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2433 : SpillFuncThreshold;
2434 return Threshold < NumCSI;
2435}
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002436
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002437bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2438 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2439 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2440 // A fairly simplistic guess as to whether a potential load/store to a
Krzysztof Parzyszek69ffba42017-06-22 14:11:23 +00002441 // stack location could require an extra register.
2442 if (HST.useHVXOps() && StackSize > 256)
2443 return true;
2444
2445 // Check if the function has store-immediate instructions that access
2446 // the stack. Since the offset field is not extendable, if the stack
2447 // size exceeds the offset limit (6 bits, shifted), the stores will
2448 // require a new base register.
2449 bool HasImmStack = false;
2450 unsigned MinLS = ~0u; // Log_2 of the memory access size.
2451
2452 for (const MachineBasicBlock &B : MF) {
2453 for (const MachineInstr &MI : B) {
2454 unsigned LS = 0;
2455 switch (MI.getOpcode()) {
2456 case Hexagon::S4_storeirit_io:
2457 case Hexagon::S4_storeirif_io:
2458 case Hexagon::S4_storeiri_io:
2459 ++LS;
2460 LLVM_FALLTHROUGH;
2461 case Hexagon::S4_storeirht_io:
2462 case Hexagon::S4_storeirhf_io:
2463 case Hexagon::S4_storeirh_io:
2464 ++LS;
2465 LLVM_FALLTHROUGH;
2466 case Hexagon::S4_storeirbt_io:
2467 case Hexagon::S4_storeirbf_io:
2468 case Hexagon::S4_storeirb_io:
2469 if (MI.getOperand(0).isFI())
2470 HasImmStack = true;
2471 MinLS = std::min(MinLS, LS);
2472 break;
2473 }
2474 }
2475 }
2476
2477 if (HasImmStack)
2478 return !isUInt<6>(StackSize >> MinLS);
2479
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002480 return false;
2481}