Fixed/added namespace ending comments using clang-tidy. NFC
[oota-llvm.git] / lib / Target / Hexagon / HexagonExpandCondsets.cpp
1 // Replace mux instructions with the corresponding legal instructions.
2 // It is meant to work post-SSA, but still on virtual registers. It was
3 // originally placed between register coalescing and machine instruction
4 // scheduler.
5 // In this place in the optimization sequence, live interval analysis had
6 // been performed, and the live intervals should be preserved. A large part
7 // of the code deals with preserving the liveness information.
8 //
9 // Liveness tracking aside, the main functionality of this pass is divided
10 // into two steps. The first step is to replace an instruction
11 //   vreg0 = C2_mux vreg0, vreg1, vreg2
12 // with a pair of conditional transfers
13 //   vreg0 = A2_tfrt vreg0, vreg1
14 //   vreg0 = A2_tfrf vreg0, vreg2
15 // It is the intention that the execution of this pass could be terminated
16 // after this step, and the code generated would be functionally correct.
17 //
18 // If the uses of the source values vreg1 and vreg2 are kills, and their
19 // definitions are predicable, then in the second step, the conditional
20 // transfers will then be rewritten as predicated instructions. E.g.
21 //   vreg0 = A2_or vreg1, vreg2
22 //   vreg3 = A2_tfrt vreg99, vreg0<kill>
23 // will be rewritten as
24 //   vreg3 = A2_port vreg99, vreg1, vreg2
25 //
26 // This replacement has two variants: "up" and "down". Consider this case:
27 //   vreg0 = A2_or vreg1, vreg2
28 //   ... [intervening instructions] ...
29 //   vreg3 = A2_tfrt vreg99, vreg0<kill>
30 // variant "up":
31 //   vreg3 = A2_port vreg99, vreg1, vreg2
32 //   ... [intervening instructions, vreg0->vreg3] ...
33 //   [deleted]
34 // variant "down":
35 //   [deleted]
36 //   ... [intervening instructions] ...
37 //   vreg3 = A2_port vreg99, vreg1, vreg2
38 //
39 // Both, one or none of these variants may be valid, and checks are made
40 // to rule out inapplicable variants.
41 //
42 // As an additional optimization, before either of the two steps above is
43 // executed, the pass attempts to coalesce the target register with one of
44 // the source registers, e.g. given an instruction
45 //   vreg3 = C2_mux vreg0, vreg1, vreg2
46 // vreg3 will be coalesced with either vreg1 or vreg2. If this succeeds,
47 // the instruction would then be (for example)
48 //   vreg3 = C2_mux vreg0, vreg3, vreg2
49 // and, under certain circumstances, this could result in only one predicated
50 // instruction:
51 //   vreg3 = A2_tfrf vreg0, vreg2
52 //
53
54 #define DEBUG_TYPE "expand-condsets"
55 #include "HexagonTargetMachine.h"
56
57 #include "llvm/CodeGen/Passes.h"
58 #include "llvm/CodeGen/LiveInterval.h"
59 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
60 #include "llvm/CodeGen/MachineFunction.h"
61 #include "llvm/CodeGen/MachineInstrBuilder.h"
62 #include "llvm/CodeGen/MachineRegisterInfo.h"
63 #include "llvm/Target/TargetInstrInfo.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Target/TargetRegisterInfo.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69
70 using namespace llvm;
71
72 static cl::opt<unsigned> OptTfrLimit("expand-condsets-tfr-limit",
73   cl::init(~0U), cl::Hidden, cl::desc("Max number of mux expansions"));
74 static cl::opt<unsigned> OptCoaLimit("expand-condsets-coa-limit",
75   cl::init(~0U), cl::Hidden, cl::desc("Max number of segment coalescings"));
76
77 namespace llvm {
78   void initializeHexagonExpandCondsetsPass(PassRegistry&);
79   FunctionPass *createHexagonExpandCondsets();
80 }
81
82 namespace {
83   class HexagonExpandCondsets : public MachineFunctionPass {
84   public:
85     static char ID;
86     HexagonExpandCondsets() :
87         MachineFunctionPass(ID), HII(0), TRI(0), MRI(0),
88         LIS(0), CoaLimitActive(false),
89         TfrLimitActive(false), CoaCounter(0), TfrCounter(0) {
90       if (OptCoaLimit.getPosition())
91         CoaLimitActive = true, CoaLimit = OptCoaLimit;
92       if (OptTfrLimit.getPosition())
93         TfrLimitActive = true, TfrLimit = OptTfrLimit;
94       initializeHexagonExpandCondsetsPass(*PassRegistry::getPassRegistry());
95     }
96
97     virtual const char *getPassName() const {
98       return "Hexagon Expand Condsets";
99     }
100     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101       AU.addRequired<LiveIntervals>();
102       AU.addPreserved<LiveIntervals>();
103       AU.addPreserved<SlotIndexes>();
104       MachineFunctionPass::getAnalysisUsage(AU);
105     }
106     virtual bool runOnMachineFunction(MachineFunction &MF);
107
108   private:
109     const HexagonInstrInfo *HII;
110     const TargetRegisterInfo *TRI;
111     MachineRegisterInfo *MRI;
112     LiveIntervals *LIS;
113
114     bool CoaLimitActive, TfrLimitActive;
115     unsigned CoaLimit, TfrLimit, CoaCounter, TfrCounter;
116
117     struct RegisterRef {
118       RegisterRef(const MachineOperand &Op) : Reg(Op.getReg()),
119           Sub(Op.getSubReg()) {}
120       RegisterRef(unsigned R = 0, unsigned S = 0) : Reg(R), Sub(S) {}
121       bool operator== (RegisterRef RR) const {
122         return Reg == RR.Reg && Sub == RR.Sub;
123       }
124       bool operator!= (RegisterRef RR) const { return !operator==(RR); }
125       unsigned Reg, Sub;
126     };
127
128     typedef DenseMap<unsigned,unsigned> ReferenceMap;
129     enum { Sub_Low = 0x1, Sub_High = 0x2, Sub_None = (Sub_Low | Sub_High) };
130     enum { Exec_Then = 0x10, Exec_Else = 0x20 };
131     unsigned getMaskForSub(unsigned Sub);
132     bool isCondset(const MachineInstr *MI);
133
134     void addRefToMap(RegisterRef RR, ReferenceMap &Map, unsigned Exec);
135     bool isRefInMap(RegisterRef, ReferenceMap &Map, unsigned Exec);
136
137     LiveInterval::iterator nextSegment(LiveInterval &LI, SlotIndex S);
138     LiveInterval::iterator prevSegment(LiveInterval &LI, SlotIndex S);
139     void makeDefined(unsigned Reg, SlotIndex S, bool SetDef);
140     void makeUndead(unsigned Reg, SlotIndex S);
141     void shrinkToUses(unsigned Reg, LiveInterval &LI);
142     void updateKillFlags(unsigned Reg, LiveInterval &LI);
143     void terminateSegment(LiveInterval::iterator LT, SlotIndex S,
144         LiveInterval &LI);
145     void addInstrToLiveness(MachineInstr *MI);
146     void removeInstrFromLiveness(MachineInstr *MI);
147
148     unsigned getCondTfrOpcode(const MachineOperand &SO, bool Cond);
149     MachineInstr *genTfrFor(MachineOperand &SrcOp, unsigned DstR,
150         unsigned DstSR, const MachineOperand &PredOp, bool Cond);
151     bool split(MachineInstr *MI);
152     bool splitInBlock(MachineBasicBlock &B);
153
154     bool isPredicable(MachineInstr *MI);
155     MachineInstr *getReachingDefForPred(RegisterRef RD,
156         MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond);
157     bool canMoveOver(MachineInstr *MI, ReferenceMap &Defs, ReferenceMap &Uses);
158     bool canMoveMemTo(MachineInstr *MI, MachineInstr *ToI, bool IsDown);
159     void predicateAt(RegisterRef RD, MachineInstr *MI,
160         MachineBasicBlock::iterator Where, unsigned PredR, bool Cond);
161     void renameInRange(RegisterRef RO, RegisterRef RN, unsigned PredR,
162         bool Cond, MachineBasicBlock::iterator First,
163         MachineBasicBlock::iterator Last);
164     bool predicate(MachineInstr *TfrI, bool Cond);
165     bool predicateInBlock(MachineBasicBlock &B);
166
167     void postprocessUndefImplicitUses(MachineBasicBlock &B);
168     void removeImplicitUses(MachineInstr *MI);
169     void removeImplicitUses(MachineBasicBlock &B);
170
171     bool isIntReg(RegisterRef RR, unsigned &BW);
172     bool isIntraBlocks(LiveInterval &LI);
173     bool coalesceRegisters(RegisterRef R1, RegisterRef R2);
174     bool coalesceSegments(MachineFunction &MF);
175   };
176 } // namespace
177
178 char HexagonExpandCondsets::ID = 0;
179
180
181 unsigned HexagonExpandCondsets::getMaskForSub(unsigned Sub) {
182   switch (Sub) {
183     case Hexagon::subreg_loreg:
184       return Sub_Low;
185     case Hexagon::subreg_hireg:
186       return Sub_High;
187     case Hexagon::NoSubRegister:
188       return Sub_None;
189   }
190   llvm_unreachable("Invalid subregister");
191 }
192
193
194 bool HexagonExpandCondsets::isCondset(const MachineInstr *MI) {
195   unsigned Opc = MI->getOpcode();
196   switch (Opc) {
197     case Hexagon::C2_mux:
198     case Hexagon::C2_muxii:
199     case Hexagon::C2_muxir:
200     case Hexagon::C2_muxri:
201     case Hexagon::MUX64_rr:
202         return true;
203       break;
204   }
205   return false;
206 }
207
208
209 void HexagonExpandCondsets::addRefToMap(RegisterRef RR, ReferenceMap &Map,
210       unsigned Exec) {
211   unsigned Mask = getMaskForSub(RR.Sub) | Exec;
212   ReferenceMap::iterator F = Map.find(RR.Reg);
213   if (F == Map.end())
214     Map.insert(std::make_pair(RR.Reg, Mask));
215   else
216     F->second |= Mask;
217 }
218
219
220 bool HexagonExpandCondsets::isRefInMap(RegisterRef RR, ReferenceMap &Map,
221       unsigned Exec) {
222   ReferenceMap::iterator F = Map.find(RR.Reg);
223   if (F == Map.end())
224     return false;
225   unsigned Mask = getMaskForSub(RR.Sub) | Exec;
226   if (Mask & F->second)
227     return true;
228   return false;
229 }
230
231
232 LiveInterval::iterator HexagonExpandCondsets::nextSegment(LiveInterval &LI,
233       SlotIndex S) {
234   for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
235     if (I->start >= S)
236       return I;
237   }
238   return LI.end();
239 }
240
241
242 LiveInterval::iterator HexagonExpandCondsets::prevSegment(LiveInterval &LI,
243       SlotIndex S) {
244   LiveInterval::iterator P = LI.end();
245   for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
246     if (I->end > S)
247       return P;
248     P = I;
249   }
250   return P;
251 }
252
253
254 /// Find the implicit use of register Reg in slot index S, and make sure
255 /// that the "defined" flag is set to SetDef. While the mux expansion is
256 /// going on, predicated instructions will have implicit uses of the
257 /// registers that are being defined. This is to keep any preceding
258 /// definitions live. If there is no preceding definition, the implicit
259 /// use will be marked as "undef", otherwise it will be "defined". This
260 /// function is used to update the flag.
261 void HexagonExpandCondsets::makeDefined(unsigned Reg, SlotIndex S,
262       bool SetDef) {
263   if (!S.isRegister())
264     return;
265   MachineInstr *MI = LIS->getInstructionFromIndex(S);
266   assert(MI && "Expecting instruction");
267   for (auto &Op : MI->operands()) {
268     if (!Op.isReg() || !Op.isUse() || Op.getReg() != Reg)
269       continue;
270     bool IsDef = !Op.isUndef();
271     if (Op.isImplicit() && IsDef != SetDef)
272       Op.setIsUndef(!SetDef);
273   }
274 }
275
276
277 void HexagonExpandCondsets::makeUndead(unsigned Reg, SlotIndex S) {
278   // If S is a block boundary, then there can still be a dead def reaching
279   // this point. Instead of traversing the CFG, queue start points of all
280   // live segments that begin with a register, and end at a block boundary.
281   // This may "resurrect" some truly dead definitions, but doing so is
282   // harmless.
283   SmallVector<MachineInstr*,8> Defs;
284   if (S.isBlock()) {
285     LiveInterval &LI = LIS->getInterval(Reg);
286     for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
287       if (!I->start.isRegister() || !I->end.isBlock())
288         continue;
289       MachineInstr *MI = LIS->getInstructionFromIndex(I->start);
290       Defs.push_back(MI);
291     }
292   } else if (S.isRegister()) {
293     MachineInstr *MI = LIS->getInstructionFromIndex(S);
294     Defs.push_back(MI);
295   }
296
297   for (unsigned i = 0, n = Defs.size(); i < n; ++i) {
298     MachineInstr *MI = Defs[i];
299     for (auto &Op : MI->operands()) {
300       if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
301         continue;
302       Op.setIsDead(false);
303     }
304   }
305 }
306
307
308 /// Shrink the segments in the live interval for a given register to the last
309 /// use before each subsequent def. Unlike LiveIntervals::shrinkToUses, this
310 /// function will not mark any definitions of Reg as dead. The reason for this
311 /// is that this function is used while a MUX instruction is being expanded,
312 /// or while a conditional copy is undergoing predication. During these
313 /// processes, there may be defs present in the instruction sequence that have
314 /// not yet been removed, or there may be missing uses that have not yet been
315 /// added. We want to utilize LiveIntervals::shrinkToUses as much as possible,
316 /// but since it does not extend any intervals that are too short, we need to
317 /// pre-emptively extend them here in anticipation of further changes.
318 void HexagonExpandCondsets::shrinkToUses(unsigned Reg, LiveInterval &LI) {
319   SmallVector<MachineInstr*,4> Deads;
320   LIS->shrinkToUses(&LI, &Deads);
321   // Need to undo the deadification made by "shrinkToUses". It's easier to
322   // do it here, since we have a list of all instructions that were just
323   // marked as dead.
324   for (unsigned i = 0, n = Deads.size(); i < n; ++i) {
325     MachineInstr *MI = Deads[i];
326     // Clear the "dead" flag.
327     for (auto &Op : MI->operands()) {
328       if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
329         continue;
330       Op.setIsDead(false);
331     }
332     // Extend the live segment to the beginning of the next one.
333     LiveInterval::iterator End = LI.end();
334     SlotIndex S = LIS->getInstructionIndex(MI).getRegSlot();
335     LiveInterval::iterator T = LI.FindSegmentContaining(S);
336     assert(T != End);
337     LiveInterval::iterator N = std::next(T);
338     if (N != End)
339       T->end = N->start;
340     else
341       T->end = LIS->getMBBEndIdx(MI->getParent());
342   }
343   updateKillFlags(Reg, LI);
344 }
345
346
347 /// Given an updated live interval LI for register Reg, update the kill flags
348 /// in instructions using Reg to reflect the liveness changes.
349 void HexagonExpandCondsets::updateKillFlags(unsigned Reg, LiveInterval &LI) {
350   MRI->clearKillFlags(Reg);
351   for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
352     SlotIndex EX = I->end;
353     if (!EX.isRegister())
354       continue;
355     MachineInstr *MI = LIS->getInstructionFromIndex(EX);
356     for (auto &Op : MI->operands()) {
357       if (!Op.isReg() || !Op.isUse() || Op.getReg() != Reg)
358         continue;
359       // Only set the kill flag on the first encountered use of Reg in this
360       // instruction.
361       Op.setIsKill(true);
362       break;
363     }
364   }
365 }
366
367
368 /// When adding a new instruction to liveness, the newly added definition
369 /// will start a new live segment. This may happen at a position that falls
370 /// within an existing live segment. In such case that live segment needs to
371 /// be truncated to make room for the new segment. Ultimately, the truncation
372 /// will occur at the last use, but for now the segment can be terminated
373 /// right at the place where the new segment will start. The segments will be
374 /// shrunk-to-uses later.
375 void HexagonExpandCondsets::terminateSegment(LiveInterval::iterator LT,
376       SlotIndex S, LiveInterval &LI) {
377   // Terminate the live segment pointed to by LT within a live interval LI.
378   if (LT == LI.end())
379     return;
380
381   VNInfo *OldVN = LT->valno;
382   SlotIndex EX = LT->end;
383   LT->end = S;
384   // If LT does not end at a block boundary, the termination is done.
385   if (!EX.isBlock())
386     return;
387
388   // If LT ended at a block boundary, it's possible that its value number
389   // is picked up at the beginning other blocks. Create a new value number
390   // and change such blocks to use it instead.
391   VNInfo *NewVN = 0;
392   for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
393     if (!I->start.isBlock() || I->valno != OldVN)
394       continue;
395     // Generate on-demand a new value number that is defined by the
396     // block beginning (i.e. -phi).
397     if (!NewVN)
398       NewVN = LI.getNextValue(I->start, LIS->getVNInfoAllocator());
399     I->valno = NewVN;
400   }
401 }
402
403
404 /// Add the specified instruction to live intervals. This function is used
405 /// to update the live intervals while the program code is being changed.
406 /// Neither the expansion of a MUX, nor the predication are atomic, and this
407 /// function is used to update the live intervals while these transformations
408 /// are being done.
409 void HexagonExpandCondsets::addInstrToLiveness(MachineInstr *MI) {
410   SlotIndex MX = LIS->isNotInMIMap(MI) ? LIS->InsertMachineInstrInMaps(MI)
411                                        : LIS->getInstructionIndex(MI);
412   DEBUG(dbgs() << "adding liveness info for instr\n  " << MX << "  " << *MI);
413
414   MX = MX.getRegSlot();
415   bool Predicated = HII->isPredicated(MI);
416   MachineBasicBlock *MB = MI->getParent();
417
418   // Strip all implicit uses from predicated instructions. They will be
419   // added again, according to the updated information.
420   if (Predicated)
421     removeImplicitUses(MI);
422
423   // For each def in MI we need to insert a new live segment starting at MX
424   // into the interval. If there already exists a live segment in the interval
425   // that contains MX, we need to terminate it at MX.
426   SmallVector<RegisterRef,2> Defs;
427   for (auto &Op : MI->operands())
428     if (Op.isReg() && Op.isDef())
429       Defs.push_back(RegisterRef(Op));
430
431   for (unsigned i = 0, n = Defs.size(); i < n; ++i) {
432     unsigned DefR = Defs[i].Reg;
433     LiveInterval &LID = LIS->getInterval(DefR);
434     DEBUG(dbgs() << "adding def " << PrintReg(DefR, TRI)
435                  << " with interval\n  " << LID << "\n");
436     // If MX falls inside of an existing live segment, terminate it.
437     LiveInterval::iterator LT = LID.FindSegmentContaining(MX);
438     if (LT != LID.end())
439       terminateSegment(LT, MX, LID);
440     DEBUG(dbgs() << "after terminating segment\n  " << LID << "\n");
441
442     // Create a new segment starting from MX.
443     LiveInterval::iterator P = prevSegment(LID, MX), N = nextSegment(LID, MX);
444     SlotIndex EX;
445     VNInfo *VN = LID.getNextValue(MX, LIS->getVNInfoAllocator());
446     if (N == LID.end()) {
447       // There is no live segment after MX. End this segment at the end of
448       // the block.
449       EX = LIS->getMBBEndIdx(MB);
450     } else {
451       // If the next segment starts at the block boundary, end the new segment
452       // at the boundary of the preceding block (i.e. the previous index).
453       // Otherwise, end the segment at the beginning of the next segment. In
454       // either case it will be "shrunk-to-uses" later.
455       EX = N->start.isBlock() ? N->start.getPrevIndex() : N->start;
456     }
457     if (Predicated) {
458       // Predicated instruction will have an implicit use of the defined
459       // register. This is necessary so that this definition will not make
460       // any previous definitions dead. If there are no previous live
461       // segments, still add the implicit use, but make it "undef".
462       // Because of the implicit use, the preceding definition is not
463       // dead. Mark is as such (if necessary).
464       MachineOperand ImpUse = MachineOperand::CreateReg(DefR, false, true);
465       ImpUse.setSubReg(Defs[i].Sub);
466       bool Undef = false;
467       if (P == LID.end())
468         Undef = true;
469       else {
470         // If the previous segment extends to the end of the previous block,
471         // the end index may actually be the beginning of this block. If
472         // the previous segment ends at a block boundary, move it back by one,
473         // to get the proper block for it.
474         SlotIndex PE = P->end.isBlock() ? P->end.getPrevIndex() : P->end;
475         MachineBasicBlock *PB = LIS->getMBBFromIndex(PE);
476         if (PB != MB && !LIS->isLiveInToMBB(LID, MB))
477           Undef = true;
478       }
479       if (!Undef) {
480         makeUndead(DefR, P->valno->def);
481         // We are adding a live use, so extend the previous segment to
482         // include it.
483         P->end = MX;
484       } else {
485         ImpUse.setIsUndef(true);
486       }
487
488       if (!MI->readsRegister(DefR))
489         MI->addOperand(ImpUse);
490       if (N != LID.end())
491         makeDefined(DefR, N->start, true);
492     }
493     LiveRange::Segment NR = LiveRange::Segment(MX, EX, VN);
494     LID.addSegment(NR);
495     DEBUG(dbgs() << "added a new segment " << NR << "\n  " << LID << "\n");
496     shrinkToUses(DefR, LID);
497     DEBUG(dbgs() << "updated imp-uses: " << *MI);
498     LID.verify();
499   }
500
501   // For each use in MI:
502   // - If there is no live segment that contains MX for the used register,
503   //   extend the previous one. Ignore implicit uses.
504   for (auto &Op : MI->operands()) {
505     if (!Op.isReg() || !Op.isUse() || Op.isImplicit() || Op.isUndef())
506       continue;
507     unsigned UseR = Op.getReg();
508     LiveInterval &LIU = LIS->getInterval(UseR);
509     // Find the last segment P that starts before MX.
510     LiveInterval::iterator P = LIU.FindSegmentContaining(MX);
511     if (P == LIU.end())
512       P = prevSegment(LIU, MX);
513
514     assert(P != LIU.end() && "MI uses undefined register?");
515     SlotIndex EX = P->end;
516     // If P contains MX, there is not much to do.
517     if (EX > MX) {
518       Op.setIsKill(false);
519       continue;
520     }
521     // Otherwise, extend P to "next(MX)".
522     P->end = MX.getNextIndex();
523     Op.setIsKill(true);
524     // Get the old "kill" instruction, and remove the kill flag.
525     if (MachineInstr *KI = LIS->getInstructionFromIndex(MX))
526       KI->clearRegisterKills(UseR, nullptr);
527     shrinkToUses(UseR, LIU);
528     LIU.verify();
529   }
530 }
531
532
533 /// Update the live interval information to reflect the removal of the given
534 /// instruction from the program. As with "addInstrToLiveness", this function
535 /// is called while the program code is being changed.
536 void HexagonExpandCondsets::removeInstrFromLiveness(MachineInstr *MI) {
537   SlotIndex MX = LIS->getInstructionIndex(MI).getRegSlot();
538   DEBUG(dbgs() << "removing instr\n  " << MX << "  " << *MI);
539
540   // For each def in MI:
541   // If MI starts a live segment, merge this segment with the previous segment.
542   //
543   for (auto &Op : MI->operands()) {
544     if (!Op.isReg() || !Op.isDef())
545       continue;
546     unsigned DefR = Op.getReg();
547     LiveInterval &LID = LIS->getInterval(DefR);
548     LiveInterval::iterator LT = LID.FindSegmentContaining(MX);
549     assert(LT != LID.end() && "Expecting live segments");
550     DEBUG(dbgs() << "removing def at " << MX << " of " << PrintReg(DefR, TRI)
551                  << " with interval\n  " << LID << "\n");
552     if (LT->start != MX)
553       continue;
554
555     VNInfo *MVN = LT->valno;
556     if (LT != LID.begin()) {
557       // If the current live segment is not the first, the task is easy. If
558       // the previous segment continues into the current block, extend it to
559       // the end of the current one, and merge the value numbers.
560       // Otherwise, remove the current segment, and make the end of it "undef".
561       LiveInterval::iterator P = std::prev(LT);
562       SlotIndex PE = P->end.isBlock() ? P->end.getPrevIndex() : P->end;
563       MachineBasicBlock *MB = MI->getParent();
564       MachineBasicBlock *PB = LIS->getMBBFromIndex(PE);
565       if (PB != MB && !LIS->isLiveInToMBB(LID, MB)) {
566         makeDefined(DefR, LT->end, false);
567         LID.removeSegment(*LT);
568       } else {
569         // Make the segments adjacent, so that merge-vn can also merge the
570         // segments.
571         P->end = LT->start;
572         makeUndead(DefR, P->valno->def);
573         LID.MergeValueNumberInto(MVN, P->valno);
574       }
575     } else {
576       LiveInterval::iterator N = std::next(LT);
577       LiveInterval::iterator RmB = LT, RmE = N;
578       while (N != LID.end()) {
579         // Iterate until the first register-based definition is found
580         // (i.e. skip all block-boundary entries).
581         LiveInterval::iterator Next = std::next(N);
582         if (N->start.isRegister()) {
583           makeDefined(DefR, N->start, false);
584           break;
585         }
586         if (N->end.isRegister()) {
587           makeDefined(DefR, N->end, false);
588           RmE = Next;
589           break;
590         }
591         RmE = Next;
592         N = Next;
593       }
594       // Erase the segments in one shot to avoid invalidating iterators.
595       LID.segments.erase(RmB, RmE);
596     }
597
598     bool VNUsed = false;
599     for (LiveInterval::iterator I = LID.begin(), E = LID.end(); I != E; ++I) {
600       if (I->valno != MVN)
601         continue;
602       VNUsed = true;
603       break;
604     }
605     if (!VNUsed)
606       MVN->markUnused();
607
608     DEBUG(dbgs() << "new interval: ");
609     if (!LID.empty()) {
610       DEBUG(dbgs() << LID << "\n");
611       LID.verify();
612     } else {
613       DEBUG(dbgs() << "<empty>\n");
614       LIS->removeInterval(DefR);
615     }
616   }
617
618   // For uses there is nothing to do. The intervals will be updated via
619   // shrinkToUses.
620   SmallVector<unsigned,4> Uses;
621   for (auto &Op : MI->operands()) {
622     if (!Op.isReg() || !Op.isUse())
623       continue;
624     unsigned R = Op.getReg();
625     if (!TargetRegisterInfo::isVirtualRegister(R))
626       continue;
627     Uses.push_back(R);
628   }
629   LIS->RemoveMachineInstrFromMaps(MI);
630   MI->eraseFromParent();
631   for (unsigned i = 0, n = Uses.size(); i < n; ++i) {
632     LiveInterval &LI = LIS->getInterval(Uses[i]);
633     shrinkToUses(Uses[i], LI);
634   }
635 }
636
637
638 /// Get the opcode for a conditional transfer of the value in SO (source
639 /// operand). The condition (true/false) is given in Cond.
640 unsigned HexagonExpandCondsets::getCondTfrOpcode(const MachineOperand &SO,
641       bool Cond) {
642   using namespace Hexagon;
643   if (SO.isReg()) {
644     unsigned PhysR;
645     RegisterRef RS = SO;
646     if (TargetRegisterInfo::isVirtualRegister(RS.Reg)) {
647       const TargetRegisterClass *VC = MRI->getRegClass(RS.Reg);
648       assert(VC->begin() != VC->end() && "Empty register class");
649       PhysR = *VC->begin();
650     } else {
651       assert(TargetRegisterInfo::isPhysicalRegister(RS.Reg));
652       PhysR = RS.Reg;
653     }
654     unsigned PhysS = (RS.Sub == 0) ? PhysR : TRI->getSubReg(PhysR, RS.Sub);
655     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysS);
656     switch (RC->getSize()) {
657       case 4:
658         return Cond ? A2_tfrt : A2_tfrf;
659       case 8:
660         return Cond ? A2_tfrpt : A2_tfrpf;
661     }
662     llvm_unreachable("Invalid register operand");
663   }
664   if (SO.isImm() || SO.isFPImm())
665     return Cond ? C2_cmoveit : C2_cmoveif;
666   llvm_unreachable("Unexpected source operand");
667 }
668
669
670 /// Generate a conditional transfer, copying the value SrcOp to the
671 /// destination register DstR:DstSR, and using the predicate register from
672 /// PredOp. The Cond argument specifies whether the predicate is to be
673 /// if(PredOp), or if(!PredOp).
674 MachineInstr *HexagonExpandCondsets::genTfrFor(MachineOperand &SrcOp,
675       unsigned DstR, unsigned DstSR, const MachineOperand &PredOp, bool Cond) {
676   MachineInstr *MI = SrcOp.getParent();
677   MachineBasicBlock &B = *MI->getParent();
678   MachineBasicBlock::iterator At = MI;
679   DebugLoc DL = MI->getDebugLoc();
680
681   // Don't avoid identity copies here (i.e. if the source and the destination
682   // are the same registers). It is actually better to generate them here,
683   // since this would cause the copy to potentially be predicated in the next
684   // step. The predication will remove such a copy if it is unable to
685   /// predicate.
686
687   unsigned Opc = getCondTfrOpcode(SrcOp, Cond);
688   MachineInstr *TfrI = BuildMI(B, At, DL, HII->get(Opc))
689         .addReg(DstR, RegState::Define, DstSR)
690         .addOperand(PredOp)
691         .addOperand(SrcOp);
692   // We don't want any kills yet.
693   TfrI->clearKillInfo();
694   DEBUG(dbgs() << "created an initial copy: " << *TfrI);
695   return TfrI;
696 }
697
698
699 /// Replace a MUX instruction MI with a pair A2_tfrt/A2_tfrf. This function
700 /// performs all necessary changes to complete the replacement.
701 bool HexagonExpandCondsets::split(MachineInstr *MI) {
702   if (TfrLimitActive) {
703     if (TfrCounter >= TfrLimit)
704       return false;
705     TfrCounter++;
706   }
707   DEBUG(dbgs() << "\nsplitting BB#" << MI->getParent()->getNumber()
708                << ": " << *MI);
709   MachineOperand &MD = MI->getOperand(0); // Definition
710   MachineOperand &MP = MI->getOperand(1); // Predicate register
711   assert(MD.isDef());
712   unsigned DR = MD.getReg(), DSR = MD.getSubReg();
713
714   // First, create the two invididual conditional transfers, and add each
715   // of them to the live intervals information. Do that first and then remove
716   // the old instruction from live intervals.
717   if (MachineInstr *TfrT = genTfrFor(MI->getOperand(2), DR, DSR, MP, true))
718     addInstrToLiveness(TfrT);
719   if (MachineInstr *TfrF = genTfrFor(MI->getOperand(3), DR, DSR, MP, false))
720     addInstrToLiveness(TfrF);
721   removeInstrFromLiveness(MI);
722
723   return true;
724 }
725
726
727 /// Split all MUX instructions in the given block into pairs of contitional
728 /// transfers.
729 bool HexagonExpandCondsets::splitInBlock(MachineBasicBlock &B) {
730   bool Changed = false;
731   MachineBasicBlock::iterator I, E, NextI;
732   for (I = B.begin(), E = B.end(); I != E; I = NextI) {
733     NextI = std::next(I);
734     if (isCondset(I))
735       Changed |= split(I);
736   }
737   return Changed;
738 }
739
740
741 bool HexagonExpandCondsets::isPredicable(MachineInstr *MI) {
742   if (HII->isPredicated(MI) || !HII->isPredicable(MI))
743     return false;
744   if (MI->hasUnmodeledSideEffects() || MI->mayStore())
745     return false;
746   // Reject instructions with multiple defs (e.g. post-increment loads).
747   bool HasDef = false;
748   for (auto &Op : MI->operands()) {
749     if (!Op.isReg() || !Op.isDef())
750       continue;
751     if (HasDef)
752       return false;
753     HasDef = true;
754   }
755   for (auto &Mo : MI->memoperands())
756     if (Mo->isVolatile())
757       return false;
758   return true;
759 }
760
761
762 /// Find the reaching definition for a predicated use of RD. The RD is used
763 /// under the conditions given by PredR and Cond, and this function will ignore
764 /// definitions that set RD under the opposite conditions.
765 MachineInstr *HexagonExpandCondsets::getReachingDefForPred(RegisterRef RD,
766       MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond) {
767   MachineBasicBlock &B = *UseIt->getParent();
768   MachineBasicBlock::iterator I = UseIt, S = B.begin();
769   if (I == S)
770     return 0;
771
772   bool PredValid = true;
773   do {
774     --I;
775     MachineInstr *MI = &*I;
776     // Check if this instruction can be ignored, i.e. if it is predicated
777     // on the complementary condition.
778     if (PredValid && HII->isPredicated(MI)) {
779       if (MI->readsRegister(PredR) && (Cond != HII->isPredicatedTrue(MI)))
780         continue;
781     }
782
783     // Check the defs. If the PredR is defined, invalidate it. If RD is
784     // defined, return the instruction or 0, depending on the circumstances.
785     for (auto &Op : MI->operands()) {
786       if (!Op.isReg() || !Op.isDef())
787         continue;
788       RegisterRef RR = Op;
789       if (RR.Reg == PredR) {
790         PredValid = false;
791         continue;
792       }
793       if (RR.Reg != RD.Reg)
794         continue;
795       // If the "Reg" part agrees, there is still the subregister to check.
796       // If we are looking for vreg1:loreg, we can skip vreg1:hireg, but
797       // not vreg1 (w/o subregisters).
798       if (RR.Sub == RD.Sub)
799         return MI;
800       if (RR.Sub == 0 || RD.Sub == 0)
801         return 0;
802       // We have different subregisters, so we can continue looking.
803     }
804   } while (I != S);
805
806   return 0;
807 }
808
809
810 /// Check if the instruction MI can be safely moved over a set of instructions
811 /// whose side-effects (in terms of register defs and uses) are expressed in
812 /// the maps Defs and Uses. These maps reflect the conditional defs and uses
813 /// that depend on the same predicate register to allow moving instructions
814 /// over instructions predicated on the opposite condition.
815 bool HexagonExpandCondsets::canMoveOver(MachineInstr *MI, ReferenceMap &Defs,
816       ReferenceMap &Uses) {
817   // In order to be able to safely move MI over instructions that define
818   // "Defs" and use "Uses", no def operand from MI can be defined or used
819   // and no use operand can be defined.
820   for (auto &Op : MI->operands()) {
821     if (!Op.isReg())
822       continue;
823     RegisterRef RR = Op;
824     // For physical register we would need to check register aliases, etc.
825     // and we don't want to bother with that. It would be of little value
826     // before the actual register rewriting (from virtual to physical).
827     if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
828       return false;
829     // No redefs for any operand.
830     if (isRefInMap(RR, Defs, Exec_Then))
831       return false;
832     // For defs, there cannot be uses.
833     if (Op.isDef() && isRefInMap(RR, Uses, Exec_Then))
834       return false;
835   }
836   return true;
837 }
838
839
840 /// Check if the instruction accessing memory (TheI) can be moved to the
841 /// location ToI.
842 bool HexagonExpandCondsets::canMoveMemTo(MachineInstr *TheI, MachineInstr *ToI,
843       bool IsDown) {
844   bool IsLoad = TheI->mayLoad(), IsStore = TheI->mayStore();
845   if (!IsLoad && !IsStore)
846     return true;
847   if (HII->areMemAccessesTriviallyDisjoint(TheI, ToI))
848     return true;
849   if (TheI->hasUnmodeledSideEffects())
850     return false;
851
852   MachineBasicBlock::iterator StartI = IsDown ? TheI : ToI;
853   MachineBasicBlock::iterator EndI = IsDown ? ToI : TheI;
854   bool Ordered = TheI->hasOrderedMemoryRef();
855
856   // Search for aliased memory reference in (StartI, EndI).
857   for (MachineBasicBlock::iterator I = std::next(StartI); I != EndI; ++I) {
858     MachineInstr *MI = &*I;
859     if (MI->hasUnmodeledSideEffects())
860       return false;
861     bool L = MI->mayLoad(), S = MI->mayStore();
862     if (!L && !S)
863       continue;
864     if (Ordered && MI->hasOrderedMemoryRef())
865       return false;
866
867     bool Conflict = (L && IsStore) || S;
868     if (Conflict)
869       return false;
870   }
871   return true;
872 }
873
874
875 /// Generate a predicated version of MI (where the condition is given via
876 /// PredR and Cond) at the point indicated by Where.
877 void HexagonExpandCondsets::predicateAt(RegisterRef RD, MachineInstr *MI,
878       MachineBasicBlock::iterator Where, unsigned PredR, bool Cond) {
879   // The problem with updating live intervals is that we can move one def
880   // past another def. In particular, this can happen when moving an A2_tfrt
881   // over an A2_tfrf defining the same register. From the point of view of
882   // live intervals, these two instructions are two separate definitions,
883   // and each one starts another live segment. LiveIntervals's "handleMove"
884   // does not allow such moves, so we need to handle it ourselves. To avoid
885   // invalidating liveness data while we are using it, the move will be
886   // implemented in 4 steps: (1) add a clone of the instruction MI at the
887   // target location, (2) update liveness, (3) delete the old instruction,
888   // and (4) update liveness again.
889
890   MachineBasicBlock &B = *MI->getParent();
891   DebugLoc DL = Where->getDebugLoc();  // "Where" points to an instruction.
892   unsigned Opc = MI->getOpcode();
893   unsigned PredOpc = HII->getCondOpcode(Opc, !Cond);
894   MachineInstrBuilder MB = BuildMI(B, Where, DL, HII->get(PredOpc));
895   unsigned Ox = 0, NP = MI->getNumOperands();
896   // Skip all defs from MI first.
897   while (Ox < NP) {
898     MachineOperand &MO = MI->getOperand(Ox);
899     if (!MO.isReg() || !MO.isDef())
900       break;
901     Ox++;
902   }
903   // Add the new def, then the predicate register, then the rest of the
904   // operands.
905   MB.addReg(RD.Reg, RegState::Define, RD.Sub);
906   MB.addReg(PredR);
907   while (Ox < NP) {
908     MachineOperand &MO = MI->getOperand(Ox);
909     if (!MO.isReg() || !MO.isImplicit())
910       MB.addOperand(MO);
911     Ox++;
912   }
913
914   MachineFunction &MF = *B.getParent();
915   MachineInstr::mmo_iterator I = MI->memoperands_begin();
916   unsigned NR = std::distance(I, MI->memoperands_end());
917   MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(NR);
918   for (unsigned i = 0; i < NR; ++i)
919     MemRefs[i] = *I++;
920   MB.setMemRefs(MemRefs, MemRefs+NR);
921
922   MachineInstr *NewI = MB;
923   NewI->clearKillInfo();
924   addInstrToLiveness(NewI);
925 }
926
927
928 /// In the range [First, Last], rename all references to the "old" register RO
929 /// to the "new" register RN, but only in instructions predicated on the given
930 /// condition.
931 void HexagonExpandCondsets::renameInRange(RegisterRef RO, RegisterRef RN,
932       unsigned PredR, bool Cond, MachineBasicBlock::iterator First,
933       MachineBasicBlock::iterator Last) {
934   MachineBasicBlock::iterator End = std::next(Last);
935   for (MachineBasicBlock::iterator I = First; I != End; ++I) {
936     MachineInstr *MI = &*I;
937     // Do not touch instructions that are not predicated, or are predicated
938     // on the opposite condition.
939     if (!HII->isPredicated(MI))
940       continue;
941     if (!MI->readsRegister(PredR) || (Cond != HII->isPredicatedTrue(MI)))
942       continue;
943
944     for (auto &Op : MI->operands()) {
945       if (!Op.isReg() || RO != RegisterRef(Op))
946         continue;
947       Op.setReg(RN.Reg);
948       Op.setSubReg(RN.Sub);
949       // In practice, this isn't supposed to see any defs.
950       assert(!Op.isDef() && "Not expecting a def");
951     }
952   }
953 }
954
955
956 /// For a given conditional copy, predicate the definition of the source of
957 /// the copy under the given condition (using the same predicate register as
958 /// the copy).
959 bool HexagonExpandCondsets::predicate(MachineInstr *TfrI, bool Cond) {
960   // TfrI - A2_tfr[tf] Instruction (not A2_tfrsi).
961   unsigned Opc = TfrI->getOpcode();
962   (void)Opc;
963   assert(Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf);
964   DEBUG(dbgs() << "\nattempt to predicate if-" << (Cond ? "true" : "false")
965                << ": " << *TfrI);
966
967   MachineOperand &MD = TfrI->getOperand(0);
968   MachineOperand &MP = TfrI->getOperand(1);
969   MachineOperand &MS = TfrI->getOperand(2);
970   // The source operand should be a <kill>. This is not strictly necessary,
971   // but it makes things a lot simpler. Otherwise, we would need to rename
972   // some registers, which would complicate the transformation considerably.
973   if (!MS.isKill())
974     return false;
975
976   RegisterRef RT(MS);
977   unsigned PredR = MP.getReg();
978   MachineInstr *DefI = getReachingDefForPred(RT, TfrI, PredR, Cond);
979   if (!DefI || !isPredicable(DefI))
980     return false;
981
982   DEBUG(dbgs() << "Source def: " << *DefI);
983
984   // Collect the information about registers defined and used between the
985   // DefI and the TfrI.
986   // Map: reg -> bitmask of subregs
987   ReferenceMap Uses, Defs;
988   MachineBasicBlock::iterator DefIt = DefI, TfrIt = TfrI;
989
990   // Check if the predicate register is valid between DefI and TfrI.
991   // If it is, we can then ignore instructions predicated on the negated
992   // conditions when collecting def and use information.
993   bool PredValid = true;
994   for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
995     if (!I->modifiesRegister(PredR, 0))
996       continue;
997     PredValid = false;
998     break;
999   }
1000
1001   for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
1002     MachineInstr *MI = &*I;
1003     // If this instruction is predicated on the same register, it could
1004     // potentially be ignored.
1005     // By default assume that the instruction executes on the same condition
1006     // as TfrI (Exec_Then), and also on the opposite one (Exec_Else).
1007     unsigned Exec = Exec_Then | Exec_Else;
1008     if (PredValid && HII->isPredicated(MI) && MI->readsRegister(PredR))
1009       Exec = (Cond == HII->isPredicatedTrue(MI)) ? Exec_Then : Exec_Else;
1010
1011     for (auto &Op : MI->operands()) {
1012       if (!Op.isReg())
1013         continue;
1014       // We don't want to deal with physical registers. The reason is that
1015       // they can be aliased with other physical registers. Aliased virtual
1016       // registers must share the same register number, and can only differ
1017       // in the subregisters, which we are keeping track of. Physical
1018       // registers ters no longer have subregisters---their super- and
1019       // subregisters are other physical registers, and we are not checking
1020       // that.
1021       RegisterRef RR = Op;
1022       if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
1023         return false;
1024
1025       ReferenceMap &Map = Op.isDef() ? Defs : Uses;
1026       addRefToMap(RR, Map, Exec);
1027     }
1028   }
1029
1030   // The situation:
1031   //   RT = DefI
1032   //   ...
1033   //   RD = TfrI ..., RT
1034
1035   // If the register-in-the-middle (RT) is used or redefined between
1036   // DefI and TfrI, we may not be able proceed with this transformation.
1037   // We can ignore a def that will not execute together with TfrI, and a
1038   // use that will. If there is such a use (that does execute together with
1039   // TfrI), we will not be able to move DefI down. If there is a use that
1040   // executed if TfrI's condition is false, then RT must be available
1041   // unconditionally (cannot be predicated).
1042   // Essentially, we need to be able to rename RT to RD in this segment.
1043   if (isRefInMap(RT, Defs, Exec_Then) || isRefInMap(RT, Uses, Exec_Else))
1044     return false;
1045   RegisterRef RD = MD;
1046   // If the predicate register is defined between DefI and TfrI, the only
1047   // potential thing to do would be to move the DefI down to TfrI, and then
1048   // predicate. The reaching def (DefI) must be movable down to the location
1049   // of the TfrI.
1050   // If the target register of the TfrI (RD) is not used or defined between
1051   // DefI and TfrI, consider moving TfrI up to DefI.
1052   bool CanUp =   canMoveOver(TfrI, Defs, Uses);
1053   bool CanDown = canMoveOver(DefI, Defs, Uses);
1054   // The TfrI does not access memory, but DefI could. Check if it's safe
1055   // to move DefI down to TfrI.
1056   if (DefI->mayLoad() || DefI->mayStore())
1057     if (!canMoveMemTo(DefI, TfrI, true))
1058       CanDown = false;
1059
1060   DEBUG(dbgs() << "Can move up: " << (CanUp ? "yes" : "no")
1061                << ", can move down: " << (CanDown ? "yes\n" : "no\n"));
1062   MachineBasicBlock::iterator PastDefIt = std::next(DefIt);
1063   if (CanUp)
1064     predicateAt(RD, DefI, PastDefIt, PredR, Cond);
1065   else if (CanDown)
1066     predicateAt(RD, DefI, TfrIt, PredR, Cond);
1067   else
1068     return false;
1069
1070   if (RT != RD)
1071     renameInRange(RT, RD, PredR, Cond, PastDefIt, TfrIt);
1072
1073   // Delete the user of RT first (it should work either way, but this order
1074   // of deleting is more natural).
1075   removeInstrFromLiveness(TfrI);
1076   removeInstrFromLiveness(DefI);
1077   return true;
1078 }
1079
1080
1081 /// Predicate all cases of conditional copies in the specified block.
1082 bool HexagonExpandCondsets::predicateInBlock(MachineBasicBlock &B) {
1083   bool Changed = false;
1084   MachineBasicBlock::iterator I, E, NextI;
1085   for (I = B.begin(), E = B.end(); I != E; I = NextI) {
1086     NextI = std::next(I);
1087     unsigned Opc = I->getOpcode();
1088     if (Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf) {
1089       bool Done = predicate(I, (Opc == Hexagon::A2_tfrt));
1090       if (!Done) {
1091         // If we didn't predicate I, we may need to remove it in case it is
1092         // an "identity" copy, e.g.  vreg1 = A2_tfrt vreg2, vreg1.
1093         if (RegisterRef(I->getOperand(0)) == RegisterRef(I->getOperand(2)))
1094           removeInstrFromLiveness(I);
1095       }
1096       Changed |= Done;
1097     }
1098   }
1099   return Changed;
1100 }
1101
1102
1103 void HexagonExpandCondsets::removeImplicitUses(MachineInstr *MI) {
1104   for (unsigned i = MI->getNumOperands(); i > 0; --i) {
1105     MachineOperand &MO = MI->getOperand(i-1);
1106     if (MO.isReg() && MO.isUse() && MO.isImplicit())
1107       MI->RemoveOperand(i-1);
1108   }
1109 }
1110
1111
1112 void HexagonExpandCondsets::removeImplicitUses(MachineBasicBlock &B) {
1113   for (MachineBasicBlock::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1114     MachineInstr *MI = &*I;
1115     if (HII->isPredicated(MI))
1116       removeImplicitUses(MI);
1117   }
1118 }
1119
1120
1121 void HexagonExpandCondsets::postprocessUndefImplicitUses(MachineBasicBlock &B) {
1122   // Implicit uses that are "undef" are only meaningful (outside of the
1123   // internals of this pass) when the instruction defines a subregister,
1124   // and the implicit-undef use applies to the defined register. In such
1125   // cases, the proper way to record the information in the IR is to mark
1126   // the definition as "undef", which will be interpreted as "read-undef".
1127   typedef SmallSet<unsigned,2> RegisterSet;
1128   for (MachineBasicBlock::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1129     MachineInstr *MI = &*I;
1130     RegisterSet Undefs;
1131     for (unsigned i = MI->getNumOperands(); i > 0; --i) {
1132       MachineOperand &MO = MI->getOperand(i-1);
1133       if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.isUndef()) {
1134         MI->RemoveOperand(i-1);
1135         Undefs.insert(MO.getReg());
1136       }
1137     }
1138     for (auto &Op : MI->operands()) {
1139       if (!Op.isReg() || !Op.isDef() || !Op.getSubReg())
1140         continue;
1141       if (Undefs.count(Op.getReg()))
1142         Op.setIsUndef(true);
1143     }
1144   }
1145 }
1146
1147
1148 bool HexagonExpandCondsets::isIntReg(RegisterRef RR, unsigned &BW) {
1149   if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
1150     return false;
1151   const TargetRegisterClass *RC = MRI->getRegClass(RR.Reg);
1152   if (RC == &Hexagon::IntRegsRegClass) {
1153     BW = 32;
1154     return true;
1155   }
1156   if (RC == &Hexagon::DoubleRegsRegClass) {
1157     BW = (RR.Sub != 0) ? 32 : 64;
1158     return true;
1159   }
1160   return false;
1161 }
1162
1163
1164 bool HexagonExpandCondsets::isIntraBlocks(LiveInterval &LI) {
1165   for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
1166     LiveRange::Segment &LR = *I;
1167     // Range must start at a register...
1168     if (!LR.start.isRegister())
1169       return false;
1170     // ...and end in a register or in a dead slot.
1171     if (!LR.end.isRegister() && !LR.end.isDead())
1172       return false;
1173   }
1174   return true;
1175 }
1176
1177
1178 bool HexagonExpandCondsets::coalesceRegisters(RegisterRef R1, RegisterRef R2) {
1179   if (CoaLimitActive) {
1180     if (CoaCounter >= CoaLimit)
1181       return false;
1182     CoaCounter++;
1183   }
1184   unsigned BW1, BW2;
1185   if (!isIntReg(R1, BW1) || !isIntReg(R2, BW2) || BW1 != BW2)
1186     return false;
1187   if (MRI->isLiveIn(R1.Reg))
1188     return false;
1189   if (MRI->isLiveIn(R2.Reg))
1190     return false;
1191
1192   LiveInterval &L1 = LIS->getInterval(R1.Reg);
1193   LiveInterval &L2 = LIS->getInterval(R2.Reg);
1194   bool Overlap = L1.overlaps(L2);
1195
1196   DEBUG(dbgs() << "compatible registers: ("
1197                << (Overlap ? "overlap" : "disjoint") << ")\n  "
1198                << PrintReg(R1.Reg, TRI, R1.Sub) << "  " << L1 << "\n  "
1199                << PrintReg(R2.Reg, TRI, R2.Sub) << "  " << L2 << "\n");
1200   if (R1.Sub || R2.Sub)
1201     return false;
1202   if (Overlap)
1203     return false;
1204
1205   // Coalescing could have a negative impact on scheduling, so try to limit
1206   // to some reasonable extent. Only consider coalescing segments, when one
1207   // of them does not cross basic block boundaries.
1208   if (!isIntraBlocks(L1) && !isIntraBlocks(L2))
1209     return false;
1210
1211   MRI->replaceRegWith(R2.Reg, R1.Reg);
1212
1213   // Move all live segments from L2 to L1.
1214   typedef DenseMap<VNInfo*,VNInfo*> ValueInfoMap;
1215   ValueInfoMap VM;
1216   for (LiveInterval::iterator I = L2.begin(), E = L2.end(); I != E; ++I) {
1217     VNInfo *NewVN, *OldVN = I->valno;
1218     ValueInfoMap::iterator F = VM.find(OldVN);
1219     if (F == VM.end()) {
1220       NewVN = L1.getNextValue(I->valno->def, LIS->getVNInfoAllocator());
1221       VM.insert(std::make_pair(OldVN, NewVN));
1222     } else {
1223       NewVN = F->second;
1224     }
1225     L1.addSegment(LiveRange::Segment(I->start, I->end, NewVN));
1226   }
1227   while (L2.begin() != L2.end())
1228     L2.removeSegment(*L2.begin());
1229
1230   updateKillFlags(R1.Reg, L1);
1231   DEBUG(dbgs() << "coalesced: " << L1 << "\n");
1232   L1.verify();
1233
1234   return true;
1235 }
1236
1237
1238 /// Attempt to coalesce one of the source registers to a MUX intruction with
1239 /// the destination register. This could lead to having only one predicated
1240 /// instruction in the end instead of two.
1241 bool HexagonExpandCondsets::coalesceSegments(MachineFunction &MF) {
1242   SmallVector<MachineInstr*,16> Condsets;
1243   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1244     MachineBasicBlock &B = *I;
1245     for (MachineBasicBlock::iterator J = B.begin(), F = B.end(); J != F; ++J) {
1246       MachineInstr *MI = &*J;
1247       if (!isCondset(MI))
1248         continue;
1249       MachineOperand &S1 = MI->getOperand(2), &S2 = MI->getOperand(3);
1250       if (!S1.isReg() && !S2.isReg())
1251         continue;
1252       Condsets.push_back(MI);
1253     }
1254   }
1255
1256   bool Changed = false;
1257   for (unsigned i = 0, n = Condsets.size(); i < n; ++i) {
1258     MachineInstr *CI = Condsets[i];
1259     RegisterRef RD = CI->getOperand(0);
1260     RegisterRef RP = CI->getOperand(1);
1261     MachineOperand &S1 = CI->getOperand(2), &S2 = CI->getOperand(3);
1262     bool Done = false;
1263     // Consider this case:
1264     //   vreg1 = instr1 ...
1265     //   vreg2 = instr2 ...
1266     //   vreg0 = C2_mux ..., vreg1, vreg2
1267     // If vreg0 was coalesced with vreg1, we could end up with the following
1268     // code:
1269     //   vreg0 = instr1 ...
1270     //   vreg2 = instr2 ...
1271     //   vreg0 = A2_tfrf ..., vreg2
1272     // which will later become:
1273     //   vreg0 = instr1 ...
1274     //   vreg0 = instr2_cNotPt ...
1275     // i.e. there will be an unconditional definition (instr1) of vreg0
1276     // followed by a conditional one. The output dependency was there before
1277     // and it unavoidable, but if instr1 is predicable, we will no longer be
1278     // able to predicate it here.
1279     // To avoid this scenario, don't coalesce the destination register with
1280     // a source register that is defined by a predicable instruction.
1281     if (S1.isReg()) {
1282       RegisterRef RS = S1;
1283       MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, true);
1284       if (!RDef || !HII->isPredicable(RDef))
1285         Done = coalesceRegisters(RD, RegisterRef(S1));
1286     }
1287     if (!Done && S2.isReg()) {
1288       RegisterRef RS = S2;
1289       MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, false);
1290       if (!RDef || !HII->isPredicable(RDef))
1291         Done = coalesceRegisters(RD, RegisterRef(S2));
1292     }
1293     Changed |= Done;
1294   }
1295   return Changed;
1296 }
1297
1298
1299 bool HexagonExpandCondsets::runOnMachineFunction(MachineFunction &MF) {
1300   HII = static_cast<const HexagonInstrInfo*>(MF.getSubtarget().getInstrInfo());
1301   TRI = MF.getSubtarget().getRegisterInfo();
1302   LIS = &getAnalysis<LiveIntervals>();
1303   MRI = &MF.getRegInfo();
1304
1305   bool Changed = false;
1306
1307   // Try to coalesce the target of a mux with one of its sources.
1308   // This could eliminate a register copy in some circumstances.
1309   Changed |= coalesceSegments(MF);
1310
1311   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1312     // First, simply split all muxes into a pair of conditional transfers
1313     // and update the live intervals to reflect the new arrangement.
1314     // This is done mainly to make the live interval update simpler, than it
1315     // would be while trying to predicate instructions at the same time.
1316     Changed |= splitInBlock(*I);
1317     // Traverse all blocks and collapse predicable instructions feeding
1318     // conditional transfers into predicated instructions.
1319     // Walk over all the instructions again, so we may catch pre-existing
1320     // cases that were not created in the previous step.
1321     Changed |= predicateInBlock(*I);
1322   }
1323
1324   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
1325     postprocessUndefImplicitUses(*I);
1326   return Changed;
1327 }
1328
1329
1330 //===----------------------------------------------------------------------===//
1331 //                         Public Constructor Functions
1332 //===----------------------------------------------------------------------===//
1333
1334 static void initializePassOnce(PassRegistry &Registry) {
1335   const char *Name = "Hexagon Expand Condsets";
1336   PassInfo *PI = new PassInfo(Name, "expand-condsets",
1337         &HexagonExpandCondsets::ID, 0, false, false);
1338   Registry.registerPass(*PI, true);
1339 }
1340
1341 void llvm::initializeHexagonExpandCondsetsPass(PassRegistry &Registry) {
1342   CALL_ONCE_INITIALIZATION(initializePassOnce)
1343 }
1344
1345
1346 FunctionPass *llvm::createHexagonExpandCondsets() {
1347   return new HexagonExpandCondsets();
1348 }