1 //===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
2 //
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 //===----------------------------------------------------------------------===//
10 
11 #define DEBUG_TYPE "hexagon-pei"
12 
13 #include "HexagonBlockRanges.h"
14 #include "HexagonFrameLowering.h"
15 #include "HexagonInstrInfo.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonRegisterInfo.h"
18 #include "HexagonSubtarget.h"
19 #include "HexagonTargetMachine.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/CodeGen/LivePhysRegs.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachinePostDominators.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40 
41 // Hexagon stack frame layout as defined by the ABI:
42 //
43 //                                                       Incoming arguments
44 //                                                       passed via stack
45 //                                                                      |
46 //                                                                      |
47 //        SP during function's                 FP during function's     |
48 //    +-- runtime (top of stack)               runtime (bottom) --+     |
49 //    |                                                           |     |
50 // --++---------------------+------------------+-----------------++-+-------
51 //   |  parameter area for  |  variable-size   |   fixed-size    |LR|  arg
52 //   |   called functions   |  local objects   |  local objects  |FP|
53 // --+----------------------+------------------+-----------------+--+-------
54 //    <-    size known    -> <- size unknown -> <- size known  ->
55 //
56 // Low address                                                 High address
57 //
58 // <--- stack growth
59 //
60 //
61 // - In any circumstances, the outgoing function arguments are always accessi-
62 //   ble using the SP, and the incoming arguments are accessible using the FP.
63 // - If the local objects are not aligned, they can always be accessed using
64 //   the FP.
65 // - If there are no variable-sized objects, the local objects can always be
66 //   accessed using the SP, regardless whether they are aligned or not. (The
67 //   alignment padding will be at the bottom of the stack (highest address),
68 //   and so the offset with respect to the SP will be known at the compile-
69 //   -time.)
70 //
71 // The only complication occurs if there are both, local aligned objects, and
72 // dynamically allocated (variable-sized) objects. The alignment pad will be
73 // placed between the FP and the local objects, thus preventing the use of the
74 // FP to access the local objects. At the same time, the variable-sized objects
75 // will be between the SP and the local objects, thus introducing an unknown
76 // distance from the SP to the locals.
77 //
78 // To avoid this problem, a new register is created that holds the aligned
79 // address of the bottom of the stack, referred in the sources as AP (aligned
80 // pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
81 // that aligns AP to the required boundary (a maximum of the alignments of
82 // all stack objects, fixed- and variable-sized). All local objects[1] will
83 // then use AP as the base pointer.
84 // [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
85 // their name from being allocated at fixed locations on the stack, relative
86 // to the FP. In the presence of dynamic allocation and local alignment, such
87 // objects can only be accessed through the FP.
88 //
89 // Illustration of the AP:
90 //                                                                FP --+
91 //                                                                     |
92 // ---------------+---------------------+-----+-----------------------++-+--
93 //   Rest of the  | Local stack objects | Pad |  Fixed stack objects  |LR|
94 //   stack frame  | (aligned)           |     |  (CSR, spills, etc.)  |FP|
95 // ---------------+---------------------+-----+-----------------+-----+--+--
96 //                                      |<-- Multiple of the -->|
97 //                                           stack alignment    +-- AP
98 //
99 // The AP is set up at the beginning of the function. Since it is not a dedi-
100 // cated (reserved) register, it needs to be kept live throughout the function
101 // to be available as the base register for local object accesses.
102 // Normally, an address of a stack objects is obtained by a pseudo-instruction
103 // PS_fi. To access local objects with the AP register present, a different
104 // pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
105 // argument compared to PS_fi: the first input register is the AP register.
106 // This keeps the register live between its definition and its uses.
107 
108 // The AP register is originally set up using pseudo-instruction PS_aligna:
109 //   AP = PS_aligna A
110 // where
111 //   A  - required stack alignment
112 // The alignment value must be the maximum of all alignments required by
113 // any stack object.
114 
115 // The dynamic allocation uses a pseudo-instruction PS_alloca:
116 //   Rd = PS_alloca Rs, A
117 // where
118 //   Rd - address of the allocated space
119 //   Rs - minimum size (the actual allocated can be larger to accommodate
120 //        alignment)
121 //   A  - required alignment
122 
123 
124 using namespace llvm;
125 
126 static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
127     cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
128 
129 static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
130     cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
131     cl::ZeroOrMore);
132 
133 static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
134     cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
135     cl::init(6), cl::ZeroOrMore);
136 
137 static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
138     cl::Hidden, cl::desc("Specify Os spill func threshold"),
139     cl::init(1), cl::ZeroOrMore);
140 
141 static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
142     cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
143     cl::init(false), cl::ZeroOrMore);
144 
145 static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
146     cl::init(true), cl::Hidden, cl::ZeroOrMore,
147     cl::desc("Enable stack frame shrink wrapping"));
148 
149 static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
150     cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
151     "shrink-wraps"));
152 
153 static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
154     cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
155     cl::init(false), cl::ZeroOrMore);
156 
157 static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
158     cl::Hidden, cl::desc("Use allocframe more conservatively"));
159 
160 static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
161     cl::init(true), cl::desc("Optimize spill slots"));
162 
163 #ifndef NDEBUG
164 static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
165     cl::init(UINT_MAX));
166 static unsigned SpillOptCount = 0;
167 #endif
168 
169 
170 namespace llvm {
171   void initializeHexagonCallFrameInformationPass(PassRegistry&);
172   FunctionPass *createHexagonCallFrameInformation();
173 }
174 
175 namespace {
176   class HexagonCallFrameInformation : public MachineFunctionPass {
177   public:
178     static char ID;
179     HexagonCallFrameInformation() : MachineFunctionPass(ID) {
180       PassRegistry &PR = *PassRegistry::getPassRegistry();
181       initializeHexagonCallFrameInformationPass(PR);
182     }
183     bool runOnMachineFunction(MachineFunction &MF) override;
184     MachineFunctionProperties getRequiredProperties() const override {
185       return MachineFunctionProperties().set(
186           MachineFunctionProperties::Property::NoVRegs);
187     }
188   };
189 
190   char HexagonCallFrameInformation::ID = 0;
191 }
192 
193 bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
194   auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
195   bool NeedCFI = MF.getMMI().hasDebugInfo() ||
196                  MF.getFunction()->needsUnwindTableEntry();
197 
198   if (!NeedCFI)
199     return false;
200   HFI.insertCFIInstructions(MF);
201   return true;
202 }
203 
204 INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
205                 "Hexagon call frame information", false, false)
206 
207 FunctionPass *llvm::createHexagonCallFrameInformation() {
208   return new HexagonCallFrameInformation();
209 }
210 
211 
212 namespace {
213   /// Map a register pair Reg to the subregister that has the greater "number",
214   /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
215   unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
216                                   bool hireg = true) {
217     if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
218       return Reg;
219 
220     unsigned RegNo = 0;
221     for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
222       if (hireg) {
223         if (*SubRegs > RegNo)
224           RegNo = *SubRegs;
225       } else {
226         if (!RegNo || *SubRegs < RegNo)
227           RegNo = *SubRegs;
228       }
229     }
230     return RegNo;
231   }
232 
233   /// Returns the callee saved register with the largest id in the vector.
234   unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
235                                 const TargetRegisterInfo &TRI) {
236     static_assert(Hexagon::R1 > 0,
237                   "Assume physical registers are encoded as positive integers");
238     if (CSI.empty())
239       return 0;
240 
241     unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
242     for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
243       unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
244       if (Reg > Max)
245         Max = Reg;
246     }
247     return Max;
248   }
249 
250   /// Checks if the basic block contains any instruction that needs a stack
251   /// frame to be already in place.
252   bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
253         const HexagonRegisterInfo &HRI) {
254     for (auto &I : MBB) {
255       const MachineInstr *MI = &I;
256       if (MI->isCall())
257         return true;
258       unsigned Opc = MI->getOpcode();
259       switch (Opc) {
260         case Hexagon::PS_alloca:
261         case Hexagon::PS_aligna:
262           return true;
263         default:
264           break;
265       }
266       // Check individual operands.
267       for (const MachineOperand &MO : MI->operands()) {
268         // While the presence of a frame index does not prove that a stack
269         // frame will be required, all frame indexes should be within alloc-
270         // frame/deallocframe. Otherwise, the code that translates a frame
271         // index into an offset would have to be aware of the placement of
272         // the frame creation/destruction instructions.
273         if (MO.isFI())
274           return true;
275         if (!MO.isReg())
276           continue;
277         unsigned R = MO.getReg();
278         // Virtual registers will need scavenging, which then may require
279         // a stack slot.
280         if (TargetRegisterInfo::isVirtualRegister(R))
281           return true;
282         for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
283           if (CSR[*S])
284             return true;
285       }
286     }
287     return false;
288   }
289 
290   /// Returns true if MBB has a machine instructions that indicates a tail call
291   /// in the block.
292   bool hasTailCall(const MachineBasicBlock &MBB) {
293     MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
294     unsigned RetOpc = I->getOpcode();
295     return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
296   }
297 
298   /// Returns true if MBB contains an instruction that returns.
299   bool hasReturn(const MachineBasicBlock &MBB) {
300     for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
301       if (I->isReturn())
302         return true;
303     return false;
304   }
305 
306   /// Returns the "return" instruction from this block, or nullptr if there
307   /// isn't any.
308   MachineInstr *getReturn(MachineBasicBlock &MBB) {
309     for (auto &I : MBB)
310       if (I.isReturn())
311         return &I;
312     return nullptr;
313   }
314 
315   bool isRestoreCall(unsigned Opc) {
316     switch (Opc) {
317       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
318       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
319       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
320       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
321       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
322       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
323       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
324       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
325         return true;
326     }
327     return false;
328   }
329 
330   inline bool isOptNone(const MachineFunction &MF) {
331     return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
332            MF.getTarget().getOptLevel() == CodeGenOpt::None;
333   }
334 
335   inline bool isOptSize(const MachineFunction &MF) {
336     const Function &F = *MF.getFunction();
337     return F.optForSize() && !F.optForMinSize();
338   }
339 
340   inline bool isMinSize(const MachineFunction &MF) {
341     return MF.getFunction()->optForMinSize();
342   }
343 }
344 
345 
346 /// Implements shrink-wrapping of the stack frame. By default, stack frame
347 /// is created in the function entry block, and is cleaned up in every block
348 /// that returns. This function finds alternate blocks: one for the frame
349 /// setup (prolog) and one for the cleanup (epilog).
350 void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
351       MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
352   static unsigned ShrinkCounter = 0;
353 
354   if (ShrinkLimit.getPosition()) {
355     if (ShrinkCounter >= ShrinkLimit)
356       return;
357     ShrinkCounter++;
358   }
359 
360   auto &HST = MF.getSubtarget<HexagonSubtarget>();
361   auto &HRI = *HST.getRegisterInfo();
362 
363   MachineDominatorTree MDT;
364   MDT.runOnMachineFunction(MF);
365   MachinePostDominatorTree MPT;
366   MPT.runOnMachineFunction(MF);
367 
368   typedef DenseMap<unsigned,unsigned> UnsignedMap;
369   UnsignedMap RPO;
370   typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
371   RPOTType RPOT(&MF);
372   unsigned RPON = 0;
373   for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
374     RPO[(*I)->getNumber()] = RPON++;
375 
376   // Don't process functions that have loops, at least for now. Placement
377   // of prolog and epilog must take loop structure into account. For simpli-
378   // city don't do it right now.
379   for (auto &I : MF) {
380     unsigned BN = RPO[I.getNumber()];
381     for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
382       // If found a back-edge, return.
383       if (RPO[(*SI)->getNumber()] <= BN)
384         return;
385     }
386   }
387 
388   // Collect the set of blocks that need a stack frame to execute. Scan
389   // each block for uses/defs of callee-saved registers, calls, etc.
390   SmallVector<MachineBasicBlock*,16> SFBlocks;
391   BitVector CSR(Hexagon::NUM_TARGET_REGS);
392   for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
393     for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
394       CSR[*S] = true;
395 
396   for (auto &I : MF)
397     if (needsStackFrame(I, CSR, HRI))
398       SFBlocks.push_back(&I);
399 
400   DEBUG({
401     dbgs() << "Blocks needing SF: {";
402     for (auto &B : SFBlocks)
403       dbgs() << " BB#" << B->getNumber();
404     dbgs() << " }\n";
405   });
406   // No frame needed?
407   if (SFBlocks.empty())
408     return;
409 
410   // Pick a common dominator and a common post-dominator.
411   MachineBasicBlock *DomB = SFBlocks[0];
412   for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
413     DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
414     if (!DomB)
415       break;
416   }
417   MachineBasicBlock *PDomB = SFBlocks[0];
418   for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
419     PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
420     if (!PDomB)
421       break;
422   }
423   DEBUG({
424     dbgs() << "Computed dom block: BB#";
425     if (DomB) dbgs() << DomB->getNumber();
426     else      dbgs() << "<null>";
427     dbgs() << ", computed pdom block: BB#";
428     if (PDomB) dbgs() << PDomB->getNumber();
429     else       dbgs() << "<null>";
430     dbgs() << "\n";
431   });
432   if (!DomB || !PDomB)
433     return;
434 
435   // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
436   if (!MDT.dominates(DomB, PDomB)) {
437     DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
438     return;
439   }
440   if (!MPT.dominates(PDomB, DomB)) {
441     DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
442     return;
443   }
444 
445   // Finally, everything seems right.
446   PrologB = DomB;
447   EpilogB = PDomB;
448 }
449 
450 
451 /// Perform most of the PEI work here:
452 /// - saving/restoring of the callee-saved registers,
453 /// - stack frame creation and destruction.
454 /// Normally, this work is distributed among various functions, but doing it
455 /// in one place allows shrink-wrapping of the stack frame.
456 void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
457                                         MachineBasicBlock &MBB) const {
458   auto &HST = MF.getSubtarget<HexagonSubtarget>();
459   auto &HRI = *HST.getRegisterInfo();
460 
461   MachineFrameInfo &MFI = MF.getFrameInfo();
462   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
463 
464   MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
465   if (EnableShrinkWrapping)
466     findShrunkPrologEpilog(MF, PrologB, EpilogB);
467 
468   bool PrologueStubs = false;
469   insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
470   insertPrologueInBlock(*PrologB, PrologueStubs);
471   updateEntryPaths(MF, *PrologB);
472 
473   if (EpilogB) {
474     insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
475     insertEpilogueInBlock(*EpilogB);
476   } else {
477     for (auto &B : MF)
478       if (B.isReturnBlock())
479         insertCSRRestoresInBlock(B, CSI, HRI);
480 
481     for (auto &B : MF)
482       if (B.isReturnBlock())
483         insertEpilogueInBlock(B);
484 
485     for (auto &B : MF) {
486       if (B.empty())
487         continue;
488       MachineInstr *RetI = getReturn(B);
489       if (!RetI || isRestoreCall(RetI->getOpcode()))
490         continue;
491       for (auto &R : CSI)
492         RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
493     }
494   }
495 
496   if (EpilogB) {
497     // If there is an epilog block, it may not have a return instruction.
498     // In such case, we need to add the callee-saved registers as live-ins
499     // in all blocks on all paths from the epilog to any return block.
500     unsigned MaxBN = MF.getNumBlockIDs();
501     BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
502     updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
503   }
504 }
505 
506 
507 void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
508       bool PrologueStubs) const {
509   MachineFunction &MF = *MBB.getParent();
510   MachineFrameInfo &MFI = MF.getFrameInfo();
511   auto &HST = MF.getSubtarget<HexagonSubtarget>();
512   auto &HII = *HST.getInstrInfo();
513   auto &HRI = *HST.getRegisterInfo();
514   DebugLoc dl;
515 
516   unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
517 
518   // Calculate the total stack frame size.
519   // Get the number of bytes to allocate from the FrameInfo.
520   unsigned FrameSize = MFI.getStackSize();
521   // Round up the max call frame size to the max alignment on the stack.
522   unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
523   MFI.setMaxCallFrameSize(MaxCFA);
524 
525   FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
526   MFI.setStackSize(FrameSize);
527 
528   bool AlignStack = (MaxAlign > getStackAlignment());
529 
530   // Get the number of bytes to allocate from the FrameInfo.
531   unsigned NumBytes = MFI.getStackSize();
532   unsigned SP = HRI.getStackRegister();
533   unsigned MaxCF = MFI.getMaxCallFrameSize();
534   MachineBasicBlock::iterator InsertPt = MBB.begin();
535 
536   SmallVector<MachineInstr *, 4> AdjustRegs;
537   for (auto &MBB : MF)
538     for (auto &MI : MBB)
539       if (MI.getOpcode() == Hexagon::PS_alloca)
540         AdjustRegs.push_back(&MI);
541 
542   for (auto MI : AdjustRegs) {
543     assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
544     expandAlloca(MI, HII, SP, MaxCF);
545     MI->eraseFromParent();
546   }
547 
548   if (!hasFP(MF))
549     return;
550 
551   // Check for overflow.
552   // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
553   const unsigned int ALLOCFRAME_MAX = 16384;
554 
555   // Create a dummy memory operand to avoid allocframe from being treated as
556   // a volatile memory reference.
557   MachineMemOperand *MMO =
558     MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
559                             4, 4);
560 
561   if (NumBytes >= ALLOCFRAME_MAX) {
562     // Emit allocframe(#0).
563     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
564       .addImm(0)
565       .addMemOperand(MMO);
566 
567     // Subtract offset from frame pointer.
568     // We use a caller-saved non-parameter register for that.
569     unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
570     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32),
571             CallerSavedReg).addImm(NumBytes);
572     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
573       .addReg(SP)
574       .addReg(CallerSavedReg);
575   } else {
576     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
577       .addImm(NumBytes)
578       .addMemOperand(MMO);
579   }
580 
581   if (AlignStack) {
582     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
583         .addReg(SP)
584         .addImm(-int64_t(MaxAlign));
585   }
586 
587   // If the stack-checking is enabled, and we spilled the callee-saved
588   // registers inline (i.e. did not use a spill function), then call
589   // the stack checker directly.
590   if (EnableStackOVFSanitizer && !PrologueStubs)
591     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
592            .addExternalSymbol("__runtime_stack_check");
593 }
594 
595 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
596   MachineFunction &MF = *MBB.getParent();
597   if (!hasFP(MF))
598     return;
599 
600   auto &HST = MF.getSubtarget<HexagonSubtarget>();
601   auto &HII = *HST.getInstrInfo();
602   auto &HRI = *HST.getRegisterInfo();
603   unsigned SP = HRI.getStackRegister();
604 
605   MachineInstr *RetI = getReturn(MBB);
606   unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
607 
608   MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
609   DebugLoc DL;
610   if (InsertPt != MBB.end())
611     DL = InsertPt->getDebugLoc();
612   else if (!MBB.empty())
613     DL = std::prev(MBB.end())->getDebugLoc();
614 
615   // Handle EH_RETURN.
616   if (RetOpc == Hexagon::EH_RETURN_JMPR) {
617     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
618     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
619         .addReg(SP)
620         .addReg(Hexagon::R28);
621     return;
622   }
623 
624   // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
625   // frame instruction if we encounter it.
626   if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
627       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
628       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
629       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
630     MachineBasicBlock::iterator It = RetI;
631     ++It;
632     // Delete all instructions after the RESTORE (except labels).
633     while (It != MBB.end()) {
634       if (!It->isLabel())
635         It = MBB.erase(It);
636       else
637         ++It;
638     }
639     return;
640   }
641 
642   // It is possible that the restoring code is a call to a library function.
643   // All of the restore* functions include "deallocframe", so we need to make
644   // sure that we don't add an extra one.
645   bool NeedsDeallocframe = true;
646   if (!MBB.empty() && InsertPt != MBB.begin()) {
647     MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
648     unsigned COpc = PrevIt->getOpcode();
649     if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
650         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
651         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
652         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
653         COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
654       NeedsDeallocframe = false;
655   }
656 
657   if (!NeedsDeallocframe)
658     return;
659   // If the returning instruction is PS_jmpret, replace it with dealloc_return,
660   // otherwise just add deallocframe. The function could be returning via a
661   // tail call.
662   if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
663     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
664     return;
665   }
666   unsigned NewOpc = Hexagon::L4_return;
667   MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
668   // Transfer the function live-out registers.
669   NewI->copyImplicitOps(MF, *RetI);
670   MBB.erase(RetI);
671 }
672 
673 void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
674       MachineBasicBlock &SaveB) const {
675   SetVector<unsigned> Worklist;
676 
677   MachineBasicBlock &EntryB = MF.front();
678   Worklist.insert(EntryB.getNumber());
679 
680   unsigned SaveN = SaveB.getNumber();
681   auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
682 
683   for (unsigned i = 0; i < Worklist.size(); ++i) {
684     unsigned BN = Worklist[i];
685     MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
686     for (auto &R : CSI)
687       if (!MBB.isLiveIn(R.getReg()))
688         MBB.addLiveIn(R.getReg());
689     if (BN != SaveN)
690       for (auto &SB : MBB.successors())
691         Worklist.insert(SB->getNumber());
692   }
693 }
694 
695 bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
696       MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
697       BitVector &Path) const {
698   assert(MBB.getNumber() >= 0);
699   unsigned BN = MBB.getNumber();
700   if (Path[BN] || DoneF[BN])
701     return false;
702   if (DoneT[BN])
703     return true;
704 
705   auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
706 
707   Path[BN] = true;
708   bool ReachedExit = false;
709   for (auto &SB : MBB.successors())
710     ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
711 
712   if (!MBB.empty() && MBB.back().isReturn()) {
713     // Add implicit uses of all callee-saved registers to the reached
714     // return instructions. This is to prevent the anti-dependency breaker
715     // from renaming these registers.
716     MachineInstr &RetI = MBB.back();
717     if (!isRestoreCall(RetI.getOpcode()))
718       for (auto &R : CSI)
719         RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
720     ReachedExit = true;
721   }
722 
723   // We don't want to add unnecessary live-ins to the restore block: since
724   // the callee-saved registers are being defined in it, the entry of the
725   // restore block cannot be on the path from the definitions to any exit.
726   if (ReachedExit && &MBB != &RestoreB) {
727     for (auto &R : CSI)
728       if (!MBB.isLiveIn(R.getReg()))
729         MBB.addLiveIn(R.getReg());
730     DoneT[BN] = true;
731   }
732   if (!ReachedExit)
733     DoneF[BN] = true;
734 
735   Path[BN] = false;
736   return ReachedExit;
737 }
738 
739 
740 namespace {
741   Optional<MachineBasicBlock::iterator> findCFILocation(MachineBasicBlock &B) {
742     // The CFI instructions need to be inserted right after allocframe.
743     // An exception to this is a situation where allocframe is bundled
744     // with a call: then the CFI instructions need to be inserted before
745     // the packet with the allocframe+call (in case the call throws an
746     // exception).
747     auto End = B.instr_end();
748 
749     for (MachineInstr &I : B) {
750       MachineBasicBlock::iterator It = I.getIterator();
751       if (!I.isBundle()) {
752         if (I.getOpcode() == Hexagon::S2_allocframe)
753           return std::next(It);
754         continue;
755       }
756       // I is a bundle.
757       bool HasCall = false, HasAllocFrame = false;
758       auto T = It.getInstrIterator();
759       while (++T != End && T->isBundled()) {
760         if (T->getOpcode() == Hexagon::S2_allocframe)
761           HasAllocFrame = true;
762         else if (T->isCall())
763           HasCall = true;
764       }
765       if (HasAllocFrame)
766         return HasCall ? It : std::next(It);
767     }
768     return None;
769   }
770 }
771 
772 
773 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
774   for (auto &B : MF) {
775     auto At = findCFILocation(B);
776     if (At.hasValue())
777       insertCFIInstructionsAt(B, At.getValue());
778   }
779 }
780 
781 
782 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
783       MachineBasicBlock::iterator At) const {
784   MachineFunction &MF = *MBB.getParent();
785   MachineFrameInfo &MFI = MF.getFrameInfo();
786   MachineModuleInfo &MMI = MF.getMMI();
787   auto &HST = MF.getSubtarget<HexagonSubtarget>();
788   auto &HII = *HST.getInstrInfo();
789   auto &HRI = *HST.getRegisterInfo();
790 
791   // If CFI instructions have debug information attached, something goes
792   // wrong with the final assembly generation: the prolog_end is placed
793   // in a wrong location.
794   DebugLoc DL;
795   const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
796 
797   MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
798   bool HasFP = hasFP(MF);
799 
800   if (HasFP) {
801     unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
802     unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
803 
804     // Define CFA via an offset from the value of FP.
805     //
806     //  -8   -4    0 (SP)
807     // --+----+----+---------------------
808     //   | FP | LR |          increasing addresses -->
809     // --+----+----+---------------------
810     //   |         +-- Old SP (before allocframe)
811     //   +-- New FP (after allocframe)
812     //
813     // MCCFIInstruction::createDefCfa subtracts the offset from the register.
814     // MCCFIInstruction::createOffset takes the offset without sign change.
815     auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
816     BuildMI(MBB, At, DL, CFID)
817         .addCFIIndex(MF.addFrameInst(DefCfa));
818     // R31 (return addr) = CFA - 4
819     auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
820     BuildMI(MBB, At, DL, CFID)
821         .addCFIIndex(MF.addFrameInst(OffR31));
822     // R30 (frame ptr) = CFA - 8
823     auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
824     BuildMI(MBB, At, DL, CFID)
825         .addCFIIndex(MF.addFrameInst(OffR30));
826   }
827 
828   static unsigned int RegsToMove[] = {
829     Hexagon::R1,  Hexagon::R0,  Hexagon::R3,  Hexagon::R2,
830     Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
831     Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
832     Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
833     Hexagon::D0,  Hexagon::D1,  Hexagon::D8,  Hexagon::D9,
834     Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
835     Hexagon::NoRegister
836   };
837 
838   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
839 
840   for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
841     unsigned Reg = RegsToMove[i];
842     auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
843       return C.getReg() == Reg;
844     };
845     auto F = find_if(CSI, IfR);
846     if (F == CSI.end())
847       continue;
848 
849     int64_t Offset;
850     if (HasFP) {
851       // If the function has a frame pointer (i.e. has an allocframe),
852       // then the CFA has been defined in terms of FP. Any offsets in
853       // the following CFI instructions have to be defined relative
854       // to FP, which points to the bottom of the stack frame.
855       // The function getFrameIndexReference can still choose to use SP
856       // for the offset calculation, so we cannot simply call it here.
857       // Instead, get the offset (relative to the FP) directly.
858       Offset = MFI.getObjectOffset(F->getFrameIdx());
859     } else {
860       unsigned FrameReg;
861       Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
862     }
863     // Subtract 8 to make room for R30 and R31, which are added above.
864     Offset -= 8;
865 
866     if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
867       unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
868       auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
869                                                    Offset);
870       BuildMI(MBB, At, DL, CFID)
871           .addCFIIndex(MF.addFrameInst(OffReg));
872     } else {
873       // Split the double regs into subregs, and generate appropriate
874       // cfi_offsets.
875       // The only reason, we are split double regs is, llvm-mc does not
876       // understand paired registers for cfi_offset.
877       // Eg .cfi_offset r1:0, -64
878 
879       unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
880       unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
881       unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
882       unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
883       auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
884                                                   Offset+4);
885       BuildMI(MBB, At, DL, CFID)
886           .addCFIIndex(MF.addFrameInst(OffHi));
887       auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
888                                                   Offset);
889       BuildMI(MBB, At, DL, CFID)
890           .addCFIIndex(MF.addFrameInst(OffLo));
891     }
892   }
893 }
894 
895 
896 bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
897   auto &MFI = MF.getFrameInfo();
898   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
899 
900   bool HasFixed = MFI.getNumFixedObjects();
901   bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
902                         .getLocalFrameObjectCount();
903   bool HasExtraAlign = HRI.needsStackRealignment(MF);
904   bool HasAlloca = MFI.hasVarSizedObjects();
905 
906   // Insert ALLOCFRAME if we need to or at -O0 for the debugger.  Think
907   // that this shouldn't be required, but doing so now because gcc does and
908   // gdb can't break at the start of the function without it.  Will remove if
909   // this turns out to be a gdb bug.
910   //
911   if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
912     return true;
913 
914   // By default we want to use SP (since it's always there). FP requires
915   // some setup (i.e. ALLOCFRAME).
916   // Fixed and preallocated objects need FP if the distance from them to
917   // the SP is unknown (as is with alloca or aligna).
918   if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
919     return true;
920 
921   if (MFI.getStackSize() > 0) {
922     if (EnableStackOVFSanitizer || UseAllocframe)
923       return true;
924   }
925 
926   if (MFI.hasCalls() ||
927       MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
928     return true;
929 
930   return false;
931 }
932 
933 
934 enum SpillKind {
935   SK_ToMem,
936   SK_FromMem,
937   SK_FromMemTailcall
938 };
939 
940 static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
941       bool Stkchk = false) {
942   const char * V4SpillToMemoryFunctions[] = {
943     "__save_r16_through_r17",
944     "__save_r16_through_r19",
945     "__save_r16_through_r21",
946     "__save_r16_through_r23",
947     "__save_r16_through_r25",
948     "__save_r16_through_r27" };
949 
950   const char * V4SpillToMemoryStkchkFunctions[] = {
951     "__save_r16_through_r17_stkchk",
952     "__save_r16_through_r19_stkchk",
953     "__save_r16_through_r21_stkchk",
954     "__save_r16_through_r23_stkchk",
955     "__save_r16_through_r25_stkchk",
956     "__save_r16_through_r27_stkchk" };
957 
958   const char * V4SpillFromMemoryFunctions[] = {
959     "__restore_r16_through_r17_and_deallocframe",
960     "__restore_r16_through_r19_and_deallocframe",
961     "__restore_r16_through_r21_and_deallocframe",
962     "__restore_r16_through_r23_and_deallocframe",
963     "__restore_r16_through_r25_and_deallocframe",
964     "__restore_r16_through_r27_and_deallocframe" };
965 
966   const char * V4SpillFromMemoryTailcallFunctions[] = {
967     "__restore_r16_through_r17_and_deallocframe_before_tailcall",
968     "__restore_r16_through_r19_and_deallocframe_before_tailcall",
969     "__restore_r16_through_r21_and_deallocframe_before_tailcall",
970     "__restore_r16_through_r23_and_deallocframe_before_tailcall",
971     "__restore_r16_through_r25_and_deallocframe_before_tailcall",
972     "__restore_r16_through_r27_and_deallocframe_before_tailcall"
973   };
974 
975   const char **SpillFunc = nullptr;
976 
977   switch(SpillType) {
978   case SK_ToMem:
979     SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
980                        : V4SpillToMemoryFunctions;
981     break;
982   case SK_FromMem:
983     SpillFunc = V4SpillFromMemoryFunctions;
984     break;
985   case SK_FromMemTailcall:
986     SpillFunc = V4SpillFromMemoryTailcallFunctions;
987     break;
988   }
989   assert(SpillFunc && "Unknown spill kind");
990 
991   // Spill all callee-saved registers up to the highest register used.
992   switch (MaxReg) {
993   case Hexagon::R17:
994     return SpillFunc[0];
995   case Hexagon::R19:
996     return SpillFunc[1];
997   case Hexagon::R21:
998     return SpillFunc[2];
999   case Hexagon::R23:
1000     return SpillFunc[3];
1001   case Hexagon::R25:
1002     return SpillFunc[4];
1003   case Hexagon::R27:
1004     return SpillFunc[5];
1005   default:
1006     llvm_unreachable("Unhandled maximum callee save register");
1007   }
1008   return 0;
1009 }
1010 
1011 
1012 int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
1013       int FI, unsigned &FrameReg) const {
1014   auto &MFI = MF.getFrameInfo();
1015   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1016 
1017   int Offset = MFI.getObjectOffset(FI);
1018   bool HasAlloca = MFI.hasVarSizedObjects();
1019   bool HasExtraAlign = HRI.needsStackRealignment(MF);
1020   bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
1021 
1022   unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
1023   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1024   unsigned AP = HMFI.getStackAlignBasePhysReg();
1025   unsigned FrameSize = MFI.getStackSize();
1026 
1027   bool UseFP = false, UseAP = false;  // Default: use SP (except at -O0).
1028   // Use FP at -O0, except when there are objects with extra alignment.
1029   // That additional alignment requirement may cause a pad to be inserted,
1030   // which will make it impossible to use FP to access objects located
1031   // past the pad.
1032   if (NoOpt && !HasExtraAlign)
1033     UseFP = true;
1034   if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1035     // Fixed and preallocated objects will be located before any padding
1036     // so FP must be used to access them.
1037     UseFP |= (HasAlloca || HasExtraAlign);
1038   } else {
1039     if (HasAlloca) {
1040       if (HasExtraAlign)
1041         UseAP = true;
1042       else
1043         UseFP = true;
1044     }
1045   }
1046 
1047   // If FP was picked, then there had better be FP.
1048   bool HasFP = hasFP(MF);
1049   assert((HasFP || !UseFP) && "This function must have frame pointer");
1050 
1051   // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1052   // FP/LR. If the base register is used to access an object across these
1053   // 8 bytes, then the offset will need to be adjusted by 8.
1054   //
1055   // After allocframe:
1056   //                    HexagonISelLowering adds 8 to ---+
1057   //                    the offsets of all stack-based   |
1058   //                    arguments (*)                    |
1059   //                                                     |
1060   //   getObjectOffset < 0   0     8  getObjectOffset >= 8
1061   // ------------------------+-----+------------------------> increasing
1062   //     <local objects>     |FP/LR|    <input arguments>     addresses
1063   // -----------------+------+-----+------------------------>
1064   //                  |      |
1065   //    SP/AP point --+      +-- FP points here (**)
1066   //    somewhere on
1067   //    this side of FP/LR
1068   //
1069   // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1070   // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1071 
1072   // The lowering assumes that FP/LR is present, and so the offsets of
1073   // the formal arguments start at 8. If FP/LR is not there we need to
1074   // reduce the offset by 8.
1075   if (Offset > 0 && !HasFP)
1076     Offset -= 8;
1077 
1078   if (UseFP)
1079     FrameReg = FP;
1080   else if (UseAP)
1081     FrameReg = AP;
1082   else
1083     FrameReg = SP;
1084 
1085   // Calculate the actual offset in the instruction. If there is no FP
1086   // (in other words, no allocframe), then SP will not be adjusted (i.e.
1087   // there will be no SP -= FrameSize), so the frame size should not be
1088   // added to the calculated offset.
1089   int RealOffset = Offset;
1090   if (!UseFP && !UseAP && HasFP)
1091     RealOffset = FrameSize+Offset;
1092   return RealOffset;
1093 }
1094 
1095 
1096 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
1097       const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1098       bool &PrologueStubs) const {
1099   if (CSI.empty())
1100     return true;
1101 
1102   MachineBasicBlock::iterator MI = MBB.begin();
1103   PrologueStubs = false;
1104   MachineFunction &MF = *MBB.getParent();
1105   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1106   auto &HII = *HST.getInstrInfo();
1107 
1108   if (useSpillFunction(MF, CSI)) {
1109     PrologueStubs = true;
1110     unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1111     bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1112     const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1113                                                StkOvrFlowEnabled);
1114     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1115     bool IsPIC = HTM.isPositionIndependent();
1116     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1117 
1118     // Call spill function.
1119     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1120     unsigned SpillOpc;
1121     if (StkOvrFlowEnabled) {
1122       if (LongCalls)
1123         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1124                          : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1125       else
1126         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1127                          : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1128     } else {
1129       if (LongCalls)
1130         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1131                          : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1132       else
1133         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1134                          : Hexagon::SAVE_REGISTERS_CALL_V4;
1135     }
1136 
1137     MachineInstr *SaveRegsCall =
1138         BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1139           .addExternalSymbol(SpillFun);
1140 
1141     // Add callee-saved registers as use.
1142     addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1143     // Add live in registers.
1144     for (unsigned I = 0; I < CSI.size(); ++I)
1145       MBB.addLiveIn(CSI[I].getReg());
1146     return true;
1147   }
1148 
1149   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1150     unsigned Reg = CSI[i].getReg();
1151     // Add live in registers. We treat eh_return callee saved register r0 - r3
1152     // specially. They are not really callee saved registers as they are not
1153     // supposed to be killed.
1154     bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1155     int FI = CSI[i].getFrameIdx();
1156     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1157     HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
1158     if (IsKill)
1159       MBB.addLiveIn(Reg);
1160   }
1161   return true;
1162 }
1163 
1164 
1165 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1166       const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1167   if (CSI.empty())
1168     return false;
1169 
1170   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1171   MachineFunction &MF = *MBB.getParent();
1172   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1173   auto &HII = *HST.getInstrInfo();
1174 
1175   if (useRestoreFunction(MF, CSI)) {
1176     bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1177     unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1178     SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1179     const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1180     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1181     bool IsPIC = HTM.isPositionIndependent();
1182     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1183 
1184     // Call spill function.
1185     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1186                                   : MBB.getLastNonDebugInstr()->getDebugLoc();
1187     MachineInstr *DeallocCall = nullptr;
1188 
1189     if (HasTC) {
1190       unsigned RetOpc;
1191       if (LongCalls)
1192         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1193                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1194       else
1195         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1196                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1197       DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1198           .addExternalSymbol(RestoreFn);
1199     } else {
1200       // The block has a return.
1201       MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1202       assert(It->isReturn() && std::next(It) == MBB.end());
1203       unsigned RetOpc;
1204       if (LongCalls)
1205         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1206                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1207       else
1208         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1209                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1210       DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
1211           .addExternalSymbol(RestoreFn);
1212       // Transfer the function live-out registers.
1213       DeallocCall->copyImplicitOps(MF, *It);
1214     }
1215     addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1216     return true;
1217   }
1218 
1219   for (unsigned i = 0; i < CSI.size(); ++i) {
1220     unsigned Reg = CSI[i].getReg();
1221     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1222     int FI = CSI[i].getFrameIdx();
1223     HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
1224   }
1225 
1226   return true;
1227 }
1228 
1229 MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1230     MachineFunction &MF, MachineBasicBlock &MBB,
1231     MachineBasicBlock::iterator I) const {
1232   MachineInstr &MI = *I;
1233   unsigned Opc = MI.getOpcode();
1234   (void)Opc; // Silence compiler warning.
1235   assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1236          "Cannot handle this call frame pseudo instruction");
1237   return MBB.erase(I);
1238 }
1239 
1240 
1241 void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1242     MachineFunction &MF, RegScavenger *RS) const {
1243   // If this function has uses aligned stack and also has variable sized stack
1244   // objects, then we need to map all spill slots to fixed positions, so that
1245   // they can be accessed through FP. Otherwise they would have to be accessed
1246   // via AP, which may not be available at the particular place in the program.
1247   MachineFrameInfo &MFI = MF.getFrameInfo();
1248   bool HasAlloca = MFI.hasVarSizedObjects();
1249   bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
1250 
1251   if (!HasAlloca || !NeedsAlign)
1252     return;
1253 
1254   unsigned LFS = MFI.getLocalFrameSize();
1255   for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1256     if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
1257       continue;
1258     unsigned S = MFI.getObjectSize(i);
1259     // Reduce the alignment to at most 8. This will require unaligned vector
1260     // stores if they happen here.
1261     unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1262     MFI.setObjectAlignment(i, 8);
1263     LFS = alignTo(LFS+S, A);
1264     MFI.mapLocalFrameObject(i, -LFS);
1265   }
1266 
1267   MFI.setLocalFrameSize(LFS);
1268   unsigned A = MFI.getLocalFrameMaxAlign();
1269   assert(A <= 8 && "Unexpected local frame alignment");
1270   if (A == 0)
1271     MFI.setLocalFrameMaxAlign(8);
1272   MFI.setUseLocalStackAllocationBlock(true);
1273 
1274   // Set the physical aligned-stack base address register.
1275   unsigned AP = 0;
1276   if (const MachineInstr *AI = getAlignaInstr(MF))
1277     AP = AI->getOperand(0).getReg();
1278   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1279   HMFI.setStackAlignBasePhysReg(AP);
1280 }
1281 
1282 /// Returns true if there are no caller-saved registers available in class RC.
1283 static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1284       const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1285   MachineRegisterInfo &MRI = MF.getRegInfo();
1286 
1287   auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1288     for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1289       if (MRI.isPhysRegUsed(*AI))
1290         return true;
1291     return false;
1292   };
1293 
1294   // Check for an unused caller-saved register. Callee-saved registers
1295   // have become pristine by now.
1296   for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1297     if (!IsUsed(*P))
1298       return false;
1299 
1300   // All caller-saved registers are used.
1301   return true;
1302 }
1303 
1304 
1305 #ifndef NDEBUG
1306 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
1307   dbgs() << '{';
1308   for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1309     unsigned R = x;
1310     dbgs() << ' ' << PrintReg(R, &TRI);
1311   }
1312   dbgs() << " }";
1313 }
1314 #endif
1315 
1316 
1317 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1318       const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1319   DEBUG(dbgs() << __func__ << " on "
1320                << MF.getFunction()->getName() << '\n');
1321   MachineFrameInfo &MFI = MF.getFrameInfo();
1322   BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1323 
1324   // Generate a set of unique, callee-saved registers (SRegs), where each
1325   // register in the set is maximal in terms of sub-/super-register relation,
1326   // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1327 
1328   // (1) For each callee-saved register, add that register and all of its
1329   // sub-registers to SRegs.
1330   DEBUG(dbgs() << "Initial CS registers: {");
1331   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1332     unsigned R = CSI[i].getReg();
1333     DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1334     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1335       SRegs[*SR] = true;
1336   }
1337   DEBUG(dbgs() << " }\n");
1338   DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1339 
1340   // (2) For each reserved register, remove that register and all of its
1341   // sub- and super-registers from SRegs.
1342   BitVector Reserved = TRI->getReservedRegs(MF);
1343   for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1344     unsigned R = x;
1345     for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1346       SRegs[*SR] = false;
1347   }
1348   DEBUG(dbgs() << "Res:     "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1349   DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1350 
1351   // (3) Collect all registers that have at least one sub-register in SRegs,
1352   // and also have no sub-registers that are reserved. These will be the can-
1353   // didates for saving as a whole instead of their individual sub-registers.
1354   // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1355   BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1356   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1357     unsigned R = x;
1358     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1359       TmpSup[*SR] = true;
1360   }
1361   for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1362     unsigned R = x;
1363     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1364       if (!Reserved[*SR])
1365         continue;
1366       TmpSup[R] = false;
1367       break;
1368     }
1369   }
1370   DEBUG(dbgs() << "TmpSup:  "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
1371 
1372   // (4) Include all super-registers found in (3) into SRegs.
1373   SRegs |= TmpSup;
1374   DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1375 
1376   // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1377   // remove R from SRegs.
1378   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1379     unsigned R = x;
1380     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1381       if (!SRegs[*SR])
1382         continue;
1383       SRegs[R] = false;
1384       break;
1385     }
1386   }
1387   DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1388 
1389   // Now, for each register that has a fixed stack slot, create the stack
1390   // object for it.
1391   CSI.clear();
1392 
1393   typedef TargetFrameLowering::SpillSlot SpillSlot;
1394   unsigned NumFixed;
1395   int MinOffset = 0;  // CS offsets are negative.
1396   const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1397   for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1398     if (!SRegs[S->Reg])
1399       continue;
1400     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1401     int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1402     MinOffset = std::min(MinOffset, S->Offset);
1403     CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1404     SRegs[S->Reg] = false;
1405   }
1406 
1407   // There can be some registers that don't have fixed slots. For example,
1408   // we need to store R0-R3 in functions with exception handling. For each
1409   // such register, create a non-fixed stack object.
1410   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1411     unsigned R = x;
1412     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1413     int Off = MinOffset - RC->getSize();
1414     unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1415     assert(isPowerOf2_32(Align));
1416     Off &= -Align;
1417     int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), Off);
1418     MinOffset = std::min(MinOffset, Off);
1419     CSI.push_back(CalleeSavedInfo(R, FI));
1420     SRegs[R] = false;
1421   }
1422 
1423   DEBUG({
1424     dbgs() << "CS information: {";
1425     for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1426       int FI = CSI[i].getFrameIdx();
1427       int Off = MFI.getObjectOffset(FI);
1428       dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1429       if (Off >= 0)
1430         dbgs() << '+';
1431       dbgs() << Off;
1432     }
1433     dbgs() << " }\n";
1434   });
1435 
1436 #ifndef NDEBUG
1437   // Verify that all registers were handled.
1438   bool MissedReg = false;
1439   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1440     unsigned R = x;
1441     dbgs() << PrintReg(R, TRI) << ' ';
1442     MissedReg = true;
1443   }
1444   if (MissedReg)
1445     llvm_unreachable("...there are unhandled callee-saved registers!");
1446 #endif
1447 
1448   return true;
1449 }
1450 
1451 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1452       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1453       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1454   MachineInstr *MI = &*It;
1455   DebugLoc DL = MI->getDebugLoc();
1456   unsigned DstR = MI->getOperand(0).getReg();
1457   unsigned SrcR = MI->getOperand(1).getReg();
1458   if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1459       !Hexagon::ModRegsRegClass.contains(SrcR))
1460     return false;
1461 
1462   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1463   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1464     .addOperand(MI->getOperand(1));
1465   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1466     .addReg(TmpR, RegState::Kill);
1467 
1468   NewRegs.push_back(TmpR);
1469   B.erase(It);
1470   return true;
1471 }
1472 
1473 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1474       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1475       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1476   MachineInstr *MI = &*It;
1477   if (!MI->getOperand(0).isFI())
1478     return false;
1479 
1480   DebugLoc DL = MI->getDebugLoc();
1481   unsigned Opc = MI->getOpcode();
1482   unsigned SrcR = MI->getOperand(2).getReg();
1483   bool IsKill = MI->getOperand(2).isKill();
1484   int FI = MI->getOperand(0).getIndex();
1485 
1486   // TmpR = C2_tfrpr SrcR   if SrcR is a predicate register
1487   // TmpR = A2_tfrcrr SrcR  if SrcR is a modifier register
1488   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1489   unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1490                                                  : Hexagon::A2_tfrcrr;
1491   BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1492     .addReg(SrcR, getKillRegState(IsKill));
1493 
1494   // S2_storeri_io FI, 0, TmpR
1495   BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1496     .addFrameIndex(FI)
1497     .addImm(0)
1498     .addReg(TmpR, RegState::Kill)
1499     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1500 
1501   NewRegs.push_back(TmpR);
1502   B.erase(It);
1503   return true;
1504 }
1505 
1506 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1507       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1508       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1509   MachineInstr *MI = &*It;
1510   if (!MI->getOperand(1).isFI())
1511     return false;
1512 
1513   DebugLoc DL = MI->getDebugLoc();
1514   unsigned Opc = MI->getOpcode();
1515   unsigned DstR = MI->getOperand(0).getReg();
1516   int FI = MI->getOperand(1).getIndex();
1517 
1518   // TmpR = L2_loadri_io FI, 0
1519   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1520   BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1521     .addFrameIndex(FI)
1522     .addImm(0)
1523     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1524 
1525   // DstR = C2_tfrrp TmpR   if DstR is a predicate register
1526   // DstR = A2_tfrrcr TmpR  if DstR is a modifier register
1527   unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1528                                                  : Hexagon::A2_tfrrcr;
1529   BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1530     .addReg(TmpR, RegState::Kill);
1531 
1532   NewRegs.push_back(TmpR);
1533   B.erase(It);
1534   return true;
1535 }
1536 
1537 
1538 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1539       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1540       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1541   auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1542   MachineInstr *MI = &*It;
1543   if (!MI->getOperand(0).isFI())
1544     return false;
1545 
1546   DebugLoc DL = MI->getDebugLoc();
1547   unsigned SrcR = MI->getOperand(2).getReg();
1548   bool IsKill = MI->getOperand(2).isKill();
1549   int FI = MI->getOperand(0).getIndex();
1550 
1551   bool Is128B = HST.useHVXDblOps();
1552   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1553                      : &Hexagon::VectorRegs128BRegClass;
1554 
1555   // Insert transfer to general vector register.
1556   //   TmpR0 = A2_tfrsi 0x01010101
1557   //   TmpR1 = V6_vandqrt Qx, TmpR0
1558   //   store FI, 0, TmpR1
1559   unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1560   unsigned TmpR1 = MRI.createVirtualRegister(RC);
1561 
1562   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1563     .addImm(0x01010101);
1564 
1565   unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1566   BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1567     .addReg(SrcR, getKillRegState(IsKill))
1568     .addReg(TmpR0, RegState::Kill);
1569 
1570   auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1571   HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1572   expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1573 
1574   NewRegs.push_back(TmpR0);
1575   NewRegs.push_back(TmpR1);
1576   B.erase(It);
1577   return true;
1578 }
1579 
1580 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1581       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1582       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1583   auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1584   MachineInstr *MI = &*It;
1585   if (!MI->getOperand(1).isFI())
1586     return false;
1587 
1588   DebugLoc DL = MI->getDebugLoc();
1589   unsigned DstR = MI->getOperand(0).getReg();
1590   int FI = MI->getOperand(1).getIndex();
1591 
1592   bool Is128B = HST.useHVXDblOps();
1593   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1594                      : &Hexagon::VectorRegs128BRegClass;
1595 
1596   // TmpR0 = A2_tfrsi 0x01010101
1597   // TmpR1 = load FI, 0
1598   // DstR = V6_vandvrt TmpR1, TmpR0
1599   unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1600   unsigned TmpR1 = MRI.createVirtualRegister(RC);
1601 
1602   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1603     .addImm(0x01010101);
1604   auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1605   HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1606   expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1607 
1608   unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1609   BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1610     .addReg(TmpR1, RegState::Kill)
1611     .addReg(TmpR0, RegState::Kill);
1612 
1613   NewRegs.push_back(TmpR0);
1614   NewRegs.push_back(TmpR1);
1615   B.erase(It);
1616   return true;
1617 }
1618 
1619 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1620       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1621       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1622   MachineFunction &MF = *B.getParent();
1623   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1624   auto &MFI = MF.getFrameInfo();
1625   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1626   MachineInstr *MI = &*It;
1627   if (!MI->getOperand(0).isFI())
1628     return false;
1629 
1630   // It is possible that the double vector being stored is only partially
1631   // defined. From the point of view of the liveness tracking, it is ok to
1632   // store it as a whole, but if we break it up we may end up storing a
1633   // register that is entirely undefined.
1634   LivePhysRegs LPR(&HRI);
1635   LPR.addLiveIns(B);
1636   SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
1637   for (auto R = B.begin(); R != It; ++R)
1638     LPR.stepForward(*R, Clobbers);
1639 
1640   DebugLoc DL = MI->getDebugLoc();
1641   unsigned SrcR = MI->getOperand(2).getReg();
1642   unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1643   unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
1644   bool IsKill = MI->getOperand(2).isKill();
1645   int FI = MI->getOperand(0).getIndex();
1646 
1647   bool Is128B = HST.useHVXDblOps();
1648   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1649                      : &Hexagon::VectorRegs128BRegClass;
1650   unsigned Size = RC->getSize();
1651   unsigned NeedAlign = RC->getAlignment();
1652   unsigned HasAlign = MFI.getObjectAlignment(FI);
1653   unsigned StoreOpc;
1654 
1655   // Store low part.
1656   if (LPR.contains(SrcLo)) {
1657     if (NeedAlign <= HasAlign)
1658       StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai  : Hexagon::V6_vS32b_ai_128B;
1659     else
1660       StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1661 
1662     BuildMI(B, It, DL, HII.get(StoreOpc))
1663       .addFrameIndex(FI)
1664       .addImm(0)
1665       .addReg(SrcLo, getKillRegState(IsKill))
1666       .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1667   }
1668 
1669   // Store high part.
1670   if (LPR.contains(SrcHi)) {
1671     if (NeedAlign <= MinAlign(HasAlign, Size))
1672       StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai  : Hexagon::V6_vS32b_ai_128B;
1673     else
1674       StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1675 
1676     BuildMI(B, It, DL, HII.get(StoreOpc))
1677       .addFrameIndex(FI)
1678       .addImm(Size)
1679       .addReg(SrcHi, getKillRegState(IsKill))
1680       .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1681   }
1682 
1683   B.erase(It);
1684   return true;
1685 }
1686 
1687 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1688       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1689       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1690   MachineFunction &MF = *B.getParent();
1691   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1692   auto &MFI = MF.getFrameInfo();
1693   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1694   MachineInstr *MI = &*It;
1695   if (!MI->getOperand(1).isFI())
1696     return false;
1697 
1698   DebugLoc DL = MI->getDebugLoc();
1699   unsigned DstR = MI->getOperand(0).getReg();
1700   unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1701   unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
1702   int FI = MI->getOperand(1).getIndex();
1703 
1704   bool Is128B = HST.useHVXDblOps();
1705   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1706                      : &Hexagon::VectorRegs128BRegClass;
1707   unsigned Size = RC->getSize();
1708   unsigned NeedAlign = RC->getAlignment();
1709   unsigned HasAlign = MFI.getObjectAlignment(FI);
1710   unsigned LoadOpc;
1711 
1712   // Load low part.
1713   if (NeedAlign <= HasAlign)
1714     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai  : Hexagon::V6_vL32b_ai_128B;
1715   else
1716     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1717 
1718   BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1719     .addFrameIndex(FI)
1720     .addImm(0)
1721     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1722 
1723   // Load high part.
1724   if (NeedAlign <= MinAlign(HasAlign, Size))
1725     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai  : Hexagon::V6_vL32b_ai_128B;
1726   else
1727     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1728 
1729   BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1730     .addFrameIndex(FI)
1731     .addImm(Size)
1732     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1733 
1734   B.erase(It);
1735   return true;
1736 }
1737 
1738 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1739       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1740       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1741   MachineFunction &MF = *B.getParent();
1742   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1743   auto &MFI = MF.getFrameInfo();
1744   MachineInstr *MI = &*It;
1745   if (!MI->getOperand(0).isFI())
1746     return false;
1747 
1748   DebugLoc DL = MI->getDebugLoc();
1749   unsigned SrcR = MI->getOperand(2).getReg();
1750   bool IsKill = MI->getOperand(2).isKill();
1751   int FI = MI->getOperand(0).getIndex();
1752 
1753   bool Is128B = HST.useHVXDblOps();
1754   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1755                      : &Hexagon::VectorRegs128BRegClass;
1756 
1757   unsigned NeedAlign = RC->getAlignment();
1758   unsigned HasAlign = MFI.getObjectAlignment(FI);
1759   unsigned StoreOpc;
1760 
1761   if (NeedAlign <= HasAlign)
1762     StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1763   else
1764     StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1765 
1766   BuildMI(B, It, DL, HII.get(StoreOpc))
1767     .addFrameIndex(FI)
1768     .addImm(0)
1769     .addReg(SrcR, getKillRegState(IsKill))
1770     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1771 
1772   B.erase(It);
1773   return true;
1774 }
1775 
1776 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1777       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1778       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1779   MachineFunction &MF = *B.getParent();
1780   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1781   auto &MFI = MF.getFrameInfo();
1782   MachineInstr *MI = &*It;
1783   if (!MI->getOperand(1).isFI())
1784     return false;
1785 
1786   DebugLoc DL = MI->getDebugLoc();
1787   unsigned DstR = MI->getOperand(0).getReg();
1788   int FI = MI->getOperand(1).getIndex();
1789 
1790   bool Is128B = HST.useHVXDblOps();
1791   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1792                      : &Hexagon::VectorRegs128BRegClass;
1793 
1794   unsigned NeedAlign = RC->getAlignment();
1795   unsigned HasAlign = MFI.getObjectAlignment(FI);
1796   unsigned LoadOpc;
1797 
1798   if (NeedAlign <= HasAlign)
1799     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1800   else
1801     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1802 
1803   BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1804     .addFrameIndex(FI)
1805     .addImm(0)
1806     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1807 
1808   B.erase(It);
1809   return true;
1810 }
1811 
1812 
1813 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1814       SmallVectorImpl<unsigned> &NewRegs) const {
1815   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1816   auto &HII = *HST.getInstrInfo();
1817   MachineRegisterInfo &MRI = MF.getRegInfo();
1818   bool Changed = false;
1819 
1820   for (auto &B : MF) {
1821     // Traverse the basic block.
1822     MachineBasicBlock::iterator NextI;
1823     for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1824       MachineInstr *MI = &*I;
1825       NextI = std::next(I);
1826       unsigned Opc = MI->getOpcode();
1827 
1828       switch (Opc) {
1829         case TargetOpcode::COPY:
1830           Changed |= expandCopy(B, I, MRI, HII, NewRegs);
1831           break;
1832         case Hexagon::STriw_pred:
1833         case Hexagon::STriw_mod:
1834           Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
1835           break;
1836         case Hexagon::LDriw_pred:
1837         case Hexagon::LDriw_mod:
1838           Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
1839           break;
1840         case Hexagon::PS_vstorerq_ai:
1841         case Hexagon::PS_vstorerq_ai_128B:
1842           Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
1843           break;
1844         case Hexagon::PS_vloadrq_ai:
1845         case Hexagon::PS_vloadrq_ai_128B:
1846           Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
1847           break;
1848         case Hexagon::PS_vloadrw_ai:
1849         case Hexagon::PS_vloadrwu_ai:
1850         case Hexagon::PS_vloadrw_ai_128B:
1851         case Hexagon::PS_vloadrwu_ai_128B:
1852           Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
1853           break;
1854         case Hexagon::PS_vstorerw_ai:
1855         case Hexagon::PS_vstorerwu_ai:
1856         case Hexagon::PS_vstorerw_ai_128B:
1857         case Hexagon::PS_vstorerwu_ai_128B:
1858           Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
1859           break;
1860       }
1861     }
1862   }
1863 
1864   return Changed;
1865 }
1866 
1867 
1868 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1869                                                 BitVector &SavedRegs,
1870                                                 RegScavenger *RS) const {
1871   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1872   auto &HRI = *HST.getRegisterInfo();
1873 
1874   SavedRegs.resize(HRI.getNumRegs());
1875 
1876   // If we have a function containing __builtin_eh_return we want to spill and
1877   // restore all callee saved registers. Pretend that they are used.
1878   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1879     for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1880       SavedRegs.set(*R);
1881 
1882   // Replace predicate register pseudo spill code.
1883   SmallVector<unsigned,8> NewRegs;
1884   expandSpillMacros(MF, NewRegs);
1885   if (OptimizeSpillSlots && !isOptNone(MF))
1886     optimizeSpillSlots(MF, NewRegs);
1887 
1888   // We need to reserve a a spill slot if scavenging could potentially require
1889   // spilling a scavenged register.
1890   if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
1891     MachineFrameInfo &MFI = MF.getFrameInfo();
1892     MachineRegisterInfo &MRI = MF.getRegInfo();
1893     SetVector<const TargetRegisterClass*> SpillRCs;
1894     // Reserve an int register in any case, because it could be used to hold
1895     // the stack offset in case it does not fit into a spill instruction.
1896     SpillRCs.insert(&Hexagon::IntRegsRegClass);
1897 
1898     for (unsigned VR : NewRegs)
1899       SpillRCs.insert(MRI.getRegClass(VR));
1900 
1901     for (auto *RC : SpillRCs) {
1902       if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1903         continue;
1904       unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1905       unsigned S = RC->getSize(), A = RC->getAlignment();
1906       for (unsigned i = 0; i < Num; i++) {
1907         int NewFI = MFI.CreateSpillStackObject(S, A);
1908         RS->addScavengingFrameIndex(NewFI);
1909       }
1910     }
1911   }
1912 
1913   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1914 }
1915 
1916 
1917 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1918       HexagonBlockRanges::IndexRange &FIR,
1919       HexagonBlockRanges::InstrIndexMap &IndexMap,
1920       HexagonBlockRanges::RegToRangeMap &DeadMap,
1921       const TargetRegisterClass *RC) const {
1922   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1923   auto &MRI = MF.getRegInfo();
1924 
1925   auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1926     auto F = DeadMap.find({Reg,0});
1927     if (F == DeadMap.end())
1928       return false;
1929     for (auto &DR : F->second)
1930       if (DR.contains(FIR))
1931         return true;
1932     return false;
1933   };
1934 
1935   for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1936     bool Dead = true;
1937     for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1938       if (isDead(R.Reg))
1939         continue;
1940       Dead = false;
1941       break;
1942     }
1943     if (Dead)
1944       return Reg;
1945   }
1946   return 0;
1947 }
1948 
1949 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1950       SmallVectorImpl<unsigned> &VRegs) const {
1951   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1952   auto &HII = *HST.getInstrInfo();
1953   auto &HRI = *HST.getRegisterInfo();
1954   auto &MRI = MF.getRegInfo();
1955   HexagonBlockRanges HBR(MF);
1956 
1957   typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1958       BlockIndexMap;
1959   typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1960       BlockRangeMap;
1961   typedef HexagonBlockRanges::IndexType IndexType;
1962 
1963   struct SlotInfo {
1964     BlockRangeMap Map;
1965     unsigned Size;
1966     const TargetRegisterClass *RC;
1967 
1968     SlotInfo() : Map(), Size(0), RC(nullptr) {}
1969   };
1970 
1971   BlockIndexMap BlockIndexes;
1972   SmallSet<int,4> BadFIs;
1973   std::map<int,SlotInfo> FIRangeMap;
1974 
1975   // Accumulate register classes: get a common class for a pre-existing
1976   // class HaveRC and a new class NewRC. Return nullptr if a common class
1977   // cannot be found, otherwise return the resulting class. If HaveRC is
1978   // nullptr, assume that it is still unset.
1979   auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1980                              const TargetRegisterClass *NewRC)
1981         -> const TargetRegisterClass* {
1982     if (HaveRC == nullptr || HaveRC == NewRC)
1983       return NewRC;
1984     // Different classes, both non-null. Pick the more general one.
1985     if (HaveRC->hasSubClassEq(NewRC))
1986       return HaveRC;
1987     if (NewRC->hasSubClassEq(HaveRC))
1988       return NewRC;
1989     return nullptr;
1990   };
1991 
1992   // Scan all blocks in the function. Check all occurrences of frame indexes,
1993   // and collect relevant information.
1994   for (auto &B : MF) {
1995     std::map<int,IndexType> LastStore, LastLoad;
1996     // Emplace appears not to be supported in gcc 4.7.2-4.
1997     //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
1998     auto P = BlockIndexes.insert(
1999                 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
2000     auto &IndexMap = P.first->second;
2001     DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2002                  << IndexMap << '\n');
2003 
2004     for (auto &In : B) {
2005       int LFI, SFI;
2006       bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2007       bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2008       if (Load && Store) {
2009         // If it's both a load and a store, then we won't handle it.
2010         BadFIs.insert(LFI);
2011         BadFIs.insert(SFI);
2012         continue;
2013       }
2014       // Check for register classes of the register used as the source for
2015       // the store, and the register used as the destination for the load.
2016       // Also, only accept base+imm_offset addressing modes. Other addressing
2017       // modes can have side-effects (post-increments, etc.). For stack
2018       // slots they are very unlikely, so there is not much loss due to
2019       // this restriction.
2020       if (Load || Store) {
2021         int TFI = Load ? LFI : SFI;
2022         unsigned AM = HII.getAddrMode(In);
2023         SlotInfo &SI = FIRangeMap[TFI];
2024         bool Bad = (AM != HexagonII::BaseImmOffset);
2025         if (!Bad) {
2026           // If the addressing mode is ok, check the register class.
2027           unsigned OpNum = Load ? 0 : 2;
2028           auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
2029           RC = getCommonRC(SI.RC, RC);
2030           if (RC == nullptr)
2031             Bad = true;
2032           else
2033             SI.RC = RC;
2034         }
2035         if (!Bad) {
2036           // Check sizes.
2037           unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
2038           if (SI.Size != 0 && SI.Size != S)
2039             Bad = true;
2040           else
2041             SI.Size = S;
2042         }
2043         if (!Bad) {
2044           for (auto *Mo : In.memoperands()) {
2045             if (!Mo->isVolatile())
2046               continue;
2047             Bad = true;
2048             break;
2049           }
2050         }
2051         if (Bad)
2052           BadFIs.insert(TFI);
2053       }
2054 
2055       // Locate uses of frame indices.
2056       for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2057         const MachineOperand &Op = In.getOperand(i);
2058         if (!Op.isFI())
2059           continue;
2060         int FI = Op.getIndex();
2061         // Make sure that the following operand is an immediate and that
2062         // it is 0. This is the offset in the stack object.
2063         if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2064             In.getOperand(i+1).getImm() != 0)
2065           BadFIs.insert(FI);
2066         if (BadFIs.count(FI))
2067           continue;
2068 
2069         IndexType Index = IndexMap.getIndex(&In);
2070         if (Load) {
2071           if (LastStore[FI] == IndexType::None)
2072             LastStore[FI] = IndexType::Entry;
2073           LastLoad[FI] = Index;
2074         } else if (Store) {
2075           HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2076           if (LastStore[FI] != IndexType::None)
2077             RL.add(LastStore[FI], LastLoad[FI], false, false);
2078           else if (LastLoad[FI] != IndexType::None)
2079             RL.add(IndexType::Entry, LastLoad[FI], false, false);
2080           LastLoad[FI] = IndexType::None;
2081           LastStore[FI] = Index;
2082         } else {
2083           BadFIs.insert(FI);
2084         }
2085       }
2086     }
2087 
2088     for (auto &I : LastLoad) {
2089       IndexType LL = I.second;
2090       if (LL == IndexType::None)
2091         continue;
2092       auto &RL = FIRangeMap[I.first].Map[&B];
2093       IndexType &LS = LastStore[I.first];
2094       if (LS != IndexType::None)
2095         RL.add(LS, LL, false, false);
2096       else
2097         RL.add(IndexType::Entry, LL, false, false);
2098       LS = IndexType::None;
2099     }
2100     for (auto &I : LastStore) {
2101       IndexType LS = I.second;
2102       if (LS == IndexType::None)
2103         continue;
2104       auto &RL = FIRangeMap[I.first].Map[&B];
2105       RL.add(LS, IndexType::None, false, false);
2106     }
2107   }
2108 
2109   DEBUG({
2110     for (auto &P : FIRangeMap) {
2111       dbgs() << "fi#" << P.first;
2112       if (BadFIs.count(P.first))
2113         dbgs() << " (bad)";
2114       dbgs() << "  RC: ";
2115       if (P.second.RC != nullptr)
2116         dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2117       else
2118         dbgs() << "<null>\n";
2119       for (auto &R : P.second.Map)
2120         dbgs() << "  BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2121     }
2122   });
2123 
2124   // When a slot is loaded from in a block without being stored to in the
2125   // same block, it is live-on-entry to this block. To avoid CFG analysis,
2126   // consider this slot to be live-on-exit from all blocks.
2127   SmallSet<int,4> LoxFIs;
2128 
2129   std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2130 
2131   for (auto &P : FIRangeMap) {
2132     // P = pair(FI, map: BB->RangeList)
2133     if (BadFIs.count(P.first))
2134       continue;
2135     for (auto &B : MF) {
2136       auto F = P.second.Map.find(&B);
2137       // F = pair(BB, RangeList)
2138       if (F == P.second.Map.end() || F->second.empty())
2139         continue;
2140       HexagonBlockRanges::IndexRange &IR = F->second.front();
2141       if (IR.start() == IndexType::Entry)
2142         LoxFIs.insert(P.first);
2143       BlockFIMap[&B].push_back(P.first);
2144     }
2145   }
2146 
2147   DEBUG({
2148     dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2149     for (auto &P : BlockFIMap) {
2150       auto &FIs = P.second;
2151       if (FIs.empty())
2152         continue;
2153       dbgs() << "  BB#" << P.first->getNumber() << ": {";
2154       for (auto I : FIs) {
2155         dbgs() << " fi#" << I;
2156         if (LoxFIs.count(I))
2157           dbgs() << '*';
2158       }
2159       dbgs() << " }\n";
2160     }
2161   });
2162 
2163 #ifndef NDEBUG
2164   bool HasOptLimit = SpillOptMax.getPosition();
2165 #endif
2166 
2167   // eliminate loads, when all loads eliminated, eliminate all stores.
2168   for (auto &B : MF) {
2169     auto F = BlockIndexes.find(&B);
2170     assert(F != BlockIndexes.end());
2171     HexagonBlockRanges::InstrIndexMap &IM = F->second;
2172     HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2173     HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2174     DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2175                  << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2176 
2177     for (auto FI : BlockFIMap[&B]) {
2178       if (BadFIs.count(FI))
2179         continue;
2180       DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2181       HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2182       for (auto &Range : RL) {
2183         DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2184         if (!IndexType::isInstr(Range.start()) ||
2185             !IndexType::isInstr(Range.end()))
2186           continue;
2187         MachineInstr &SI = *IM.getInstr(Range.start());
2188         MachineInstr &EI = *IM.getInstr(Range.end());
2189         assert(SI.mayStore() && "Unexpected start instruction");
2190         assert(EI.mayLoad() && "Unexpected end instruction");
2191         MachineOperand &SrcOp = SI.getOperand(2);
2192 
2193         HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2194                                                   SrcOp.getSubReg() };
2195         auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
2196         // The this-> is needed to unconfuse MSVC.
2197         unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2198         DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2199         if (FoundR == 0)
2200           continue;
2201 #ifndef NDEBUG
2202         if (HasOptLimit) {
2203           if (SpillOptCount >= SpillOptMax)
2204             return;
2205           SpillOptCount++;
2206         }
2207 #endif
2208 
2209         // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2210         MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
2211         MachineInstr *CopyIn = nullptr;
2212         if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2213           const DebugLoc &DL = SI.getDebugLoc();
2214           CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2215                       .addOperand(SrcOp);
2216         }
2217 
2218         ++StartIt;
2219         // Check if this is a last store and the FI is live-on-exit.
2220         if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2221           // Update store's source register.
2222           if (unsigned SR = SrcOp.getSubReg())
2223             SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2224           else
2225             SrcOp.setReg(FoundR);
2226           SrcOp.setSubReg(0);
2227           // We are keeping this register live.
2228           SrcOp.setIsKill(false);
2229         } else {
2230           B.erase(&SI);
2231           IM.replaceInstr(&SI, CopyIn);
2232         }
2233 
2234         auto EndIt = std::next(EI.getIterator());
2235         for (auto It = StartIt; It != EndIt; It = NextIt) {
2236           MachineInstr &MI = *It;
2237           NextIt = std::next(It);
2238           int TFI;
2239           if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2240             continue;
2241           unsigned DstR = MI.getOperand(0).getReg();
2242           assert(MI.getOperand(0).getSubReg() == 0);
2243           MachineInstr *CopyOut = nullptr;
2244           if (DstR != FoundR) {
2245             DebugLoc DL = MI.getDebugLoc();
2246             unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2247             assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2248             unsigned CopyOpc = TargetOpcode::COPY;
2249             if (HII.isSignExtendingLoad(MI))
2250               CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2251             else if (HII.isZeroExtendingLoad(MI))
2252               CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2253             CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2254                         .addReg(FoundR, getKillRegState(&MI == &EI));
2255           }
2256           IM.replaceInstr(&MI, CopyOut);
2257           B.erase(It);
2258         }
2259 
2260         // Update the dead map.
2261         HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2262         for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2263           DM[RR].subtract(Range);
2264       } // for Range in range list
2265     }
2266   }
2267 }
2268 
2269 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
2270       const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
2271   MachineBasicBlock &MB = *AI->getParent();
2272   DebugLoc DL = AI->getDebugLoc();
2273   unsigned A = AI->getOperand(2).getImm();
2274 
2275   // Have
2276   //    Rd  = alloca Rs, #A
2277   //
2278   // If Rs and Rd are different registers, use this sequence:
2279   //    Rd  = sub(r29, Rs)
2280   //    r29 = sub(r29, Rs)
2281   //    Rd  = and(Rd, #-A)    ; if necessary
2282   //    r29 = and(r29, #-A)   ; if necessary
2283   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2284   // otherwise, do
2285   //    Rd  = sub(r29, Rs)
2286   //    Rd  = and(Rd, #-A)    ; if necessary
2287   //    r29 = Rd
2288   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2289 
2290   MachineOperand &RdOp = AI->getOperand(0);
2291   MachineOperand &RsOp = AI->getOperand(1);
2292   unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2293 
2294   // Rd = sub(r29, Rs)
2295   BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
2296       .addReg(SP)
2297       .addReg(Rs);
2298   if (Rs != Rd) {
2299     // r29 = sub(r29, Rs)
2300     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
2301         .addReg(SP)
2302         .addReg(Rs);
2303   }
2304   if (A > 8) {
2305     // Rd  = and(Rd, #-A)
2306     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
2307         .addReg(Rd)
2308         .addImm(-int64_t(A));
2309     if (Rs != Rd)
2310       BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
2311           .addReg(SP)
2312           .addImm(-int64_t(A));
2313   }
2314   if (Rs == Rd) {
2315     // r29 = Rd
2316     BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
2317         .addReg(Rd);
2318   }
2319   if (CF > 0) {
2320     // Rd = add(Rd, #CF)
2321     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
2322         .addReg(Rd)
2323         .addImm(CF);
2324   }
2325 }
2326 
2327 
2328 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2329   const MachineFrameInfo &MFI = MF.getFrameInfo();
2330   if (!MFI.hasVarSizedObjects())
2331     return false;
2332   unsigned MaxA = MFI.getMaxAlignment();
2333   if (MaxA <= getStackAlignment())
2334     return false;
2335   return true;
2336 }
2337 
2338 
2339 const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2340       const MachineFunction &MF) const {
2341   for (auto &B : MF)
2342     for (auto &I : B)
2343       if (I.getOpcode() == Hexagon::PS_aligna)
2344         return &I;
2345   return nullptr;
2346 }
2347 
2348 
2349 /// Adds all callee-saved registers as implicit uses or defs to the
2350 /// instruction.
2351 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2352       const CSIVect &CSI, bool IsDef, bool IsKill) const {
2353   // Add the callee-saved registers as implicit uses.
2354   for (auto &R : CSI)
2355     MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2356 }
2357 
2358 
2359 /// Determine whether the callee-saved register saves and restores should
2360 /// be generated via inline code. If this function returns "true", inline
2361 /// code will be generated. If this function returns "false", additional
2362 /// checks are performed, which may still lead to the inline code.
2363 bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2364       const CSIVect &CSI) const {
2365   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2366     return true;
2367   if (!isOptSize(MF) && !isMinSize(MF))
2368     if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2369       return true;
2370 
2371   // Check if CSI only has double registers, and if the registers form
2372   // a contiguous block starting from D8.
2373   BitVector Regs(Hexagon::NUM_TARGET_REGS);
2374   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2375     unsigned R = CSI[i].getReg();
2376     if (!Hexagon::DoubleRegsRegClass.contains(R))
2377       return true;
2378     Regs[R] = true;
2379   }
2380   int F = Regs.find_first();
2381   if (F != Hexagon::D8)
2382     return true;
2383   while (F >= 0) {
2384     int N = Regs.find_next(F);
2385     if (N >= 0 && N != F+1)
2386       return true;
2387     F = N;
2388   }
2389 
2390   return false;
2391 }
2392 
2393 
2394 bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2395       const CSIVect &CSI) const {
2396   if (shouldInlineCSR(MF, CSI))
2397     return false;
2398   unsigned NumCSI = CSI.size();
2399   if (NumCSI <= 1)
2400     return false;
2401 
2402   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2403                                      : SpillFuncThreshold;
2404   return Threshold < NumCSI;
2405 }
2406 
2407 
2408 bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2409       const CSIVect &CSI) const {
2410   if (shouldInlineCSR(MF, CSI))
2411     return false;
2412   // The restore functions do a bit more than just restoring registers.
2413   // The non-returning versions will go back directly to the caller's
2414   // caller, others will clean up the stack frame in preparation for
2415   // a tail call. Using them can still save code size even if only one
2416   // register is getting restores. Make the decision based on -Oz:
2417   // using -Os will use inline restore for a single register.
2418   if (isMinSize(MF))
2419     return true;
2420   unsigned NumCSI = CSI.size();
2421   if (NumCSI <= 1)
2422     return false;
2423 
2424   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2425                                      : SpillFuncThreshold;
2426   return Threshold < NumCSI;
2427 }
2428 
2429 
2430 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2431   unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2432   auto &HST = MF.getSubtarget<HexagonSubtarget>();
2433   // A fairly simplistic guess as to whether a potential load/store to a
2434   // stack location could require an extra register. It does not account
2435   // for store-immediate instructions.
2436   if (HST.useHVXOps())
2437     return StackSize > 256;
2438   return false;
2439 }
2440 
2441