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