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