Fixed/added namespace ending comments using clang-tidy. NFC
[oota-llvm.git] / lib / Target / Hexagon / HexagonVLIWPacketizer.cpp
1 //===----- HexagonPacketizer.cpp - vliw packetizer ---------------------===//
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 // This implements a simple VLIW packetizer using DFA. The packetizer works on
11 // machine basic blocks. For each instruction I in BB, the packetizer consults
12 // the DFA to see if machine resources are available to execute I. If so, the
13 // packetizer checks if I depends on any instruction J in the current packet.
14 // If no dependency is found, I is added to current packet and machine resource
15 // is marked as taken. If any dependency is found, a target API call is made to
16 // prune the dependence.
17 //
18 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/DFAPacketizer.h"
20 #include "Hexagon.h"
21 #include "HexagonMachineFunctionInfo.h"
22 #include "HexagonRegisterInfo.h"
23 #include "HexagonSubtarget.h"
24 #include "HexagonTargetMachine.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/CodeGen/LatencyPriorityQueue.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/ScheduleDAG.h"
37 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
38 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
39 #include "llvm/CodeGen/SchedulerRegistry.h"
40 #include "llvm/MC/MCInstrItineraries.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
48 #include <map>
49 #include <vector>
50
51 using namespace llvm;
52
53 #define DEBUG_TYPE "packets"
54
55 static cl::opt<bool> PacketizeVolatiles("hexagon-packetize-volatiles",
56       cl::ZeroOrMore, cl::Hidden, cl::init(true),
57       cl::desc("Allow non-solo packetization of volatile memory references"));
58
59 namespace llvm {
60   FunctionPass *createHexagonPacketizer();
61   void initializeHexagonPacketizerPass(PassRegistry&);
62 }
63
64
65 namespace {
66   class HexagonPacketizer : public MachineFunctionPass {
67
68   public:
69     static char ID;
70     HexagonPacketizer() : MachineFunctionPass(ID) {
71       initializeHexagonPacketizerPass(*PassRegistry::getPassRegistry());
72     }
73
74     void getAnalysisUsage(AnalysisUsage &AU) const override {
75       AU.setPreservesCFG();
76       AU.addRequired<MachineDominatorTree>();
77       AU.addRequired<MachineBranchProbabilityInfo>();
78       AU.addPreserved<MachineDominatorTree>();
79       AU.addRequired<MachineLoopInfo>();
80       AU.addPreserved<MachineLoopInfo>();
81       MachineFunctionPass::getAnalysisUsage(AU);
82     }
83
84     const char *getPassName() const override {
85       return "Hexagon Packetizer";
86     }
87
88     bool runOnMachineFunction(MachineFunction &Fn) override;
89   };
90   char HexagonPacketizer::ID = 0;
91
92   class HexagonPacketizerList : public VLIWPacketizerList {
93
94   private:
95
96     // Has the instruction been promoted to a dot-new instruction.
97     bool PromotedToDotNew;
98
99     // Has the instruction been glued to allocframe.
100     bool GlueAllocframeStore;
101
102     // Has the feeder instruction been glued to new value jump.
103     bool GlueToNewValueJump;
104
105     // Check if there is a dependence between some instruction already in this
106     // packet and this instruction.
107     bool Dependence;
108
109     // Only check for dependence if there are resources available to
110     // schedule this instruction.
111     bool FoundSequentialDependence;
112
113     /// \brief A handle to the branch probability pass.
114    const MachineBranchProbabilityInfo *MBPI;
115
116    // Track MIs with ignored dependece.
117    std::vector<MachineInstr*> IgnoreDepMIs;
118
119   public:
120     // Ctor.
121     HexagonPacketizerList(MachineFunction &MF, MachineLoopInfo &MLI,
122                           const MachineBranchProbabilityInfo *MBPI);
123
124     // initPacketizerState - initialize some internal flags.
125     void initPacketizerState() override;
126
127     // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
128     bool ignorePseudoInstruction(MachineInstr *MI,
129                                  MachineBasicBlock *MBB) override;
130
131     // isSoloInstruction - return true if instruction MI can not be packetized
132     // with any other instruction, which means that MI itself is a packet.
133     bool isSoloInstruction(MachineInstr *MI) override;
134
135     // isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ
136     // together.
137     bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) override;
138
139     // isLegalToPruneDependencies - Is it legal to prune dependece between SUI
140     // and SUJ.
141     bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) override;
142
143     MachineBasicBlock::iterator addToPacket(MachineInstr *MI) override;
144   private:
145     bool IsCallDependent(MachineInstr* MI, SDep::Kind DepType, unsigned DepReg);
146     bool PromoteToDotNew(MachineInstr* MI, SDep::Kind DepType,
147                          MachineBasicBlock::iterator &MII,
148                          const TargetRegisterClass* RC);
149     bool CanPromoteToDotNew(MachineInstr *MI, SUnit *PacketSU, unsigned DepReg,
150                             const std::map<MachineInstr *, SUnit *> &MIToSUnit,
151                             MachineBasicBlock::iterator &MII,
152                             const TargetRegisterClass *RC);
153     bool
154     CanPromoteToNewValue(MachineInstr *MI, SUnit *PacketSU, unsigned DepReg,
155                          const std::map<MachineInstr *, SUnit *> &MIToSUnit,
156                          MachineBasicBlock::iterator &MII);
157     bool CanPromoteToNewValueStore(
158         MachineInstr *MI, MachineInstr *PacketMI, unsigned DepReg,
159         const std::map<MachineInstr *, SUnit *> &MIToSUnit);
160     bool DemoteToDotOld(MachineInstr *MI);
161     bool ArePredicatesComplements(
162         MachineInstr *MI1, MachineInstr *MI2,
163         const std::map<MachineInstr *, SUnit *> &MIToSUnit);
164     bool RestrictingDepExistInPacket(MachineInstr *, unsigned,
165                                      const std::map<MachineInstr *, SUnit *> &);
166     bool isNewifiable(MachineInstr* MI);
167     bool isCondInst(MachineInstr* MI);
168     bool tryAllocateResourcesForConstExt(MachineInstr* MI);
169     bool canReserveResourcesForConstExt(MachineInstr *MI);
170     void reserveResourcesForConstExt(MachineInstr* MI);
171     bool isNewValueInst(MachineInstr* MI);
172   };
173 } // namespace
174
175 INITIALIZE_PASS_BEGIN(HexagonPacketizer, "packets", "Hexagon Packetizer",
176                       false, false)
177 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
178 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
179 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
180 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
181 INITIALIZE_PASS_END(HexagonPacketizer, "packets", "Hexagon Packetizer",
182                     false, false)
183
184
185 // HexagonPacketizerList Ctor.
186 HexagonPacketizerList::HexagonPacketizerList(
187     MachineFunction &MF, MachineLoopInfo &MLI,
188     const MachineBranchProbabilityInfo *MBPI)
189     : VLIWPacketizerList(MF, MLI, true) {
190   this->MBPI = MBPI;
191 }
192
193 bool HexagonPacketizer::runOnMachineFunction(MachineFunction &Fn) {
194   const TargetInstrInfo *TII = Fn.getSubtarget().getInstrInfo();
195   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
196   const MachineBranchProbabilityInfo *MBPI =
197     &getAnalysis<MachineBranchProbabilityInfo>();
198   // Instantiate the packetizer.
199   HexagonPacketizerList Packetizer(Fn, MLI, MBPI);
200
201   // DFA state table should not be empty.
202   assert(Packetizer.getResourceTracker() && "Empty DFA table!");
203
204   //
205   // Loop over all basic blocks and remove KILL pseudo-instructions
206   // These instructions confuse the dependence analysis. Consider:
207   // D0 = ...   (Insn 0)
208   // R0 = KILL R0, D0 (Insn 1)
209   // R0 = ... (Insn 2)
210   // Here, Insn 1 will result in the dependence graph not emitting an output
211   // dependence between Insn 0 and Insn 2. This can lead to incorrect
212   // packetization
213   //
214   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
215        MBB != MBBe; ++MBB) {
216     MachineBasicBlock::iterator End = MBB->end();
217     MachineBasicBlock::iterator MI = MBB->begin();
218     while (MI != End) {
219       if (MI->isKill()) {
220         MachineBasicBlock::iterator DeleteMI = MI;
221         ++MI;
222         MBB->erase(DeleteMI);
223         End = MBB->end();
224         continue;
225       }
226       ++MI;
227     }
228   }
229
230   // Loop over all of the basic blocks.
231   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
232        MBB != MBBe; ++MBB) {
233     // Find scheduling regions and schedule / packetize each region.
234     unsigned RemainingCount = MBB->size();
235     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
236         RegionEnd != MBB->begin();) {
237       // The next region starts above the previous region. Look backward in the
238       // instruction stream until we find the nearest boundary.
239       MachineBasicBlock::iterator I = RegionEnd;
240       for(;I != MBB->begin(); --I, --RemainingCount) {
241         if (TII->isSchedulingBoundary(std::prev(I), MBB, Fn))
242           break;
243       }
244       I = MBB->begin();
245
246       // Skip empty scheduling regions.
247       if (I == RegionEnd) {
248         RegionEnd = std::prev(RegionEnd);
249         --RemainingCount;
250         continue;
251       }
252       // Skip regions with one instruction.
253       if (I == std::prev(RegionEnd)) {
254         RegionEnd = std::prev(RegionEnd);
255         continue;
256       }
257
258       Packetizer.PacketizeMIs(MBB, I, RegionEnd);
259       RegionEnd = I;
260     }
261   }
262
263   return true;
264 }
265
266
267 static bool IsIndirectCall(MachineInstr* MI) {
268   return MI->getOpcode() == Hexagon::J2_callr;
269 }
270
271 // Reserve resources for constant extender. Trigure an assertion if
272 // reservation fail.
273 void HexagonPacketizerList::reserveResourcesForConstExt(MachineInstr* MI) {
274   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
275   MachineFunction *MF = MI->getParent()->getParent();
276   MachineInstr *PseudoMI = MF->CreateMachineInstr(QII->get(Hexagon::A4_ext),
277                                                   MI->getDebugLoc());
278
279   if (ResourceTracker->canReserveResources(PseudoMI)) {
280     ResourceTracker->reserveResources(PseudoMI);
281     MI->getParent()->getParent()->DeleteMachineInstr(PseudoMI);
282   } else {
283     MI->getParent()->getParent()->DeleteMachineInstr(PseudoMI);
284     llvm_unreachable("can not reserve resources for constant extender.");
285   }
286   return;
287 }
288
289 bool HexagonPacketizerList::canReserveResourcesForConstExt(MachineInstr *MI) {
290   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
291   assert((QII->isExtended(MI) || QII->isConstExtended(MI)) &&
292          "Should only be called for constant extended instructions");
293   MachineFunction *MF = MI->getParent()->getParent();
294   MachineInstr *PseudoMI = MF->CreateMachineInstr(QII->get(Hexagon::A4_ext),
295                                                   MI->getDebugLoc());
296   bool CanReserve = ResourceTracker->canReserveResources(PseudoMI);
297   MF->DeleteMachineInstr(PseudoMI);
298   return CanReserve;
299 }
300
301 // Allocate resources (i.e. 4 bytes) for constant extender. If succeed, return
302 // true, otherwise, return false.
303 bool HexagonPacketizerList::tryAllocateResourcesForConstExt(MachineInstr* MI) {
304   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
305   MachineFunction *MF = MI->getParent()->getParent();
306   MachineInstr *PseudoMI = MF->CreateMachineInstr(QII->get(Hexagon::A4_ext),
307                                                   MI->getDebugLoc());
308
309   if (ResourceTracker->canReserveResources(PseudoMI)) {
310     ResourceTracker->reserveResources(PseudoMI);
311     MI->getParent()->getParent()->DeleteMachineInstr(PseudoMI);
312     return true;
313   } else {
314     MI->getParent()->getParent()->DeleteMachineInstr(PseudoMI);
315     return false;
316   }
317 }
318
319
320 bool HexagonPacketizerList::IsCallDependent(MachineInstr* MI,
321                                           SDep::Kind DepType,
322                                           unsigned DepReg) {
323
324   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
325   const HexagonRegisterInfo *QRI =
326       (const HexagonRegisterInfo *)MF.getSubtarget().getRegisterInfo();
327
328   // Check for lr dependence
329   if (DepReg == QRI->getRARegister()) {
330     return true;
331   }
332
333   if (QII->isDeallocRet(MI)) {
334     if (DepReg == QRI->getFrameRegister() ||
335         DepReg == QRI->getStackRegister())
336       return true;
337   }
338
339   // Check if this is a predicate dependence
340   const TargetRegisterClass* RC = QRI->getMinimalPhysRegClass(DepReg);
341   if (RC == &Hexagon::PredRegsRegClass) {
342     return true;
343   }
344
345   //
346   // Lastly check for an operand used in an indirect call
347   // If we had an attribute for checking if an instruction is an indirect call,
348   // then we could have avoided this relatively brittle implementation of
349   // IsIndirectCall()
350   //
351   // Assumes that the first operand of the CALLr is the function address
352   //
353   if (IsIndirectCall(MI) && (DepType == SDep::Data)) {
354     MachineOperand MO = MI->getOperand(0);
355     if (MO.isReg() && MO.isUse() && (MO.getReg() == DepReg)) {
356       return true;
357     }
358   }
359
360   return false;
361 }
362
363 static bool IsRegDependence(const SDep::Kind DepType) {
364   return (DepType == SDep::Data || DepType == SDep::Anti ||
365           DepType == SDep::Output);
366 }
367
368 static bool IsDirectJump(MachineInstr* MI) {
369   return (MI->getOpcode() == Hexagon::J2_jump);
370 }
371
372 static bool IsSchedBarrier(MachineInstr* MI) {
373   switch (MI->getOpcode()) {
374   case Hexagon::Y2_barrier:
375     return true;
376   }
377   return false;
378 }
379
380 static bool IsControlFlow(MachineInstr* MI) {
381   return (MI->getDesc().isTerminator() || MI->getDesc().isCall());
382 }
383
384 static bool IsLoopN(MachineInstr *MI) {
385   return (MI->getOpcode() == Hexagon::J2_loop0i ||
386           MI->getOpcode() == Hexagon::J2_loop0r);
387 }
388
389 /// DoesModifyCalleeSavedReg - Returns true if the instruction modifies a
390 /// callee-saved register.
391 static bool DoesModifyCalleeSavedReg(MachineInstr *MI,
392                                      const TargetRegisterInfo *TRI) {
393   for (const MCPhysReg *CSR =
394            TRI->getCalleeSavedRegs(MI->getParent()->getParent());
395        *CSR; ++CSR) {
396     unsigned CalleeSavedReg = *CSR;
397     if (MI->modifiesRegister(CalleeSavedReg, TRI))
398       return true;
399   }
400   return false;
401 }
402
403 // Returns true if an instruction can be promoted to .new predicate
404 // or new-value store.
405 bool HexagonPacketizerList::isNewifiable(MachineInstr* MI) {
406   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
407   return isCondInst(MI) || QII->mayBeNewStore(MI);
408 }
409
410 bool HexagonPacketizerList::isCondInst (MachineInstr* MI) {
411   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
412   const MCInstrDesc& TID = MI->getDesc();
413                                     // bug 5670: until that is fixed,
414                                     // this portion is disabled.
415   if (   TID.isConditionalBranch()  // && !IsRegisterJump(MI)) ||
416       || QII->isConditionalTransfer(MI)
417       || QII->isConditionalALU32(MI)
418       || QII->isConditionalLoad(MI)
419       || QII->isConditionalStore(MI)) {
420     return true;
421   }
422   return false;
423 }
424
425
426 // Promote an instructiont to its .new form.
427 // At this time, we have already made a call to CanPromoteToDotNew
428 // and made sure that it can *indeed* be promoted.
429 bool HexagonPacketizerList::PromoteToDotNew(MachineInstr* MI,
430                         SDep::Kind DepType, MachineBasicBlock::iterator &MII,
431                         const TargetRegisterClass* RC) {
432
433   assert (DepType == SDep::Data);
434   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
435
436   int NewOpcode;
437   if (RC == &Hexagon::PredRegsRegClass)
438     NewOpcode = QII->GetDotNewPredOp(MI, MBPI);
439   else
440     NewOpcode = QII->GetDotNewOp(MI);
441   MI->setDesc(QII->get(NewOpcode));
442
443   return true;
444 }
445
446 bool HexagonPacketizerList::DemoteToDotOld(MachineInstr* MI) {
447   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
448   int NewOpcode = QII->GetDotOldOp(MI->getOpcode());
449   MI->setDesc(QII->get(NewOpcode));
450   return true;
451 }
452
453 enum PredicateKind {
454   PK_False,
455   PK_True,
456   PK_Unknown
457 };
458
459 /// Returns true if an instruction is predicated on p0 and false if it's
460 /// predicated on !p0.
461 static PredicateKind getPredicateSense(MachineInstr* MI,
462                                        const HexagonInstrInfo *QII) {
463   if (!QII->isPredicated(MI))
464     return PK_Unknown;
465
466   if (QII->isPredicatedTrue(MI))
467     return PK_True;
468
469   return PK_False;
470 }
471
472 static MachineOperand& GetPostIncrementOperand(MachineInstr *MI,
473                                                const HexagonInstrInfo *QII) {
474   assert(QII->isPostIncrement(MI) && "Not a post increment operation.");
475 #ifndef NDEBUG
476   // Post Increment means duplicates. Use dense map to find duplicates in the
477   // list. Caution: Densemap initializes with the minimum of 64 buckets,
478   // whereas there are at most 5 operands in the post increment.
479   DenseMap<unsigned,  unsigned> DefRegsSet;
480   for(unsigned opNum = 0; opNum < MI->getNumOperands(); opNum++)
481     if (MI->getOperand(opNum).isReg() &&
482         MI->getOperand(opNum).isDef()) {
483       DefRegsSet[MI->getOperand(opNum).getReg()] = 1;
484     }
485
486   for(unsigned opNum = 0; opNum < MI->getNumOperands(); opNum++)
487     if (MI->getOperand(opNum).isReg() &&
488         MI->getOperand(opNum).isUse()) {
489       if (DefRegsSet[MI->getOperand(opNum).getReg()]) {
490         return MI->getOperand(opNum);
491       }
492     }
493 #else
494   if (MI->getDesc().mayLoad()) {
495     // The 2nd operand is always the post increment operand in load.
496     assert(MI->getOperand(1).isReg() &&
497                 "Post increment operand has be to a register.");
498     return (MI->getOperand(1));
499   }
500   if (MI->getDesc().mayStore()) {
501     // The 1st operand is always the post increment operand in store.
502     assert(MI->getOperand(0).isReg() &&
503                 "Post increment operand has be to a register.");
504     return (MI->getOperand(0));
505   }
506 #endif
507   // we should never come here.
508   llvm_unreachable("mayLoad or mayStore not set for Post Increment operation");
509 }
510
511 // get the value being stored
512 static MachineOperand& GetStoreValueOperand(MachineInstr *MI) {
513   // value being stored is always the last operand.
514   return (MI->getOperand(MI->getNumOperands()-1));
515 }
516
517 // can be new value store?
518 // Following restrictions are to be respected in convert a store into
519 // a new value store.
520 // 1. If an instruction uses auto-increment, its address register cannot
521 //    be a new-value register. Arch Spec 5.4.2.1
522 // 2. If an instruction uses absolute-set addressing mode,
523 //    its address register cannot be a new-value register.
524 //    Arch Spec 5.4.2.1.TODO: This is not enabled as
525 //    as absolute-set address mode patters are not implemented.
526 // 3. If an instruction produces a 64-bit result, its registers cannot be used
527 //    as new-value registers. Arch Spec 5.4.2.2.
528 // 4. If the instruction that sets a new-value register is conditional, then
529 //    the instruction that uses the new-value register must also be conditional,
530 //    and both must always have their predicates evaluate identically.
531 //    Arch Spec 5.4.2.3.
532 // 5. There is an implied restriction of a packet can not have another store,
533 //    if there is a  new value store in the packet. Corollary, if there is
534 //    already a store in a packet, there can not be a new value store.
535 //    Arch Spec: 3.4.4.2
536 bool HexagonPacketizerList::CanPromoteToNewValueStore(
537     MachineInstr *MI, MachineInstr *PacketMI, unsigned DepReg,
538     const std::map<MachineInstr *, SUnit *> &MIToSUnit) {
539   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
540   // Make sure we are looking at the store, that can be promoted.
541   if (!QII->mayBeNewStore(MI))
542     return false;
543
544   // Make sure there is dependency and can be new value'ed
545   if (GetStoreValueOperand(MI).isReg() &&
546       GetStoreValueOperand(MI).getReg() != DepReg)
547     return false;
548
549   const HexagonRegisterInfo *QRI =
550       (const HexagonRegisterInfo *)MF.getSubtarget().getRegisterInfo();
551   const MCInstrDesc& MCID = PacketMI->getDesc();
552   // first operand is always the result
553
554   const TargetRegisterClass* PacketRC = QII->getRegClass(MCID, 0, QRI, MF);
555
556   // if there is already an store in the packet, no can do new value store
557   // Arch Spec 3.4.4.2.
558   for (std::vector<MachineInstr*>::iterator VI = CurrentPacketMIs.begin(),
559          VE = CurrentPacketMIs.end();
560        (VI != VE); ++VI) {
561     SUnit *PacketSU = MIToSUnit.find(*VI)->second;
562     if (PacketSU->getInstr()->getDesc().mayStore() ||
563         // if we have mayStore = 1 set on ALLOCFRAME and DEALLOCFRAME,
564         // then we don't need this
565         PacketSU->getInstr()->getOpcode() == Hexagon::S2_allocframe ||
566         PacketSU->getInstr()->getOpcode() == Hexagon::L2_deallocframe)
567       return false;
568   }
569
570   if (PacketRC == &Hexagon::DoubleRegsRegClass) {
571     // new value store constraint: double regs can not feed into new value store
572     // arch spec section: 5.4.2.2
573     return false;
574   }
575
576   // Make sure it's NOT the post increment register that we are going to
577   // new value.
578   if (QII->isPostIncrement(MI) &&
579       MI->getDesc().mayStore() &&
580       GetPostIncrementOperand(MI, QII).getReg() == DepReg) {
581     return false;
582   }
583
584   if (QII->isPostIncrement(PacketMI) &&
585       PacketMI->getDesc().mayLoad() &&
586       GetPostIncrementOperand(PacketMI, QII).getReg() == DepReg) {
587     // if source is post_inc, or absolute-set addressing,
588     // it can not feed into new value store
589     //  r3 = memw(r2++#4)
590     //  memw(r30 + #-1404) = r2.new -> can not be new value store
591     // arch spec section: 5.4.2.1
592     return false;
593   }
594
595   // If the source that feeds the store is predicated, new value store must
596   // also be predicated.
597   if (QII->isPredicated(PacketMI)) {
598     if (!QII->isPredicated(MI))
599       return false;
600
601     // Check to make sure that they both will have their predicates
602     // evaluate identically
603     unsigned predRegNumSrc = 0;
604     unsigned predRegNumDst = 0;
605     const TargetRegisterClass* predRegClass = nullptr;
606
607     // Get predicate register used in the source instruction
608     for(unsigned opNum = 0; opNum < PacketMI->getNumOperands(); opNum++) {
609       if ( PacketMI->getOperand(opNum).isReg())
610       predRegNumSrc = PacketMI->getOperand(opNum).getReg();
611       predRegClass = QRI->getMinimalPhysRegClass(predRegNumSrc);
612       if (predRegClass == &Hexagon::PredRegsRegClass) {
613         break;
614       }
615     }
616     assert ((predRegClass == &Hexagon::PredRegsRegClass ) &&
617         ("predicate register not found in a predicated PacketMI instruction"));
618
619     // Get predicate register used in new-value store instruction
620     for(unsigned opNum = 0; opNum < MI->getNumOperands(); opNum++) {
621       if ( MI->getOperand(opNum).isReg())
622       predRegNumDst = MI->getOperand(opNum).getReg();
623       predRegClass = QRI->getMinimalPhysRegClass(predRegNumDst);
624       if (predRegClass == &Hexagon::PredRegsRegClass) {
625         break;
626       }
627     }
628     assert ((predRegClass == &Hexagon::PredRegsRegClass ) &&
629             ("predicate register not found in a predicated MI instruction"));
630
631     // New-value register producer and user (store) need to satisfy these
632     // constraints:
633     // 1) Both instructions should be predicated on the same register.
634     // 2) If producer of the new-value register is .new predicated then store
635     // should also be .new predicated and if producer is not .new predicated
636     // then store should not be .new predicated.
637     // 3) Both new-value register producer and user should have same predicate
638     // sense, i.e, either both should be negated or both should be none negated.
639
640     if (( predRegNumDst != predRegNumSrc) ||
641           QII->isDotNewInst(PacketMI) != QII->isDotNewInst(MI)  ||
642           getPredicateSense(MI, QII) != getPredicateSense(PacketMI, QII)) {
643       return false;
644     }
645   }
646
647   // Make sure that other than the new-value register no other store instruction
648   // register has been modified in the same packet. Predicate registers can be
649   // modified by they should not be modified between the producer and the store
650   // instruction as it will make them both conditional on different values.
651   // We already know this to be true for all the instructions before and
652   // including PacketMI. Howerver, we need to perform the check for the
653   // remaining instructions in the packet.
654
655   std::vector<MachineInstr*>::iterator VI;
656   std::vector<MachineInstr*>::iterator VE;
657   unsigned StartCheck = 0;
658
659   for (VI=CurrentPacketMIs.begin(), VE = CurrentPacketMIs.end();
660       (VI != VE); ++VI) {
661     SUnit *TempSU = MIToSUnit.find(*VI)->second;
662     MachineInstr* TempMI = TempSU->getInstr();
663
664     // Following condition is true for all the instructions until PacketMI is
665     // reached (StartCheck is set to 0 before the for loop).
666     // StartCheck flag is 1 for all the instructions after PacketMI.
667     if (TempMI != PacketMI && !StartCheck) // start processing only after
668       continue;                            // encountering PacketMI
669
670     StartCheck = 1;
671     if (TempMI == PacketMI) // We don't want to check PacketMI for dependence
672       continue;
673
674     for(unsigned opNum = 0; opNum < MI->getNumOperands(); opNum++) {
675       if (MI->getOperand(opNum).isReg() &&
676           TempSU->getInstr()->modifiesRegister(MI->getOperand(opNum).getReg(),
677                                                QRI))
678         return false;
679     }
680   }
681
682   // Make sure that for non-POST_INC stores:
683   // 1. The only use of reg is DepReg and no other registers.
684   //    This handles V4 base+index registers.
685   //    The following store can not be dot new.
686   //    Eg.   r0 = add(r0, #3)a
687   //          memw(r1+r0<<#2) = r0
688   if (!QII->isPostIncrement(MI) &&
689       GetStoreValueOperand(MI).isReg() &&
690       GetStoreValueOperand(MI).getReg() == DepReg) {
691     for(unsigned opNum = 0; opNum < MI->getNumOperands()-1; opNum++) {
692       if (MI->getOperand(opNum).isReg() &&
693           MI->getOperand(opNum).getReg() == DepReg) {
694         return false;
695       }
696     }
697     // 2. If data definition is because of implicit definition of the register,
698     //    do not newify the store. Eg.
699     //    %R9<def> = ZXTH %R12, %D6<imp-use>, %R12<imp-def>
700     //    STrih_indexed %R8, 2, %R12<kill>; mem:ST2[%scevgep343]
701     for(unsigned opNum = 0; opNum < PacketMI->getNumOperands(); opNum++) {
702       if (PacketMI->getOperand(opNum).isReg() &&
703           PacketMI->getOperand(opNum).getReg() == DepReg &&
704           PacketMI->getOperand(opNum).isDef() &&
705           PacketMI->getOperand(opNum).isImplicit()) {
706         return false;
707       }
708     }
709   }
710
711   // Can be dot new store.
712   return true;
713 }
714
715 // can this MI to promoted to either
716 // new value store or new value jump
717 bool HexagonPacketizerList::CanPromoteToNewValue(
718     MachineInstr *MI, SUnit *PacketSU, unsigned DepReg,
719     const std::map<MachineInstr *, SUnit *> &MIToSUnit,
720     MachineBasicBlock::iterator &MII) {
721
722   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
723   if (!QII->mayBeNewStore(MI))
724     return false;
725
726   MachineInstr *PacketMI = PacketSU->getInstr();
727
728   // Check to see the store can be new value'ed.
729   if (CanPromoteToNewValueStore(MI, PacketMI, DepReg, MIToSUnit))
730     return true;
731
732   // Check to see the compare/jump can be new value'ed.
733   // This is done as a pass on its own. Don't need to check it here.
734   return false;
735 }
736
737 // Check to see if an instruction can be dot new
738 // There are three kinds.
739 // 1. dot new on predicate - V2/V3/V4
740 // 2. dot new on stores NV/ST - V4
741 // 3. dot new on jump NV/J - V4 -- This is generated in a pass.
742 bool HexagonPacketizerList::CanPromoteToDotNew(
743     MachineInstr *MI, SUnit *PacketSU, unsigned DepReg,
744     const std::map<MachineInstr *, SUnit *> &MIToSUnit,
745     MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC) {
746   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
747   // Already a dot new instruction.
748   if (QII->isDotNewInst(MI) && !QII->mayBeNewStore(MI))
749     return false;
750
751   if (!isNewifiable(MI))
752     return false;
753
754   // predicate .new
755   if (RC == &Hexagon::PredRegsRegClass && isCondInst(MI))
756       return true;
757   else if (RC != &Hexagon::PredRegsRegClass &&
758       !QII->mayBeNewStore(MI)) // MI is not a new-value store
759     return false;
760   else {
761     // Create a dot new machine instruction to see if resources can be
762     // allocated. If not, bail out now.
763     int NewOpcode = QII->GetDotNewOp(MI);
764     const MCInstrDesc &desc = QII->get(NewOpcode);
765     DebugLoc dl;
766     MachineInstr *NewMI =
767                     MI->getParent()->getParent()->CreateMachineInstr(desc, dl);
768     bool ResourcesAvailable = ResourceTracker->canReserveResources(NewMI);
769     MI->getParent()->getParent()->DeleteMachineInstr(NewMI);
770
771     if (!ResourcesAvailable)
772       return false;
773
774     // new value store only
775     // new new value jump generated as a passes
776     if (!CanPromoteToNewValue(MI, PacketSU, DepReg, MIToSUnit, MII)) {
777       return false;
778     }
779   }
780   return true;
781 }
782
783 // Go through the packet instructions and search for anti dependency
784 // between them and DepReg from MI
785 // Consider this case:
786 // Trying to add
787 // a) %R1<def> = TFRI_cdNotPt %P3, 2
788 // to this packet:
789 // {
790 //   b) %P0<def> = OR_pp %P3<kill>, %P0<kill>
791 //   c) %P3<def> = TFR_PdRs %R23
792 //   d) %R1<def> = TFRI_cdnPt %P3, 4
793 //  }
794 // The P3 from a) and d) will be complements after
795 // a)'s P3 is converted to .new form
796 // Anti Dep between c) and b) is irrelevant for this case
797 bool HexagonPacketizerList::RestrictingDepExistInPacket(
798     MachineInstr *MI, unsigned DepReg,
799     const std::map<MachineInstr *, SUnit *> &MIToSUnit) {
800
801   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
802   SUnit *PacketSUDep = MIToSUnit.find(MI)->second;
803
804   for (std::vector<MachineInstr*>::iterator VIN = CurrentPacketMIs.begin(),
805        VEN = CurrentPacketMIs.end(); (VIN != VEN); ++VIN) {
806
807     // We only care for dependencies to predicated instructions
808     if(!QII->isPredicated(*VIN)) continue;
809
810     // Scheduling Unit for current insn in the packet
811     SUnit *PacketSU = MIToSUnit.find(*VIN)->second;
812
813     // Look at dependencies between current members of the packet
814     // and predicate defining instruction MI.
815     // Make sure that dependency is on the exact register
816     // we care about.
817     if (PacketSU->isSucc(PacketSUDep)) {
818       for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
819         if ((PacketSU->Succs[i].getSUnit() == PacketSUDep) &&
820             (PacketSU->Succs[i].getKind() == SDep::Anti) &&
821             (PacketSU->Succs[i].getReg() == DepReg)) {
822           return true;
823         }
824       }
825     }
826   }
827
828   return false;
829 }
830
831
832 /// Gets the predicate register of a predicated instruction.
833 static unsigned getPredicatedRegister(MachineInstr *MI,
834                                       const HexagonInstrInfo *QII) {
835   /// We use the following rule: The first predicate register that is a use is
836   /// the predicate register of a predicated instruction.
837
838   assert(QII->isPredicated(MI) && "Must be predicated instruction");
839
840   for (MachineInstr::mop_iterator OI = MI->operands_begin(),
841        OE = MI->operands_end(); OI != OE; ++OI) {
842     MachineOperand &Op = *OI;
843     if (Op.isReg() && Op.getReg() && Op.isUse() &&
844         Hexagon::PredRegsRegClass.contains(Op.getReg()))
845       return Op.getReg();
846   }
847
848   llvm_unreachable("Unknown instruction operand layout");
849
850   return 0;
851 }
852
853 // Given two predicated instructions, this function detects whether
854 // the predicates are complements
855 bool HexagonPacketizerList::ArePredicatesComplements(
856     MachineInstr *MI1, MachineInstr *MI2,
857     const std::map<MachineInstr *, SUnit *> &MIToSUnit) {
858
859   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
860
861   // If we don't know the predicate sense of the instructions bail out early, we
862   // need it later.
863   if (getPredicateSense(MI1, QII) == PK_Unknown ||
864       getPredicateSense(MI2, QII) == PK_Unknown)
865     return false;
866
867   // Scheduling unit for candidate
868   SUnit *SU = MIToSUnit.find(MI1)->second;
869
870   // One corner case deals with the following scenario:
871   // Trying to add
872   // a) %R24<def> = TFR_cPt %P0, %R25
873   // to this packet:
874   //
875   // {
876   //   b) %R25<def> = TFR_cNotPt %P0, %R24
877   //   c) %P0<def> = CMPEQri %R26, 1
878   // }
879   //
880   // On general check a) and b) are complements, but
881   // presence of c) will convert a) to .new form, and
882   // then it is not a complement
883   // We attempt to detect it by analyzing  existing
884   // dependencies in the packet
885
886   // Analyze relationships between all existing members of the packet.
887   // Look for Anti dependecy on the same predicate reg
888   // as used in the candidate
889   for (std::vector<MachineInstr*>::iterator VIN = CurrentPacketMIs.begin(),
890        VEN = CurrentPacketMIs.end(); (VIN != VEN); ++VIN) {
891
892     // Scheduling Unit for current insn in the packet
893     SUnit *PacketSU = MIToSUnit.find(*VIN)->second;
894
895     // If this instruction in the packet is succeeded by the candidate...
896     if (PacketSU->isSucc(SU)) {
897       for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
898         // The corner case exist when there is true data
899         // dependency between candidate and one of current
900         // packet members, this dep is on predicate reg, and
901         // there already exist anti dep on the same pred in
902         // the packet.
903         if (PacketSU->Succs[i].getSUnit() == SU &&
904             PacketSU->Succs[i].getKind() == SDep::Data &&
905             Hexagon::PredRegsRegClass.contains(
906               PacketSU->Succs[i].getReg()) &&
907             // Here I know that *VIN is predicate setting instruction
908             // with true data dep to candidate on the register
909             // we care about - c) in the above example.
910             // Now I need to see if there is an anti dependency
911             // from c) to any other instruction in the
912             // same packet on the pred reg of interest
913             RestrictingDepExistInPacket(*VIN,PacketSU->Succs[i].getReg(),
914                                         MIToSUnit)) {
915            return false;
916         }
917       }
918     }
919   }
920
921   // If the above case does not apply, check regular
922   // complement condition.
923   // Check that the predicate register is the same and
924   // that the predicate sense is different
925   // We also need to differentiate .old vs. .new:
926   // !p0 is not complimentary to p0.new
927   unsigned PReg1 = getPredicatedRegister(MI1, QII);
928   unsigned PReg2 = getPredicatedRegister(MI2, QII);
929   return ((PReg1 == PReg2) &&
930           Hexagon::PredRegsRegClass.contains(PReg1) &&
931           Hexagon::PredRegsRegClass.contains(PReg2) &&
932           (getPredicateSense(MI1, QII) != getPredicateSense(MI2, QII)) &&
933           (QII->isDotNewInst(MI1) == QII->isDotNewInst(MI2)));
934 }
935
936 // initPacketizerState - Initialize packetizer flags
937 void HexagonPacketizerList::initPacketizerState() {
938
939   Dependence = false;
940   PromotedToDotNew = false;
941   GlueToNewValueJump = false;
942   GlueAllocframeStore = false;
943   FoundSequentialDependence = false;
944
945   return;
946 }
947
948 // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
949 bool HexagonPacketizerList::ignorePseudoInstruction(MachineInstr *MI,
950                                                     MachineBasicBlock *MBB) {
951   if (MI->isDebugValue())
952     return true;
953
954   if (MI->isCFIInstruction())
955     return false;
956
957   // We must print out inline assembly
958   if (MI->isInlineAsm())
959     return false;
960
961   // We check if MI has any functional units mapped to it.
962   // If it doesn't, we ignore the instruction.
963   const MCInstrDesc& TID = MI->getDesc();
964   unsigned SchedClass = TID.getSchedClass();
965   const InstrStage* IS =
966                     ResourceTracker->getInstrItins()->beginStage(SchedClass);
967   unsigned FuncUnits = IS->getUnits();
968   return !FuncUnits;
969 }
970
971 // isSoloInstruction: - Returns true for instructions that must be
972 // scheduled in their own packet.
973 bool HexagonPacketizerList::isSoloInstruction(MachineInstr *MI) {
974   if (MI->isEHLabel() || MI->isCFIInstruction())
975     return true;
976
977   if (MI->isInlineAsm())
978     return true;
979
980   // From Hexagon V4 Programmer's Reference Manual 3.4.4 Grouping constraints:
981   // trap, pause, barrier, icinva, isync, and syncht are solo instructions.
982   // They must not be grouped with other instructions in a packet.
983   if (IsSchedBarrier(MI))
984     return true;
985
986   return false;
987 }
988
989 // isLegalToPacketizeTogether:
990 // SUI is the current instruction that is out side of the current packet.
991 // SUJ is the current instruction inside the current packet against which that
992 // SUI will be packetized.
993 bool HexagonPacketizerList::isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {
994   MachineInstr *I = SUI->getInstr();
995   MachineInstr *J = SUJ->getInstr();
996   assert(I && J && "Unable to packetize null instruction!");
997
998   const MCInstrDesc &MCIDI = I->getDesc();
999   const MCInstrDesc &MCIDJ = J->getDesc();
1000
1001   MachineBasicBlock::iterator II = I;
1002
1003   const unsigned FrameSize = MF.getFrameInfo()->getStackSize();
1004   const HexagonRegisterInfo *QRI =
1005       (const HexagonRegisterInfo *)MF.getSubtarget().getRegisterInfo();
1006   const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
1007
1008   // Inline asm cannot go in the packet.
1009   if (I->getOpcode() == Hexagon::INLINEASM)
1010     llvm_unreachable("Should not meet inline asm here!");
1011
1012   if (isSoloInstruction(I))
1013     llvm_unreachable("Should not meet solo instr here!");
1014
1015   // A save callee-save register function call can only be in a packet
1016   // with instructions that don't write to the callee-save registers.
1017   if ((QII->isSaveCalleeSavedRegsCall(I) &&
1018        DoesModifyCalleeSavedReg(J, QRI)) ||
1019       (QII->isSaveCalleeSavedRegsCall(J) &&
1020        DoesModifyCalleeSavedReg(I, QRI))) {
1021     Dependence = true;
1022     return false;
1023   }
1024
1025   // Two control flow instructions cannot go in the same packet.
1026   if (IsControlFlow(I) && IsControlFlow(J)) {
1027     Dependence = true;
1028     return false;
1029   }
1030
1031   // A LoopN instruction cannot appear in the same packet as a jump or call.
1032   if (IsLoopN(I) &&
1033      (IsDirectJump(J) || MCIDJ.isCall() || QII->isDeallocRet(J))) {
1034     Dependence = true;
1035     return false;
1036   }
1037   if (IsLoopN(J) &&
1038      (IsDirectJump(I) || MCIDI.isCall() || QII->isDeallocRet(I))) {
1039     Dependence = true;
1040     return false;
1041   }
1042
1043   // dealloc_return cannot appear in the same packet as a conditional or
1044   // unconditional jump.
1045   if (QII->isDeallocRet(I) &&
1046      (MCIDJ.isBranch() || MCIDJ.isCall() || MCIDJ.isBarrier())) {
1047     Dependence = true;
1048     return false;
1049   }
1050
1051
1052   // V4 allows dual store. But does not allow second store, if the
1053   // first store is not in SLOT0. New value store, new value jump,
1054   // dealloc_return and memop always take SLOT0.
1055   // Arch spec 3.4.4.2
1056   if (MCIDI.mayStore() && MCIDJ.mayStore() &&
1057       (QII->isNewValueInst(J) || QII->isMemOp(J) || QII->isMemOp(I))) {
1058     Dependence = true;
1059     return false;
1060   }
1061
1062   if ((QII->isMemOp(J) && MCIDI.mayStore())
1063       || (MCIDJ.mayStore() && QII->isMemOp(I))
1064       || (QII->isMemOp(J) && QII->isMemOp(I))) {
1065     Dependence = true;
1066     return false;
1067   }
1068
1069   //if dealloc_return
1070   if (MCIDJ.mayStore() && QII->isDeallocRet(I)) {
1071     Dependence = true;
1072     return false;
1073   }
1074
1075   // If an instruction feeds new value jump, glue it.
1076   MachineBasicBlock::iterator NextMII = I;
1077   ++NextMII;
1078   if (NextMII != I->getParent()->end() && QII->isNewValueJump(NextMII)) {
1079     MachineInstr *NextMI = NextMII;
1080
1081     bool secondRegMatch = false;
1082     bool maintainNewValueJump = false;
1083
1084     if (NextMI->getOperand(1).isReg() &&
1085         I->getOperand(0).getReg() == NextMI->getOperand(1).getReg()) {
1086       secondRegMatch = true;
1087       maintainNewValueJump = true;
1088     }
1089
1090     if (!secondRegMatch &&
1091           I->getOperand(0).getReg() == NextMI->getOperand(0).getReg()) {
1092       maintainNewValueJump = true;
1093     }
1094
1095     for (std::vector<MachineInstr*>::iterator
1096           VI = CurrentPacketMIs.begin(),
1097             VE = CurrentPacketMIs.end();
1098           (VI != VE && maintainNewValueJump); ++VI) {
1099       SUnit *PacketSU = MIToSUnit.find(*VI)->second;
1100
1101       // NVJ can not be part of the dual jump - Arch Spec: section 7.8
1102       if (PacketSU->getInstr()->getDesc().isCall()) {
1103         Dependence = true;
1104         break;
1105       }
1106       // Validate
1107       // 1. Packet does not have a store in it.
1108       // 2. If the first operand of the nvj is newified, and the second
1109       //    operand is also a reg, it (second reg) is not defined in
1110       //    the same packet.
1111       // 3. If the second operand of the nvj is newified, (which means
1112       //    first operand is also a reg), first reg is not defined in
1113       //    the same packet.
1114       if (PacketSU->getInstr()->getDesc().mayStore()               ||
1115           PacketSU->getInstr()->getOpcode() == Hexagon::S2_allocframe ||
1116           // Check #2.
1117           (!secondRegMatch && NextMI->getOperand(1).isReg() &&
1118             PacketSU->getInstr()->modifiesRegister(
1119                               NextMI->getOperand(1).getReg(), QRI)) ||
1120           // Check #3.
1121           (secondRegMatch &&
1122             PacketSU->getInstr()->modifiesRegister(
1123                               NextMI->getOperand(0).getReg(), QRI))) {
1124         Dependence = true;
1125         break;
1126       }
1127     }
1128     if (!Dependence)
1129       GlueToNewValueJump = true;
1130     else
1131       return false;
1132   }
1133
1134   if (SUJ->isSucc(SUI)) {
1135     for (unsigned i = 0;
1136          (i < SUJ->Succs.size()) && !FoundSequentialDependence;
1137          ++i) {
1138
1139       if (SUJ->Succs[i].getSUnit() != SUI) {
1140         continue;
1141       }
1142
1143       SDep::Kind DepType = SUJ->Succs[i].getKind();
1144
1145       // For direct calls:
1146       // Ignore register dependences for call instructions for
1147       // packetization purposes except for those due to r31 and
1148       // predicate registers.
1149       //
1150       // For indirect calls:
1151       // Same as direct calls + check for true dependences to the register
1152       // used in the indirect call.
1153       //
1154       // We completely ignore Order dependences for call instructions
1155       //
1156       // For returns:
1157       // Ignore register dependences for return instructions like jumpr,
1158       // dealloc return unless we have dependencies on the explicit uses
1159       // of the registers used by jumpr (like r31) or dealloc return
1160       // (like r29 or r30).
1161       //
1162       // TODO: Currently, jumpr is handling only return of r31. So, the
1163       // following logic (specificaly IsCallDependent) is working fine.
1164       // We need to enable jumpr for register other than r31 and then,
1165       // we need to rework the last part, where it handles indirect call
1166       // of that (IsCallDependent) function. Bug 6216 is opened for this.
1167       //
1168       unsigned DepReg = 0;
1169       const TargetRegisterClass* RC = nullptr;
1170       if (DepType == SDep::Data) {
1171         DepReg = SUJ->Succs[i].getReg();
1172         RC = QRI->getMinimalPhysRegClass(DepReg);
1173       }
1174       if ((MCIDI.isCall() || MCIDI.isReturn()) &&
1175           (!IsRegDependence(DepType) ||
1176             !IsCallDependent(I, DepType, SUJ->Succs[i].getReg()))) {
1177         /* do nothing */
1178       }
1179
1180       // For instructions that can be promoted to dot-new, try to promote.
1181       else if ((DepType == SDep::Data) &&
1182                CanPromoteToDotNew(I, SUJ, DepReg, MIToSUnit, II, RC) &&
1183                PromoteToDotNew(I, DepType, II, RC)) {
1184         PromotedToDotNew = true;
1185         /* do nothing */
1186       }
1187
1188       else if ((DepType == SDep::Data) &&
1189                (QII->isNewValueJump(I))) {
1190         /* do nothing */
1191       }
1192
1193       // For predicated instructions, if the predicates are complements
1194       // then there can be no dependence.
1195       else if (QII->isPredicated(I) &&
1196                QII->isPredicated(J) &&
1197           ArePredicatesComplements(I, J, MIToSUnit)) {
1198         /* do nothing */
1199
1200       }
1201       else if (IsDirectJump(I) &&
1202                !MCIDJ.isBranch() &&
1203                !MCIDJ.isCall() &&
1204                (DepType == SDep::Order)) {
1205         // Ignore Order dependences between unconditional direct branches
1206         // and non-control-flow instructions
1207         /* do nothing */
1208       }
1209       else if (MCIDI.isConditionalBranch() && (DepType != SDep::Data) &&
1210                (DepType != SDep::Output)) {
1211         // Ignore all dependences for jumps except for true and output
1212         // dependences
1213         /* do nothing */
1214       }
1215
1216       // Ignore output dependences due to superregs. We can
1217       // write to two different subregisters of R1:0 for instance
1218       // in the same cycle
1219       //
1220
1221       //
1222       // Let the
1223       // If neither I nor J defines DepReg, then this is a
1224       // superfluous output dependence. The dependence must be of the
1225       // form:
1226       //  R0 = ...
1227       //  R1 = ...
1228       // and there is an output dependence between the two instructions
1229       // with
1230       // DepReg = D0
1231       // We want to ignore these dependences.
1232       // Ideally, the dependence constructor should annotate such
1233       // dependences. We can then avoid this relatively expensive check.
1234       //
1235       else if (DepType == SDep::Output) {
1236         // DepReg is the register that's responsible for the dependence.
1237         unsigned DepReg = SUJ->Succs[i].getReg();
1238
1239         // Check if I and J really defines DepReg.
1240         if (I->definesRegister(DepReg) ||
1241             J->definesRegister(DepReg)) {
1242           FoundSequentialDependence = true;
1243           break;
1244         }
1245       }
1246
1247       // We ignore Order dependences for
1248       // 1. Two loads unless they are volatile.
1249       // 2. Two stores in V4 unless they are volatile.
1250       else if ((DepType == SDep::Order) &&
1251                !I->hasOrderedMemoryRef() &&
1252                !J->hasOrderedMemoryRef()) {
1253         if (MCIDI.mayStore() && MCIDJ.mayStore()) {
1254           /* do nothing */
1255         }
1256         // store followed by store-- not OK on V2
1257         // store followed by load -- not OK on all (OK if addresses
1258         // are not aliased)
1259         // load followed by store -- OK on all
1260         // load followed by load  -- OK on all
1261         else if ( !MCIDJ.mayStore()) {
1262           /* do nothing */
1263         }
1264         else {
1265           FoundSequentialDependence = true;
1266           break;
1267         }
1268       }
1269
1270       // For V4, special case ALLOCFRAME. Even though there is dependency
1271       // between ALLOCFRAME and subsequent store, allow it to be
1272       // packetized in a same packet. This implies that the store is using
1273       // caller's SP. Hence, offset needs to be updated accordingly.
1274       else if (DepType == SDep::Data
1275                && J->getOpcode() == Hexagon::S2_allocframe
1276                && (I->getOpcode() == Hexagon::S2_storerd_io
1277                    || I->getOpcode() == Hexagon::S2_storeri_io
1278                    || I->getOpcode() == Hexagon::S2_storerb_io)
1279                && I->getOperand(0).getReg() == QRI->getStackRegister()
1280                && QII->isValidOffset(I->getOpcode(),
1281                                      I->getOperand(1).getImm() -
1282                                      (FrameSize + HEXAGON_LRFP_SIZE)))
1283       {
1284         GlueAllocframeStore = true;
1285         // Since this store is to be glued with allocframe in the same
1286         // packet, it will use SP of the previous stack frame, i.e
1287         // caller's SP. Therefore, we need to recalculate offset according
1288         // to this change.
1289         I->getOperand(1).setImm(I->getOperand(1).getImm() -
1290                                         (FrameSize + HEXAGON_LRFP_SIZE));
1291       }
1292
1293       //
1294       // Skip over anti-dependences. Two instructions that are
1295       // anti-dependent can share a packet
1296       //
1297       else if (DepType != SDep::Anti) {
1298         FoundSequentialDependence = true;
1299         break;
1300       }
1301     }
1302
1303     if (FoundSequentialDependence) {
1304       Dependence = true;
1305       return false;
1306     }
1307   }
1308
1309   return true;
1310 }
1311
1312 // isLegalToPruneDependencies
1313 bool HexagonPacketizerList::isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {
1314   MachineInstr *I = SUI->getInstr();
1315   assert(I && SUJ->getInstr() && "Unable to packetize null instruction!");
1316
1317   const unsigned FrameSize = MF.getFrameInfo()->getStackSize();
1318
1319   if (Dependence) {
1320
1321     // Check if the instruction was promoted to a dot-new. If so, demote it
1322     // back into a dot-old.
1323     if (PromotedToDotNew) {
1324       DemoteToDotOld(I);
1325     }
1326
1327     // Check if the instruction (must be a store) was glued with an Allocframe
1328     // instruction. If so, restore its offset to its original value, i.e. use
1329     // curent SP instead of caller's SP.
1330     if (GlueAllocframeStore) {
1331       I->getOperand(1).setImm(I->getOperand(1).getImm() +
1332                                              FrameSize + HEXAGON_LRFP_SIZE);
1333     }
1334
1335     return false;
1336   }
1337   return true;
1338 }
1339
1340 MachineBasicBlock::iterator
1341 HexagonPacketizerList::addToPacket(MachineInstr *MI) {
1342
1343     MachineBasicBlock::iterator MII = MI;
1344     MachineBasicBlock *MBB = MI->getParent();
1345
1346     const HexagonInstrInfo *QII = (const HexagonInstrInfo *) TII;
1347
1348     if (GlueToNewValueJump) {
1349
1350       ++MII;
1351       MachineInstr *nvjMI = MII;
1352       assert(ResourceTracker->canReserveResources(MI));
1353       ResourceTracker->reserveResources(MI);
1354       if ((QII->isExtended(MI) || QII->isConstExtended(MI)) &&
1355           !tryAllocateResourcesForConstExt(MI)) {
1356         endPacket(MBB, MI);
1357         ResourceTracker->reserveResources(MI);
1358         assert(canReserveResourcesForConstExt(MI) &&
1359                "Ensure that there is a slot");
1360         reserveResourcesForConstExt(MI);
1361         // Reserve resources for new value jump constant extender.
1362         assert(canReserveResourcesForConstExt(MI) &&
1363                "Ensure that there is a slot");
1364         reserveResourcesForConstExt(nvjMI);
1365         assert(ResourceTracker->canReserveResources(nvjMI) &&
1366                "Ensure that there is a slot");
1367
1368       } else if (   // Extended instruction takes two slots in the packet.
1369         // Try reserve and allocate 4-byte in the current packet first.
1370         (QII->isExtended(nvjMI)
1371             && (!tryAllocateResourcesForConstExt(nvjMI)
1372                 || !ResourceTracker->canReserveResources(nvjMI)))
1373         || // For non-extended instruction, no need to allocate extra 4 bytes.
1374         (!QII->isExtended(nvjMI) &&
1375               !ResourceTracker->canReserveResources(nvjMI)))
1376       {
1377         endPacket(MBB, MI);
1378         // A new and empty packet starts.
1379         // We are sure that the resources requirements can be satisfied.
1380         // Therefore, do not need to call "canReserveResources" anymore.
1381         ResourceTracker->reserveResources(MI);
1382         if (QII->isExtended(nvjMI))
1383           reserveResourcesForConstExt(nvjMI);
1384       }
1385       // Here, we are sure that "reserveResources" would succeed.
1386       ResourceTracker->reserveResources(nvjMI);
1387       CurrentPacketMIs.push_back(MI);
1388       CurrentPacketMIs.push_back(nvjMI);
1389     } else {
1390       if (   (QII->isExtended(MI) || QII->isConstExtended(MI))
1391           && (   !tryAllocateResourcesForConstExt(MI)
1392               || !ResourceTracker->canReserveResources(MI)))
1393       {
1394         endPacket(MBB, MI);
1395         // Check if the instruction was promoted to a dot-new. If so, demote it
1396         // back into a dot-old
1397         if (PromotedToDotNew) {
1398           DemoteToDotOld(MI);
1399         }
1400         reserveResourcesForConstExt(MI);
1401       }
1402       // In case that "MI" is not an extended insn,
1403       // the resource availability has already been checked.
1404       ResourceTracker->reserveResources(MI);
1405       CurrentPacketMIs.push_back(MI);
1406     }
1407     return MII;
1408 }
1409
1410 //===----------------------------------------------------------------------===//
1411 //                         Public Constructor Functions
1412 //===----------------------------------------------------------------------===//
1413
1414 FunctionPass *llvm::createHexagonPacketizer() {
1415   return new HexagonPacketizer();
1416 }
1417