LLVM 24.0.0git
HexagonExpandCondsets.cpp
Go to the documentation of this file.
1//===- HexagonExpandCondsets.cpp ------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// Replace mux instructions with the corresponding legal instructions.
10// It is meant to work post-SSA, but still on virtual registers. It was
11// originally placed between register coalescing and machine instruction
12// scheduler.
13// In this place in the optimization sequence, live interval analysis had
14// been performed, and the live intervals should be preserved. A large part
15// of the code deals with preserving the liveness information.
16//
17// Liveness tracking aside, the main functionality of this pass is divided
18// into two steps. The first step is to replace an instruction
19// %0 = C2_mux %1, %2, %3
20// with a pair of conditional transfers
21// %0 = A2_tfrt %1, %2
22// %0 = A2_tfrf %1, %3
23// It is the intention that the execution of this pass could be terminated
24// after this step, and the code generated would be functionally correct.
25//
26// If the uses of the source values %1 and %2 are kills, and their
27// definitions are predicable, then in the second step, the conditional
28// transfers will then be rewritten as predicated instructions. E.g.
29// %0 = A2_or %1, %2
30// %3 = A2_tfrt %99, killed %0
31// will be rewritten as
32// %3 = A2_port %99, %1, %2
33//
34// This replacement has two variants: "up" and "down". Consider this case:
35// %0 = A2_or %1, %2
36// ... [intervening instructions] ...
37// %3 = A2_tfrt %99, killed %0
38// variant "up":
39// %3 = A2_port %99, %1, %2
40// ... [intervening instructions, %0->vreg3] ...
41// [deleted]
42// variant "down":
43// [deleted]
44// ... [intervening instructions] ...
45// %3 = A2_port %99, %1, %2
46//
47// Both, one or none of these variants may be valid, and checks are made
48// to rule out inapplicable variants.
49//
50// As an additional optimization, before either of the two steps above is
51// executed, the pass attempts to coalesce the target register with one of
52// the source registers, e.g. given an instruction
53// %3 = C2_mux %0, %1, %2
54// %3 will be coalesced with either %1 or %2. If this succeeds,
55// the instruction would then be (for example)
56// %3 = C2_mux %0, %3, %2
57// and, under certain circumstances, this could result in only one predicated
58// instruction:
59// %3 = A2_tfrf %0, %2
60//
61
62// Splitting a definition of a register into two predicated transfers
63// creates a complication in liveness tracking. Live interval computation
64// will see both instructions as actual definitions, and will mark the
65// first one as dead. The definition is not actually dead, and this
66// situation will need to be fixed. For example:
67// dead %1 = A2_tfrt ... ; marked as dead
68// %1 = A2_tfrf ...
69//
70// Since any of the individual predicated transfers may end up getting
71// removed (in case it is an identity copy), some pre-existing def may
72// be marked as dead after live interval recomputation:
73// dead %1 = ... ; marked as dead
74// ...
75// %1 = A2_tfrf ... ; if A2_tfrt is removed
76// This case happens if %1 was used as a source in A2_tfrt, which means
77// that is it actually live at the A2_tfrf, and so the now dead definition
78// of %1 will need to be updated to non-dead at some point.
79//
80// This issue could be remedied by adding implicit uses to the predicated
81// transfers, but this will create a problem with subsequent predication,
82// since the transfers will no longer be possible to reorder. To avoid
83// that, the initial splitting will not add any implicit uses. These
84// implicit uses will be added later, after predication. The extra price,
85// however, is that finding the locations where the implicit uses need
86// to be added, and updating the live ranges will be more involved.
87
88#include "Hexagon.h"
89#include "HexagonInstrInfo.h"
90#include "HexagonRegisterInfo.h"
91#include "llvm/ADT/DenseMap.h"
92#include "llvm/ADT/SetVector.h"
95#include "llvm/ADT/StringRef.h"
109#include "llvm/IR/DebugLoc.h"
110#include "llvm/IR/Function.h"
112#include "llvm/MC/LaneBitmask.h"
113#include "llvm/Pass.h"
115#include "llvm/Support/Debug.h"
118#include <cassert>
119#include <iterator>
120#include <map>
121#include <set>
122#include <utility>
123
124#define DEBUG_TYPE "expand-condsets"
125
126using namespace llvm;
127
128static cl::opt<unsigned> OptTfrLimit("expand-condsets-tfr-limit",
129 cl::init(~0U), cl::Hidden, cl::desc("Max number of mux expansions"));
130static cl::opt<unsigned> OptCoaLimit("expand-condsets-coa-limit",
131 cl::init(~0U), cl::Hidden, cl::desc("Max number of segment coalescings"));
132
133namespace {
134
135 class HexagonExpandCondsets : public MachineFunctionPass {
136 public:
137 static char ID;
138
139 HexagonExpandCondsets() : MachineFunctionPass(ID) {
140 if (OptCoaLimit.getPosition())
141 CoaLimitActive = true, CoaLimit = OptCoaLimit;
142 if (OptTfrLimit.getPosition())
143 TfrLimitActive = true, TfrLimit = OptTfrLimit;
144 }
145
146 StringRef getPassName() const override { return "Hexagon Expand Condsets"; }
147
148 void getAnalysisUsage(AnalysisUsage &AU) const override {
149 AU.addRequired<LiveIntervalsWrapperPass>();
150 AU.addPreserved<LiveIntervalsWrapperPass>();
151 AU.addPreserved<SlotIndexesWrapperPass>();
152 AU.addRequired<MachineDominatorTreeWrapperPass>();
153 AU.addPreserved<MachineDominatorTreeWrapperPass>();
155 }
156
157 bool runOnMachineFunction(MachineFunction &MF) override;
158
159 private:
160 const HexagonInstrInfo *HII = nullptr;
161 const TargetRegisterInfo *TRI = nullptr;
162 MachineDominatorTree *MDT;
163 MachineRegisterInfo *MRI = nullptr;
164 LiveIntervals *LIS = nullptr;
165 bool CoaLimitActive = false;
166 bool TfrLimitActive = false;
167 unsigned CoaLimit;
168 unsigned TfrLimit;
169 unsigned CoaCounter = 0;
170 unsigned TfrCounter = 0;
171 SmallPtrSet<const MachineOperand *, 16> KilledUses;
172
173 // FIXME: Consolidate duplicate definitions of RegisterRef
174 struct RegisterRef {
175 RegisterRef(const MachineOperand &Op) : Reg(Op.getReg()),
176 Sub(Op.getSubReg()) {}
177 RegisterRef(unsigned R = 0, unsigned S = 0) : Reg(R), Sub(S) {}
178
179 bool operator== (RegisterRef RR) const {
180 return Reg == RR.Reg && Sub == RR.Sub;
181 }
182 bool operator!= (RegisterRef RR) const { return !operator==(RR); }
183 bool operator< (RegisterRef RR) const {
184 return Reg < RR.Reg || (Reg == RR.Reg && Sub < RR.Sub);
185 }
186
187 Register Reg;
188 unsigned Sub;
189 };
190
191 using ReferenceMap = DenseMap<unsigned, unsigned>;
192 enum { Sub_Low = 0x1, Sub_High = 0x2, Sub_None = (Sub_Low | Sub_High) };
193 enum { Exec_Then = 0x10, Exec_Else = 0x20 };
194
195 unsigned getMaskForSub(unsigned Sub);
196 bool isCondset(const MachineInstr &MI);
197 LaneBitmask getLaneMask(Register Reg, unsigned Sub);
198
199 void addRefToMap(RegisterRef RR, ReferenceMap &Map, unsigned Exec);
200 bool isRefInMap(RegisterRef, ReferenceMap &Map, unsigned Exec);
201
202 void updateDeadsInRange(Register Reg, LaneBitmask LM, LiveRange &Range);
203 void computeKills(Register Reg);
204 void updateDeadFlags(Register Reg);
205 void recalculateLiveInterval(Register Reg);
206 void removeInstr(MachineInstr &MI);
207 void updateLiveness(const std::set<Register> &RegSet, bool Recalc,
208 bool UpdateKills, bool UpdateDeads);
209 void distributeLiveIntervals(const std::set<Register> &Regs);
210
211 unsigned getCondTfrOpcode(const MachineOperand &SO, bool Cond);
212 MachineInstr *genCondTfrFor(MachineOperand &SrcOp,
213 MachineBasicBlock::iterator At, unsigned DstR,
214 unsigned DstSR, const MachineOperand &PredOp, bool PredSense,
215 bool ReadUndef, bool ImpUse);
216 bool split(MachineInstr &MI, std::set<Register> &UpdRegs);
217
218 bool isPredicable(MachineInstr *MI);
219 MachineInstr *getReachingDefForPred(RegisterRef RD,
220 MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond);
221 bool canMoveOver(MachineInstr &MI, ReferenceMap &Defs, ReferenceMap &Uses);
222 bool canMoveMemTo(MachineInstr &MI, MachineInstr &ToI, bool IsDown);
223 void predicateAt(const MachineOperand &DefOp, MachineInstr &MI,
225 const MachineOperand &PredOp, bool Cond,
226 std::set<Register> &UpdRegs);
227 void renameInRange(RegisterRef RO, RegisterRef RN, unsigned PredR,
230 bool predicate(MachineInstr &TfrI, bool Cond, std::set<Register> &UpdRegs);
231 bool predicateInBlock(MachineBasicBlock &B, std::set<Register> &UpdRegs);
232
233 bool isIntReg(RegisterRef RR, unsigned &BW);
234 bool isIntraBlocks(LiveInterval &LI);
235 bool coalesceRegisters(RegisterRef R1, RegisterRef R2);
236 bool coalesceSegments(const SmallVectorImpl<MachineInstr *> &Condsets,
237 std::set<Register> &UpdRegs);
238 };
239
240} // end anonymous namespace
241
242char HexagonExpandCondsets::ID = 0;
243char &llvm::HexagonExpandCondsetsID = HexagonExpandCondsets::ID;
244
245INITIALIZE_PASS_BEGIN(HexagonExpandCondsets, "expand-condsets",
246 "Hexagon Expand Condsets", false, false)
250INITIALIZE_PASS_END(HexagonExpandCondsets, "expand-condsets",
251 "Hexagon Expand Condsets", false, false)
252
253unsigned HexagonExpandCondsets::getMaskForSub(unsigned Sub) {
254 switch (Sub) {
255 case Hexagon::isub_lo:
256 case Hexagon::vsub_lo:
257 return Sub_Low;
258 case Hexagon::isub_hi:
259 case Hexagon::vsub_hi:
260 return Sub_High;
261 case Hexagon::NoSubRegister:
262 return Sub_None;
263 }
264 llvm_unreachable("Invalid subregister");
265}
266
267bool HexagonExpandCondsets::isCondset(const MachineInstr &MI) {
268 unsigned Opc = MI.getOpcode();
269 switch (Opc) {
270 case Hexagon::C2_mux:
271 case Hexagon::C2_muxii:
272 case Hexagon::C2_muxir:
273 case Hexagon::C2_muxri:
274 case Hexagon::PS_pselect:
275 return true;
276 break;
277 }
278 return false;
279}
280
281LaneBitmask HexagonExpandCondsets::getLaneMask(Register Reg, unsigned Sub) {
283 return Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
285}
286
287void HexagonExpandCondsets::addRefToMap(RegisterRef RR, ReferenceMap &Map,
288 unsigned Exec) {
289 unsigned Mask = getMaskForSub(RR.Sub) | Exec;
290 Map[RR.Reg] |= Mask;
291}
292
293bool HexagonExpandCondsets::isRefInMap(RegisterRef RR, ReferenceMap &Map,
294 unsigned Exec) {
295 ReferenceMap::iterator F = Map.find(RR.Reg);
296 if (F == Map.end())
297 return false;
298 unsigned Mask = getMaskForSub(RR.Sub) | Exec;
299 if (Mask & F->second)
300 return true;
301 return false;
302}
303
304void HexagonExpandCondsets::computeKills(Register Reg) {
305 auto KillAt = [this, Reg](SlotIndex K, LaneBitmask LM) -> void {
306 // Record a kill on a use of Reg whose lane mask is contained in LM.
307 MachineInstr *MI = LIS->getInstructionFromIndex(K);
308 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
309 MachineOperand &Op = MI->getOperand(i);
310 if (!Op.isReg() || !Op.isUse() || Op.getReg() != Reg ||
311 MI->isRegTiedToDefOperand(i))
312 continue;
313 LaneBitmask SLM = getLaneMask(Reg, Op.getSubReg());
314 if ((SLM & LM) == SLM) {
315 // Only mark the first encountered use of Reg in this instruction.
316 KilledUses.insert(&Op);
317 break;
318 }
319 }
320 };
321
322 for (const MachineOperand &Op : MRI->use_operands(Reg))
323 KilledUses.erase(&Op);
324
325 LiveInterval &LI = LIS->getInterval(Reg);
326 for (auto I = LI.begin(), E = LI.end(); I != E; ++I) {
327 if (!I->end.isRegister())
328 continue;
329 // Do not mark the end of the segment as <kill>, if the next segment
330 // starts with a predicated instruction.
331 auto NextI = std::next(I);
332 if (NextI != E && NextI->start.isRegister()) {
333 MachineInstr *DefI = LIS->getInstructionFromIndex(NextI->start);
334 if (HII->isPredicated(*DefI))
335 continue;
336 }
337 bool WholeReg = true;
338 if (LI.hasSubRanges()) {
339 auto EndsAtI = [I] (LiveInterval::SubRange &S) -> bool {
340 LiveRange::iterator F = S.find(I->end);
341 return F != S.end() && I->end == F->end;
342 };
343 // Check if all subranges end at I->end. If so, make sure to kill
344 // the whole register.
345 for (LiveInterval::SubRange &S : LI.subranges()) {
346 if (EndsAtI(S))
347 KillAt(I->end, S.LaneMask);
348 else
349 WholeReg = false;
350 }
351 }
352 if (WholeReg)
353 KillAt(I->end, MRI->getMaxLaneMaskForVReg(Reg));
354 }
355}
356
357void HexagonExpandCondsets::updateDeadsInRange(Register Reg, LaneBitmask LM,
358 LiveRange &Range) {
360 if (Range.empty())
361 return;
362
363 // Return two booleans: { def-modifes-reg, def-covers-reg }.
364 auto IsRegDef = [this,Reg,LM] (MachineOperand &Op) -> std::pair<bool,bool> {
365 if (!Op.isReg() || !Op.isDef())
366 return { false, false };
367 Register DR = Op.getReg(), DSR = Op.getSubReg();
368 if (!DR.isVirtual() || DR != Reg)
369 return { false, false };
370 LaneBitmask SLM = getLaneMask(DR, DSR);
371 LaneBitmask A = SLM & LM;
372 return { A.any(), A == SLM };
373 };
374
375 // The splitting step will create pairs of predicated definitions without
376 // any implicit uses (since implicit uses would interfere with predication).
377 // This can cause the reaching defs to become dead after live range
378 // recomputation, even though they are not really dead.
379 // We need to identify predicated defs that need implicit uses, and
380 // dead defs that are not really dead, and correct both problems.
381
382 auto Dominate = [this] (SetVector<MachineBasicBlock*> &Defs,
383 MachineBasicBlock *Dest) -> bool {
384 for (MachineBasicBlock *D : Defs) {
385 if (D != Dest && MDT->dominates(D, Dest))
386 return true;
387 }
388 MachineBasicBlock *Entry = &Dest->getParent()->front();
389 SetVector<MachineBasicBlock *> Work(llvm::from_range, Dest->predecessors());
390 for (unsigned i = 0; i < Work.size(); ++i) {
391 MachineBasicBlock *B = Work[i];
392 if (Defs.count(B))
393 continue;
394 if (B == Entry)
395 return false;
396 Work.insert_range(B->predecessors());
397 }
398 return true;
399 };
400
401 // First, try to extend live range within individual basic blocks. This
402 // will leave us only with dead defs that do not reach any predicated
403 // defs in the same block.
404 SetVector<MachineBasicBlock*> Defs;
406 for (auto &Seg : Range) {
407 if (!Seg.start.isRegister())
408 continue;
409 MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
410 Defs.insert(DefI->getParent());
411 if (HII->isPredicated(*DefI))
412 PredDefs.push_back(Seg.start);
413 }
414
416 LiveInterval &LI = LIS->getInterval(Reg);
417 LI.computeSubRangeUndefs(Undefs, LM, *MRI, *LIS->getSlotIndexes());
418
419 for (auto &SI : PredDefs) {
420 MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
421 auto P = Range.extendInBlock(Undefs, LIS->getMBBStartIdx(BB), SI);
422 if (P.first != nullptr || P.second)
423 SI = SlotIndex();
424 }
425
426 // Calculate reachability for those predicated defs that were not handled
427 // by the in-block extension.
429 for (auto &SI : PredDefs) {
430 if (!SI.isValid())
431 continue;
432 MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
433 if (BB->pred_empty())
434 continue;
435 // If the defs from this range reach SI via all predecessors, it is live.
436 // It can happen that SI is reached by the defs through some paths, but
437 // not all. In the IR coming into this optimization, SI would not be
438 // considered live, since the defs would then not jointly dominate SI.
439 // That means that SI is an overwriting def, and no implicit use is
440 // needed at this point. Do not add SI to the extension points, since
441 // extendToIndices will abort if there is no joint dominance.
442 // If the abort was avoided by adding extra undefs added to Undefs,
443 // extendToIndices could actually indicate that SI is live, contrary
444 // to the original IR.
445 if (Dominate(Defs, BB))
446 ExtTo.push_back(SI);
447 }
448
449 if (!ExtTo.empty())
450 LIS->extendToIndices(Range, ExtTo, Undefs);
451
452 // Remove <dead> flags from all defs that are not dead after live range
453 // extension, and collect all def operands. They will be used to generate
454 // the necessary implicit uses.
455 // At the same time, add <dead> flag to all defs that are actually dead.
456 // This can happen, for example, when a mux with identical inputs is
457 // replaced with a COPY: the use of the predicate register disappears and
458 // the dead can become dead.
459 std::set<RegisterRef> DefRegs;
460 for (auto &Seg : Range) {
461 if (!Seg.start.isRegister())
462 continue;
463 MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
464 for (auto &Op : DefI->operands()) {
465 auto P = IsRegDef(Op);
466 if (P.second && Seg.end.isDead()) {
467 Op.setIsDead(true);
468 } else if (P.first) {
469 DefRegs.insert(Op);
470 Op.setIsDead(false);
471 }
472 }
473 }
474
475 // Now, add implicit uses to each predicated def that is reached
476 // by other defs.
477 for (auto &Seg : Range) {
478 if (!Seg.start.isRegister() || !Range.liveAt(Seg.start.getPrevSlot()))
479 continue;
480 MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
481 if (!HII->isPredicated(*DefI))
482 continue;
483 // Construct the set of all necessary implicit uses, based on the def
484 // operands in the instruction. We need to tie the implicit uses to
485 // the corresponding defs.
486 std::map<RegisterRef,unsigned> ImpUses;
487 for (unsigned i = 0, e = DefI->getNumOperands(); i != e; ++i) {
488 MachineOperand &Op = DefI->getOperand(i);
489 if (!Op.isReg() || !DefRegs.count(Op))
490 continue;
491 if (Op.isDef()) {
492 // Tied defs will always have corresponding uses, so no extra
493 // implicit uses are needed.
494 if (!Op.isTied())
495 ImpUses.insert({Op, i});
496 } else {
497 // This function can be called for the same register with different
498 // lane masks. If the def in this instruction was for the whole
499 // register, we can get here more than once. Avoid adding multiple
500 // implicit uses (or adding an implicit use when an explicit one is
501 // present).
502 if (Op.isTied())
503 ImpUses.erase(Op);
504 }
505 }
506 if (ImpUses.empty())
507 continue;
508 MachineFunction &MF = *DefI->getParent()->getParent();
509 for (auto [R, DefIdx] : ImpUses) {
510 MachineInstrBuilder(MF, DefI).addReg(R.Reg, RegState::Implicit, R.Sub);
511 DefI->tieOperands(DefIdx, DefI->getNumOperands()-1);
512 }
513 }
514}
515
516void HexagonExpandCondsets::updateDeadFlags(Register Reg) {
517 LiveInterval &LI = LIS->getInterval(Reg);
518 if (LI.hasSubRanges()) {
519 for (LiveInterval::SubRange &S : LI.subranges()) {
520 updateDeadsInRange(Reg, S.LaneMask, S);
521 LIS->shrinkToUses(S, Reg);
522 }
523 LI.clear();
525 } else {
526 updateDeadsInRange(Reg, MRI->getMaxLaneMaskForVReg(Reg), LI);
527 }
528}
529
530void HexagonExpandCondsets::recalculateLiveInterval(Register Reg) {
531 LIS->removeInterval(Reg);
533}
534
535void HexagonExpandCondsets::removeInstr(MachineInstr &MI) {
536 for (const MachineOperand &Op : MI.operands())
537 KilledUses.erase(&Op);
539 MI.eraseFromParent();
540}
541
542void HexagonExpandCondsets::updateLiveness(const std::set<Register> &RegSet,
543 bool Recalc, bool UpdateKills,
544 bool UpdateDeads) {
545 for (Register R : RegSet) {
546 if (!R.isVirtual()) {
547 assert(R.isPhysical());
548 // There shouldn't be any physical registers as operands, except
549 // possibly reserved registers.
550 assert(MRI->isReserved(R));
551 continue;
552 }
553 if (Recalc)
554 recalculateLiveInterval(R);
555
556 if (UpdateDeads)
557 updateDeadFlags(R);
558 // Fixing <dead> flags may extend live ranges, so compute kills after that.
559 if (UpdateKills)
560 computeKills(R);
561 assert(LIS->getInterval(R).verify());
562 }
563}
564
565void HexagonExpandCondsets::distributeLiveIntervals(
566 const std::set<Register> &Regs) {
567 ConnectedVNInfoEqClasses EQC(*LIS);
568 for (Register R : Regs) {
569 if (!R.isVirtual())
570 continue;
571 LiveInterval &LI = LIS->getInterval(R);
572 unsigned NumComp = EQC.Classify(LI);
573 if (NumComp == 1)
574 continue;
575
577 const TargetRegisterClass *RC = MRI->getRegClass(LI.reg());
578 for (unsigned I = 1; I < NumComp; ++I) {
580 NewLIs.push_back(&LIS->createEmptyInterval(NewR));
581 }
582 EQC.Distribute(LI, NewLIs.begin(), *MRI);
583 }
584}
585
586/// Get the opcode for a conditional transfer of the value in SO (source
587/// operand). The condition (true/false) is given in Cond.
588unsigned HexagonExpandCondsets::getCondTfrOpcode(const MachineOperand &SO,
589 bool IfTrue) {
590 if (SO.isReg()) {
591 MCRegister PhysR;
592 RegisterRef RS = SO;
593 if (RS.Reg.isVirtual()) {
594 const TargetRegisterClass *VC = MRI->getRegClass(RS.Reg);
595 assert(VC->begin() != VC->end() && "Empty register class");
596 PhysR = *VC->begin();
597 } else {
598 PhysR = RS.Reg;
599 }
600 MCRegister PhysS = (RS.Sub == 0) ? PhysR : TRI->getSubReg(PhysR, RS.Sub);
601 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysS);
602 switch (TRI->getRegSizeInBits(*RC)) {
603 case 32:
604 return IfTrue ? Hexagon::A2_tfrt : Hexagon::A2_tfrf;
605 case 64:
606 return IfTrue ? Hexagon::A2_tfrpt : Hexagon::A2_tfrpf;
607 }
608 llvm_unreachable("Invalid register operand");
609 }
610 switch (SO.getType()) {
619 return IfTrue ? Hexagon::C2_cmoveit : Hexagon::C2_cmoveif;
620 default:
621 break;
622 }
623 llvm_unreachable("Unexpected source operand");
624}
625
626/// Generate a conditional transfer, copying the value SrcOp to the
627/// destination register DstR:DstSR, and using the predicate register from
628/// PredOp. The Cond argument specifies whether the predicate is to be
629/// if(PredOp), or if(!PredOp).
630MachineInstr *HexagonExpandCondsets::genCondTfrFor(MachineOperand &SrcOp,
632 unsigned DstR, unsigned DstSR, const MachineOperand &PredOp,
633 bool PredSense, bool ReadUndef, bool ImpUse) {
634 MachineInstr *MI = SrcOp.getParent();
635 MachineBasicBlock &B = *At->getParent();
636 const DebugLoc &DL = MI->getDebugLoc();
637
638 // Don't avoid identity copies here (i.e. if the source and the destination
639 // are the same registers). It is actually better to generate them here,
640 // since this would cause the copy to potentially be predicated in the next
641 // step. The predication will remove such a copy if it is unable to
642 /// predicate.
643
644 unsigned Opc = getCondTfrOpcode(SrcOp, PredSense);
645 RegState DstState = RegState::Define | getUndefRegState(ReadUndef);
646 RegState PredState = getRegState(PredOp) & ~RegState::Kill;
647 MachineInstrBuilder MIB;
648
649 if (SrcOp.isReg()) {
650 MIB = BuildMI(B, At, DL, HII->get(Opc))
651 .addReg(DstR, DstState, DstSR)
652 .addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
653 .addReg(SrcOp.getReg(), getRegState(SrcOp), SrcOp.getSubReg());
654 if (KilledUses.contains(&SrcOp) &&
655 RegisterRef(SrcOp) != RegisterRef(DstR, DstSR))
656 KilledUses.insert(&MIB->getOperand(2));
657 } else {
658 MIB = BuildMI(B, At, DL, HII->get(Opc))
659 .addReg(DstR, DstState, DstSR)
660 .addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
661 .add(SrcOp);
662 }
663
664 LLVM_DEBUG(dbgs() << "created an initial copy: " << *MIB);
665 return &*MIB;
666}
667
668/// Replace a MUX instruction MI with a pair A2_tfrt/A2_tfrf. This function
669/// performs all necessary changes to complete the replacement.
670bool HexagonExpandCondsets::split(MachineInstr &MI,
671 std::set<Register> &UpdRegs) {
672 if (TfrLimitActive) {
673 if (TfrCounter >= TfrLimit)
674 return false;
675 TfrCounter++;
676 }
677 LLVM_DEBUG(dbgs() << "\nsplitting " << printMBBReference(*MI.getParent())
678 << ": " << MI);
679 MachineOperand &MD = MI.getOperand(0); // Definition
680 MachineOperand &MP = MI.getOperand(1); // Predicate register
681 assert(MD.isDef());
682 Register DR = MD.getReg(), DSR = MD.getSubReg();
683 bool ReadUndef = MD.isUndef();
685
686 auto updateRegs = [&UpdRegs] (const MachineInstr &MI) -> void {
687 for (auto &Op : MI.operands()) {
688 if (Op.isReg())
689 UpdRegs.insert(Op.getReg());
690 }
691 };
692
693 // If this is a mux of the same register, just replace it with COPY.
694 // Ideally, this would happen earlier, so that register coalescing would
695 // see it.
696 MachineOperand &ST = MI.getOperand(2);
697 MachineOperand &SF = MI.getOperand(3);
698 if (ST.isReg() && SF.isReg()) {
699 RegisterRef RT(ST);
700 if (RT == RegisterRef(SF)) {
701 // Copy regs to update first.
702 updateRegs(MI);
703 MI.setDesc(HII->get(TargetOpcode::COPY));
704 RegState S = getRegState(ST);
705 for (const MachineOperand &Op : MI.operands())
706 KilledUses.erase(&Op);
707 while (MI.getNumOperands() > 1)
708 MI.removeOperand(MI.getNumOperands()-1);
709 MachineFunction &MF = *MI.getParent()->getParent();
710 MachineInstrBuilder(MF, MI).addReg(RT.Reg, S, RT.Sub);
711 return true;
712 }
713 }
714
715 // First, create the two individual conditional transfers, and add each
716 // of them to the live intervals information. Do that first and then remove
717 // the old instruction from live intervals.
718 MachineInstr *TfrT =
719 genCondTfrFor(ST, At, DR, DSR, MP, true, ReadUndef, false);
720 MachineInstr *TfrF =
721 genCondTfrFor(SF, At, DR, DSR, MP, false, ReadUndef, true);
722 LIS->InsertMachineInstrInMaps(*TfrT);
723 LIS->InsertMachineInstrInMaps(*TfrF);
724
725 // Will need to recalculate live intervals for all registers in MI.
726 updateRegs(MI);
727
728 removeInstr(MI);
729 return true;
730}
731
732bool HexagonExpandCondsets::isPredicable(MachineInstr *MI) {
733 if (HII->isPredicated(*MI) || !HII->isPredicable(*MI))
734 return false;
735 if (MI->hasUnmodeledSideEffects() || MI->mayStore())
736 return false;
737 // Reject instructions with multiple defs (e.g. post-increment loads).
738 bool HasDef = false;
739 for (auto &Op : MI->operands()) {
740 if (!Op.isReg() || !Op.isDef())
741 continue;
742 if (HasDef)
743 return false;
744 HasDef = true;
745 }
746 for (auto &Mo : MI->memoperands()) {
747 if (Mo->isVolatile() || Mo->isAtomic())
748 return false;
749 }
750 return true;
751}
752
753/// Find the reaching definition for a predicated use of RD. The RD is used
754/// under the conditions given by PredR and Cond, and this function will ignore
755/// definitions that set RD under the opposite conditions.
756MachineInstr *HexagonExpandCondsets::getReachingDefForPred(RegisterRef RD,
757 MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond) {
758 MachineBasicBlock &B = *UseIt->getParent();
759 MachineBasicBlock::iterator I = UseIt, S = B.begin();
760 if (I == S)
761 return nullptr;
762
763 bool PredValid = true;
764 do {
765 --I;
766 MachineInstr *MI = &*I;
767 // Check if this instruction can be ignored, i.e. if it is predicated
768 // on the complementary condition.
769 if (PredValid && HII->isPredicated(*MI)) {
770 if (MI->readsRegister(PredR, /*TRI=*/nullptr) &&
771 (Cond != HII->isPredicatedTrue(*MI)))
772 continue;
773 }
774
775 // Check the defs. If the PredR is defined, invalidate it. If RD is
776 // defined, return the instruction or 0, depending on the circumstances.
777 for (auto &Op : MI->operands()) {
778 if (!Op.isReg() || !Op.isDef())
779 continue;
780 RegisterRef RR = Op;
781 if (RR.Reg == PredR) {
782 PredValid = false;
783 continue;
784 }
785 if (RR.Reg != RD.Reg)
786 continue;
787 // If the "Reg" part agrees, there is still the subregister to check.
788 // If we are looking for %1:loreg, we can skip %1:hireg, but
789 // not %1 (w/o subregisters).
790 if (RR.Sub == RD.Sub)
791 return MI;
792 if (RR.Sub == 0 || RD.Sub == 0)
793 return nullptr;
794 // We have different subregisters, so we can continue looking.
795 }
796 } while (I != S);
797
798 return nullptr;
799}
800
801/// Check if the instruction MI can be safely moved over a set of instructions
802/// whose side-effects (in terms of register defs and uses) are expressed in
803/// the maps Defs and Uses. These maps reflect the conditional defs and uses
804/// that depend on the same predicate register to allow moving instructions
805/// over instructions predicated on the opposite condition.
806bool HexagonExpandCondsets::canMoveOver(MachineInstr &MI, ReferenceMap &Defs,
807 ReferenceMap &Uses) {
808 // In order to be able to safely move MI over instructions that define
809 // "Defs" and use "Uses", no def operand from MI can be defined or used
810 // and no use operand can be defined.
811 for (auto &Op : MI.operands()) {
812 if (!Op.isReg())
813 continue;
814 RegisterRef RR = Op;
815 // For physical register we would need to check register aliases, etc.
816 // and we don't want to bother with that. It would be of little value
817 // before the actual register rewriting (from virtual to physical).
818 if (!RR.Reg.isVirtual())
819 return false;
820 // No redefs for any operand.
821 if (isRefInMap(RR, Defs, Exec_Then))
822 return false;
823 // For defs, there cannot be uses.
824 if (Op.isDef() && isRefInMap(RR, Uses, Exec_Then))
825 return false;
826 }
827 return true;
828}
829
830/// Check if the instruction accessing memory (TheI) can be moved to the
831/// location ToI.
832bool HexagonExpandCondsets::canMoveMemTo(MachineInstr &TheI, MachineInstr &ToI,
833 bool IsDown) {
834 bool IsLoad = TheI.mayLoad(), IsStore = TheI.mayStore();
835 if (!IsLoad && !IsStore)
836 return true;
837 if (HII->areMemAccessesTriviallyDisjoint(TheI, ToI))
838 return true;
839 if (TheI.hasUnmodeledSideEffects())
840 return false;
841
842 MachineBasicBlock::iterator StartI = IsDown ? TheI : ToI;
843 MachineBasicBlock::iterator EndI = IsDown ? ToI : TheI;
844 bool Ordered = TheI.hasOrderedMemoryRef();
845
846 // Search for aliased memory reference in (StartI, EndI).
847 for (MachineInstr &MI : llvm::make_range(std::next(StartI), EndI)) {
848 if (MI.hasUnmodeledSideEffects())
849 return false;
850 bool L = MI.mayLoad(), S = MI.mayStore();
851 if (!L && !S)
852 continue;
853 if (Ordered && MI.hasOrderedMemoryRef())
854 return false;
855
856 bool Conflict = (L && IsStore) || S;
857 if (Conflict)
858 return false;
859 }
860 return true;
861}
862
863/// Generate a predicated version of MI (where the condition is given via
864/// PredR and Cond) at the point indicated by Where.
865void HexagonExpandCondsets::predicateAt(const MachineOperand &DefOp,
866 MachineInstr &MI,
868 const MachineOperand &PredOp, bool Cond,
869 std::set<Register> &UpdRegs) {
870 // The problem with updating live intervals is that we can move one def
871 // past another def. In particular, this can happen when moving an A2_tfrt
872 // over an A2_tfrf defining the same register. From the point of view of
873 // live intervals, these two instructions are two separate definitions,
874 // and each one starts another live segment. LiveIntervals's "handleMove"
875 // does not allow such moves, so we need to handle it ourselves. To avoid
876 // invalidating liveness data while we are using it, the move will be
877 // implemented in 4 steps: (1) add a clone of the instruction MI at the
878 // target location, (2) update liveness, (3) delete the old instruction,
879 // and (4) update liveness again.
880
881 MachineBasicBlock &B = *MI.getParent();
882 DebugLoc DL = Where->getDebugLoc(); // "Where" points to an instruction.
883 unsigned Opc = MI.getOpcode();
884 unsigned PredOpc = HII->getCondOpcode(Opc, !Cond);
885 MachineInstrBuilder MB = BuildMI(B, Where, DL, HII->get(PredOpc));
886 unsigned Ox = 0, NP = MI.getNumOperands();
887 // Skip all defs from MI first.
888 while (Ox < NP) {
889 MachineOperand &MO = MI.getOperand(Ox);
890 if (!MO.isReg() || !MO.isDef())
891 break;
892 Ox++;
893 }
894 // Add the new def, then the predicate register, then the rest of the
895 // operands.
896 MB.addReg(DefOp.getReg(), getRegState(DefOp), DefOp.getSubReg());
897 MB.addReg(PredOp.getReg(), getUndefRegState(PredOp.isUndef()),
898 PredOp.getSubReg());
899 while (Ox < NP) {
900 MachineOperand &MO = MI.getOperand(Ox);
901 if (!MO.isReg() || !MO.isImplicit())
902 MB.add(MO);
903 Ox++;
904 }
905 MB.cloneMemRefs(MI);
906
907 MachineInstr *NewI = MB;
908 NewI->clearKillInfo();
909 LIS->InsertMachineInstrInMaps(*NewI);
910
911 for (auto &Op : NewI->operands()) {
912 if (Op.isReg())
913 UpdRegs.insert(Op.getReg());
914 }
915}
916
917/// In the range [First, Last], rename all references to the "old" register RO
918/// to the "new" register RN, but only in instructions predicated on the given
919/// condition.
920void HexagonExpandCondsets::renameInRange(RegisterRef RO, RegisterRef RN,
921 unsigned PredR, bool Cond, MachineBasicBlock::iterator First,
924 for (MachineInstr &MI : llvm::make_range(First, End)) {
925 // Do not touch instructions that are not predicated, or are predicated
926 // on the opposite condition.
927 if (!HII->isPredicated(MI))
928 continue;
929 if (!MI.readsRegister(PredR, /*TRI=*/nullptr) ||
930 (Cond != HII->isPredicatedTrue(MI)))
931 continue;
932
933 for (auto &Op : MI.operands()) {
934 if (!Op.isReg() || RO != RegisterRef(Op))
935 continue;
936 Op.setReg(RN.Reg);
937 Op.setSubReg(RN.Sub);
938 // In practice, this isn't supposed to see any defs.
939 assert(!Op.isDef() && "Not expecting a def");
940 }
941 }
942}
943
944/// For a given conditional copy, predicate the definition of the source of
945/// the copy under the given condition (using the same predicate register as
946/// the copy).
947bool HexagonExpandCondsets::predicate(MachineInstr &TfrI, bool Cond,
948 std::set<Register> &UpdRegs) {
949 // TfrI - A2_tfr[tf] Instruction (not A2_tfrsi).
950 unsigned Opc = TfrI.getOpcode();
951 (void)Opc;
952 assert(Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf);
953 LLVM_DEBUG(dbgs() << "\nattempt to predicate if-" << (Cond ? "true" : "false")
954 << ": " << TfrI);
955
956 MachineOperand &MD = TfrI.getOperand(0);
957 MachineOperand &MP = TfrI.getOperand(1);
958 MachineOperand &MS = TfrI.getOperand(2);
959 // The source operand should be a kill. This is not strictly necessary,
960 // but it makes things a lot simpler. Otherwise, we would need to rename
961 // some registers, which would complicate the transformation considerably.
962 if (!KilledUses.contains(&MS))
963 return false;
964 // Avoid predicating instructions that define a subregister if subregister
965 // liveness tracking is not enabled.
966 if (MD.getSubReg() && !MRI->shouldTrackSubRegLiveness(MD.getReg()))
967 return false;
968
969 RegisterRef RT(MS);
970 Register PredR = MP.getReg();
971 MachineInstr *DefI = getReachingDefForPred(RT, TfrI, PredR, Cond);
972 if (!DefI || !isPredicable(DefI))
973 return false;
974
975 LLVM_DEBUG(dbgs() << "Source def: " << *DefI);
976
977 // Collect the information about registers defined and used between the
978 // DefI and the TfrI.
979 // Map: reg -> bitmask of subregs
980 ReferenceMap Uses, Defs;
981 MachineBasicBlock::iterator DefIt = DefI, TfrIt = TfrI;
982
983 // Check if the predicate register is valid between DefI and TfrI.
984 // If it is, we can then ignore instructions predicated on the negated
985 // conditions when collecting def and use information.
986 bool PredValid = true;
987 for (MachineInstr &MI : llvm::make_range(std::next(DefIt), TfrIt)) {
988 if (!MI.modifiesRegister(PredR, nullptr))
989 continue;
990 PredValid = false;
991 break;
992 }
993
994 for (MachineInstr &MI : llvm::make_range(std::next(DefIt), TfrIt)) {
995 // Debug instructions do not generate any code, so their operands should
996 // not be taken into account when checking whether the transformation is
997 // possible.
998 if (MI.isDebugInstr())
999 continue;
1000 // If this instruction is predicated on the same register, it could
1001 // potentially be ignored.
1002 // By default assume that the instruction executes on the same condition
1003 // as TfrI (Exec_Then), and also on the opposite one (Exec_Else).
1004 unsigned Exec = Exec_Then | Exec_Else;
1005 if (PredValid && HII->isPredicated(MI) &&
1006 MI.readsRegister(PredR, /*TRI=*/nullptr))
1007 Exec = (Cond == HII->isPredicatedTrue(MI)) ? Exec_Then : Exec_Else;
1008
1009 for (auto &Op : MI.operands()) {
1010 if (!Op.isReg())
1011 continue;
1012 // We don't want to deal with physical registers. The reason is that
1013 // they can be aliased with other physical registers. Aliased virtual
1014 // registers must share the same register number, and can only differ
1015 // in the subregisters, which we are keeping track of. Physical
1016 // registers ters no longer have subregisters---their super- and
1017 // subregisters are other physical registers, and we are not checking
1018 // that.
1019 RegisterRef RR = Op;
1020 if (!RR.Reg.isVirtual())
1021 return false;
1022
1023 ReferenceMap &Map = Op.isDef() ? Defs : Uses;
1024 if (Op.isDef() && Op.isUndef()) {
1025 assert(RR.Sub && "Expecting a subregister on <def,read-undef>");
1026 // If this is a <def,read-undef>, then it invalidates the non-written
1027 // part of the register. For the purpose of checking the validity of
1028 // the move, assume that it modifies the whole register.
1029 RR.Sub = 0;
1030 }
1031 addRefToMap(RR, Map, Exec);
1032 }
1033 }
1034
1035 // The situation:
1036 // RT = DefI
1037 // ...
1038 // RD = TfrI ..., RT
1039
1040 // If the register-in-the-middle (RT) is used or redefined between
1041 // DefI and TfrI, we may not be able proceed with this transformation.
1042 // We can ignore a def that will not execute together with TfrI, and a
1043 // use that will. If there is such a use (that does execute together with
1044 // TfrI), we will not be able to move DefI down. If there is a use that
1045 // executed if TfrI's condition is false, then RT must be available
1046 // unconditionally (cannot be predicated).
1047 // Essentially, we need to be able to rename RT to RD in this segment.
1048 if (isRefInMap(RT, Defs, Exec_Then) || isRefInMap(RT, Uses, Exec_Else))
1049 return false;
1050 RegisterRef RD = MD;
1051 // If the predicate register is defined between DefI and TfrI, the only
1052 // potential thing to do would be to move the DefI down to TfrI, and then
1053 // predicate. The reaching def (DefI) must be movable down to the location
1054 // of the TfrI.
1055 // If the target register of the TfrI (RD) is not used or defined between
1056 // DefI and TfrI, consider moving TfrI up to DefI.
1057 bool CanUp = canMoveOver(TfrI, Defs, Uses);
1058 bool CanDown = canMoveOver(*DefI, Defs, Uses);
1059 // The TfrI does not access memory, but DefI could. Check if it's safe
1060 // to move DefI down to TfrI.
1061 if (DefI->mayLoadOrStore()) {
1062 if (!canMoveMemTo(*DefI, TfrI, true))
1063 CanDown = false;
1064 }
1065
1066 LLVM_DEBUG(dbgs() << "Can move up: " << (CanUp ? "yes" : "no")
1067 << ", can move down: " << (CanDown ? "yes\n" : "no\n"));
1068 MachineBasicBlock::iterator PastDefIt = std::next(DefIt);
1069 if (CanUp)
1070 predicateAt(MD, *DefI, PastDefIt, MP, Cond, UpdRegs);
1071 else if (CanDown)
1072 predicateAt(MD, *DefI, TfrIt, MP, Cond, UpdRegs);
1073 else
1074 return false;
1075
1076 if (RT != RD) {
1077 renameInRange(RT, RD, PredR, Cond, PastDefIt, TfrIt);
1078 UpdRegs.insert(RT.Reg);
1079 }
1080
1081 removeInstr(TfrI);
1082 removeInstr(*DefI);
1083 return true;
1084}
1085
1086/// Predicate all cases of conditional copies in the specified block.
1087bool HexagonExpandCondsets::predicateInBlock(MachineBasicBlock &B,
1088 std::set<Register> &UpdRegs) {
1089 bool Changed = false;
1090 for (MachineInstr &MI : llvm::make_early_inc_range(B)) {
1091 unsigned Opc = MI.getOpcode();
1092 if (Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf) {
1093 bool Done = predicate(MI, (Opc == Hexagon::A2_tfrt), UpdRegs);
1094 if (!Done) {
1095 // If we didn't predicate I, we may need to remove it in case it is
1096 // an "identity" copy, e.g. %1 = A2_tfrt %2, %1.
1097 if (RegisterRef(MI.getOperand(0)) == RegisterRef(MI.getOperand(2))) {
1098 for (auto &Op : MI.operands()) {
1099 if (Op.isReg())
1100 UpdRegs.insert(Op.getReg());
1101 }
1102 removeInstr(MI);
1103 }
1104 }
1105 Changed |= Done;
1106 }
1107 }
1108 return Changed;
1109}
1110
1111bool HexagonExpandCondsets::isIntReg(RegisterRef RR, unsigned &BW) {
1112 if (!RR.Reg.isVirtual())
1113 return false;
1114 const TargetRegisterClass *RC = MRI->getRegClass(RR.Reg);
1115 if (RC == &Hexagon::IntRegsRegClass) {
1116 BW = 32;
1117 return true;
1118 }
1119 if (RC == &Hexagon::DoubleRegsRegClass) {
1120 BW = (RR.Sub != 0) ? 32 : 64;
1121 return true;
1122 }
1123 return false;
1124}
1125
1126bool HexagonExpandCondsets::isIntraBlocks(LiveInterval &LI) {
1127 for (LiveRange::Segment &LR : LI) {
1128 // Range must start at a register...
1129 if (!LR.start.isRegister())
1130 return false;
1131 // ...and end in a register or in a dead slot.
1132 if (!LR.end.isRegister() && !LR.end.isDead())
1133 return false;
1134 }
1135 return true;
1136}
1137
1138bool HexagonExpandCondsets::coalesceRegisters(RegisterRef R1, RegisterRef R2) {
1139 if (CoaLimitActive) {
1140 if (CoaCounter >= CoaLimit)
1141 return false;
1142 CoaCounter++;
1143 }
1144 unsigned BW1, BW2;
1145 if (!isIntReg(R1, BW1) || !isIntReg(R2, BW2) || BW1 != BW2)
1146 return false;
1147 if (MRI->isLiveIn(R1.Reg))
1148 return false;
1149 if (MRI->isLiveIn(R2.Reg))
1150 return false;
1151
1152 LiveInterval &L1 = LIS->getInterval(R1.Reg);
1153 LiveInterval &L2 = LIS->getInterval(R2.Reg);
1154 if (L2.empty())
1155 return false;
1156 if (L1.hasSubRanges() || L2.hasSubRanges())
1157 return false;
1158 bool Overlap = L1.overlaps(L2);
1159
1160 LLVM_DEBUG(dbgs() << "compatible registers: ("
1161 << (Overlap ? "overlap" : "disjoint") << ")\n "
1162 << printReg(R1.Reg, TRI, R1.Sub) << " " << L1 << "\n "
1163 << printReg(R2.Reg, TRI, R2.Sub) << " " << L2 << "\n");
1164 if (R1.Sub || R2.Sub)
1165 return false;
1166 if (Overlap)
1167 return false;
1168
1169 // Coalescing could have a negative impact on scheduling, so try to limit
1170 // to some reasonable extent. Only consider coalescing segments, when one
1171 // of them does not cross basic block boundaries.
1172 if (!isIntraBlocks(L1) && !isIntraBlocks(L2))
1173 return false;
1174
1175 MRI->replaceRegWith(R2.Reg, R1.Reg);
1176
1177 // Move all live segments from L2 to L1.
1178 using ValueInfoMap = DenseMap<VNInfo *, VNInfo *>;
1179 ValueInfoMap VM;
1180 for (LiveRange::Segment &I : L2) {
1181 VNInfo *NewVN, *OldVN = I.valno;
1182 ValueInfoMap::iterator F = VM.find(OldVN);
1183 if (F == VM.end()) {
1184 NewVN = L1.getNextValue(I.valno->def, LIS->getVNInfoAllocator());
1185 VM.insert(std::make_pair(OldVN, NewVN));
1186 } else {
1187 NewVN = F->second;
1188 }
1189 L1.addSegment(LiveRange::Segment(I.start, I.end, NewVN));
1190 }
1191 while (!L2.empty())
1192 L2.removeSegment(*L2.begin());
1193 LIS->removeInterval(R2.Reg);
1194
1195 computeKills(R1.Reg);
1196 LLVM_DEBUG(dbgs() << "coalesced: " << L1 << "\n");
1197 assert(L1.verify());
1198
1199 return true;
1200}
1201
1202/// Attempt to coalesce one of the source registers to a MUX instruction with
1203/// the destination register. This could lead to having only one predicated
1204/// instruction in the end instead of two.
1205bool HexagonExpandCondsets::coalesceSegments(
1206 const SmallVectorImpl<MachineInstr *> &Condsets,
1207 std::set<Register> &UpdRegs) {
1209 for (MachineInstr *MI : Condsets) {
1210 MachineOperand &S1 = MI->getOperand(2), &S2 = MI->getOperand(3);
1211 if (!S1.isReg() && !S2.isReg())
1212 continue;
1213 TwoRegs.push_back(MI);
1214 }
1215
1216 bool Changed = false;
1217 for (MachineInstr *CI : TwoRegs) {
1218 RegisterRef RD = CI->getOperand(0);
1219 RegisterRef RP = CI->getOperand(1);
1220 MachineOperand &S1 = CI->getOperand(2), &S2 = CI->getOperand(3);
1221 bool Done = false;
1222 // Consider this case:
1223 // %1 = instr1 ...
1224 // %2 = instr2 ...
1225 // %0 = C2_mux ..., %1, %2
1226 // If %0 was coalesced with %1, we could end up with the following
1227 // code:
1228 // %0 = instr1 ...
1229 // %2 = instr2 ...
1230 // %0 = A2_tfrf ..., %2
1231 // which will later become:
1232 // %0 = instr1 ...
1233 // %0 = instr2_cNotPt ...
1234 // i.e. there will be an unconditional definition (instr1) of %0
1235 // followed by a conditional one. The output dependency was there before
1236 // and it unavoidable, but if instr1 is predicable, we will no longer be
1237 // able to predicate it here.
1238 // To avoid this scenario, don't coalesce the destination register with
1239 // a source register that is defined by a predicable instruction.
1240 if (S1.isReg()) {
1241 RegisterRef RS = S1;
1242 MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, true);
1243 if (!RDef || !HII->isPredicable(*RDef)) {
1244 Done = coalesceRegisters(RD, RS);
1245 if (Done) {
1246 UpdRegs.insert(RD.Reg);
1247 UpdRegs.erase(RS.Reg);
1248 }
1249 }
1250 }
1251 if (!Done && S2.isReg()) {
1252 RegisterRef RS = S2;
1253 MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, false);
1254 if (!RDef || !HII->isPredicable(*RDef)) {
1255 Done = coalesceRegisters(RD, RS);
1256 if (Done) {
1257 UpdRegs.insert(RD.Reg);
1258 UpdRegs.erase(RS.Reg);
1259 }
1260 }
1261 }
1262 Changed |= Done;
1263 }
1264 return Changed;
1265}
1266
1267bool HexagonExpandCondsets::runOnMachineFunction(MachineFunction &MF) {
1268 if (skipFunction(MF.getFunction()))
1269 return false;
1270
1271 HII = static_cast<const HexagonInstrInfo*>(MF.getSubtarget().getInstrInfo());
1273 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1274 LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1275 MRI = &MF.getRegInfo();
1276
1277 LLVM_DEBUG(LIS->print(dbgs() << "Before expand-condsets\n"));
1278
1279 bool Changed = false;
1280 std::set<Register> CoalUpd, PredUpd;
1281
1283 for (auto &B : MF) {
1284 for (auto &I : B) {
1285 if (isCondset(I))
1286 Condsets.push_back(&I);
1287 }
1288 }
1289
1290 // Try to coalesce the target of a mux with one of its sources.
1291 // This could eliminate a register copy in some circumstances.
1292 Changed |= coalesceSegments(Condsets, CoalUpd);
1293
1294 // Compute kills on all source operands. Doing this right before we split is
1295 // the easiest, because splitting adds definitions which would interfere with
1296 // computing kills afterwards.
1297 std::set<Register> KillUpd;
1298 for (MachineInstr *MI : Condsets) {
1299 for (MachineOperand &Op : MI->operands()) {
1300 if (Op.isReg() && Op.isUse()) {
1301 if (!CoalUpd.count(Op.getReg()))
1302 KillUpd.insert(Op.getReg());
1303 }
1304 }
1305 }
1306 updateLiveness(KillUpd, false, true, false);
1307 LLVM_DEBUG(LIS->print(dbgs() << "After coalescing\n"));
1308
1309 // First, simply split all muxes into a pair of conditional transfers
1310 // and update the live intervals to reflect the new arrangement. The
1311 // goal is to preserve the computed kills, since predication will rely on
1312 // them.
1313 for (MachineInstr *MI : Condsets)
1314 Changed |= split(*MI, PredUpd);
1315 Condsets.clear(); // The contents of Condsets are invalid here anyway.
1316
1317 // Do not update live ranges after splitting. The kills recorded on the
1318 // source operands of condsets were carried over by splitting, and are needed
1319 // by predication. After splitting they are difficult to recalculate (because
1320 // of predicated defs). Predication does not use live intervals.
1321 LLVM_DEBUG(LIS->print(dbgs() << "After splitting\n"));
1322
1323 // Traverse all blocks and collapse predicable instructions feeding
1324 // conditional transfers into predicated instructions.
1325 // Walk over all the instructions again, so we may catch pre-existing
1326 // cases that were not created in the previous step.
1327 for (auto &B : MF)
1328 Changed |= predicateInBlock(B, PredUpd);
1329 LLVM_DEBUG(LIS->print(dbgs() << "After predicating\n"));
1330
1331 PredUpd.insert(CoalUpd.begin(), CoalUpd.end());
1332 updateLiveness(PredUpd, true, false, true);
1333 KilledUses.clear();
1334
1335 if (Changed)
1336 distributeLiveIntervals(PredUpd);
1337
1338 LLVM_DEBUG({
1339 if (Changed)
1340 LIS->print(dbgs() << "After expand-condsets\n");
1341 });
1342
1343 return Changed;
1344}
1345
1346//===----------------------------------------------------------------------===//
1347// Public Constructor Functions
1348//===----------------------------------------------------------------------===//
1350 return new HexagonExpandCondsets();
1351}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
static cl::opt< unsigned > OptCoaLimit("expand-condsets-coa-limit", cl::init(~0U), cl::Hidden, cl::desc("Max number of segment coalescings"))
static cl::opt< unsigned > OptTfrLimit("expand-condsets-tfr-limit", cl::init(~0U), cl::Hidden, cl::desc("Max number of mux expansions"))
expand Hexagon Expand Condsets
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define R2(n)
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
SI Optimize VGPR LiveRange
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
int getCondOpcode(int Opc, bool sense) const
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const override
bool isPredicable(const MachineInstr &MI) const override
Return true if the specified instruction can be predicated.
bool isPredicatedTrue(const MachineInstr &MI) const
Register reg() const
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
bool verify(const MachineRegisterInfo *MRI=nullptr) const
Walks the interval and assert if any invariants fail to hold.
LLVM_ABI void computeSubRangeUndefs(SmallVectorImpl< SlotIndex > &Undefs, LaneBitmask LaneMask, const MachineRegisterInfo &MRI, const SlotIndexes &Indexes) const
For a given lane mask LaneMask, compute indexes at which the lane is marked undefined by subregister ...
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
SlotIndexes * getSlotIndexes() const
void RemoveMachineInstrFromMaps(MachineInstr &MI)
VNInfo::Allocator & getVNInfoAllocator()
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr, LaneBitmask SubRangeMask=LaneBitmask::getAll())
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void constructMainRangeFromSubranges(LiveInterval &LI)
For live interval LI with correct SubRanges construct matching information for the main live range.
LiveInterval & createEmptyInterval(Register Reg)
Interval creation.
LLVM_ABI void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
LLVM_ABI void print(raw_ostream &O) const
Implement the dump method.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
bool empty() const
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
iterator begin()
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
mop_range operands()
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
LLVM_ABI void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI void clearKillInfo()
Clears kill flags on all operands.
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_TargetIndex
Target-dependent index+offset operand.
@ MO_FPImmediate
Floating-point immediate operand.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI bool isLiveIn(Register Reg) const
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level.
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
iterator_range< use_iterator > use_operands(Register Reg) const
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
bool isIntReg(MCRegister Reg)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
RegState
Flags to represent properties of register accesses.
@ Kill
The last use of a register.
@ Done
Definition Threading.h:60
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
FunctionPass * createHexagonExpandCondsets()
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RegState getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Sub
Subtraction of integers.
char & HexagonExpandCondsetsID
DWARFExpression::Operation Op
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr RegState getUndefRegState(bool B)
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58