blob: 624a713a80d9ae986af7f1ae0ed95a049731fc07 [file] [log] [blame]
Krzysztof Parzyszek8b26fbf2015-07-09 15:40:25 +00001//===--- HexagonExpandCondsets.cpp ----------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +000010// Replace mux instructions with the corresponding legal instructions.
11// It is meant to work post-SSA, but still on virtual registers. It was
12// originally placed between register coalescing and machine instruction
13// scheduler.
14// In this place in the optimization sequence, live interval analysis had
15// been performed, and the live intervals should be preserved. A large part
16// of the code deals with preserving the liveness information.
17//
18// Liveness tracking aside, the main functionality of this pass is divided
19// into two steps. The first step is to replace an instruction
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +000020// vreg0 = C2_mux vreg1, vreg2, vreg3
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +000021// with a pair of conditional transfers
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +000022// vreg0 = A2_tfrt vreg1, vreg2
23// vreg0 = A2_tfrf vreg1, vreg3
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +000024// It is the intention that the execution of this pass could be terminated
25// after this step, and the code generated would be functionally correct.
26//
27// If the uses of the source values vreg1 and vreg2 are kills, and their
28// definitions are predicable, then in the second step, the conditional
29// transfers will then be rewritten as predicated instructions. E.g.
30// vreg0 = A2_or vreg1, vreg2
31// vreg3 = A2_tfrt vreg99, vreg0<kill>
32// will be rewritten as
33// vreg3 = A2_port vreg99, vreg1, vreg2
34//
35// This replacement has two variants: "up" and "down". Consider this case:
36// vreg0 = A2_or vreg1, vreg2
37// ... [intervening instructions] ...
38// vreg3 = A2_tfrt vreg99, vreg0<kill>
39// variant "up":
40// vreg3 = A2_port vreg99, vreg1, vreg2
41// ... [intervening instructions, vreg0->vreg3] ...
42// [deleted]
43// variant "down":
44// [deleted]
45// ... [intervening instructions] ...
46// vreg3 = A2_port vreg99, vreg1, vreg2
47//
48// Both, one or none of these variants may be valid, and checks are made
49// to rule out inapplicable variants.
50//
51// As an additional optimization, before either of the two steps above is
52// executed, the pass attempts to coalesce the target register with one of
53// the source registers, e.g. given an instruction
54// vreg3 = C2_mux vreg0, vreg1, vreg2
55// vreg3 will be coalesced with either vreg1 or vreg2. If this succeeds,
56// the instruction would then be (for example)
57// vreg3 = C2_mux vreg0, vreg3, vreg2
58// and, under certain circumstances, this could result in only one predicated
59// instruction:
60// vreg3 = A2_tfrf vreg0, vreg2
61//
62
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +000063// Splitting a definition of a register into two predicated transfers
64// creates a complication in liveness tracking. Live interval computation
65// will see both instructions as actual definitions, and will mark the
66// first one as dead. The definition is not actually dead, and this
67// situation will need to be fixed. For example:
68// vreg1<def,dead> = A2_tfrt ... ; marked as dead
69// vreg1<def> = A2_tfrf ...
70//
71// Since any of the individual predicated transfers may end up getting
72// removed (in case it is an identity copy), some pre-existing def may
73// be marked as dead after live interval recomputation:
74// vreg1<def,dead> = ... ; marked as dead
75// ...
76// vreg1<def> = A2_tfrf ... ; if A2_tfrt is removed
77// This case happens if vreg1 was used as a source in A2_tfrt, which means
78// that is it actually live at the A2_tfrf, and so the now dead definition
79// of vreg1 will need to be updated to non-dead at some point.
80//
81// This issue could be remedied by adding implicit uses to the predicated
82// transfers, but this will create a problem with subsequent predication,
83// since the transfers will no longer be possible to reorder. To avoid
84// that, the initial splitting will not add any implicit uses. These
85// implicit uses will be added later, after predication. The extra price,
86// however, is that finding the locations where the implicit uses need
87// to be added, and updating the live ranges will be more involved.
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +000088
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +000089#define DEBUG_TYPE "expand-condsets"
90
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000091#include "HexagonInstrInfo.h"
92#include "llvm/ADT/DenseMap.h"
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +000093#include "llvm/ADT/SetVector.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000094#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringRef.h"
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +000096#include "llvm/CodeGen/LiveInterval.h"
97#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000098#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +000099#include "llvm/CodeGen/MachineDominators.h"
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000100#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000101#include "llvm/CodeGen/MachineFunctionPass.h"
102#include "llvm/CodeGen/MachineInstr.h"
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000103#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000104#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000105#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000106#include "llvm/CodeGen/SlotIndexes.h"
107#include "llvm/IR/DebugLoc.h"
108#include "llvm/Pass.h"
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000109#include "llvm/Support/CommandLine.h"
110#include "llvm/Support/Debug.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000111#include "llvm/Support/ErrorHandling.h"
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000112#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000113#include "llvm/Target/TargetRegisterInfo.h"
114#include <cassert>
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000115#include <iterator>
116#include <set>
117#include <utility>
118
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000119using namespace llvm;
120
121static cl::opt<unsigned> OptTfrLimit("expand-condsets-tfr-limit",
122 cl::init(~0U), cl::Hidden, cl::desc("Max number of mux expansions"));
123static cl::opt<unsigned> OptCoaLimit("expand-condsets-coa-limit",
124 cl::init(~0U), cl::Hidden, cl::desc("Max number of segment coalescings"));
125
126namespace llvm {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000127
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000128 void initializeHexagonExpandCondsetsPass(PassRegistry&);
129 FunctionPass *createHexagonExpandCondsets();
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000130
131} // end namespace llvm
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000132
133namespace {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000134
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000135 class HexagonExpandCondsets : public MachineFunctionPass {
136 public:
137 static char ID;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000138
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000139 HexagonExpandCondsets() :
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000140 MachineFunctionPass(ID), HII(nullptr), TRI(nullptr), MRI(nullptr),
141 LIS(nullptr), CoaLimitActive(false),
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000142 TfrLimitActive(false), CoaCounter(0), TfrCounter(0) {
143 if (OptCoaLimit.getPosition())
144 CoaLimitActive = true, CoaLimit = OptCoaLimit;
145 if (OptTfrLimit.getPosition())
146 TfrLimitActive = true, TfrLimit = OptTfrLimit;
147 initializeHexagonExpandCondsetsPass(*PassRegistry::getPassRegistry());
148 }
149
Mehdi Amini117296c2016-10-01 02:56:57 +0000150 StringRef getPassName() const override { return "Hexagon Expand Condsets"; }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000151
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000152 void getAnalysisUsage(AnalysisUsage &AU) const override {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000153 AU.addRequired<LiveIntervals>();
154 AU.addPreserved<LiveIntervals>();
155 AU.addPreserved<SlotIndexes>();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000156 AU.addRequired<MachineDominatorTree>();
157 AU.addPreserved<MachineDominatorTree>();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000158 MachineFunctionPass::getAnalysisUsage(AU);
159 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000160
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000161 bool runOnMachineFunction(MachineFunction &MF) override;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000162
163 private:
164 const HexagonInstrInfo *HII;
165 const TargetRegisterInfo *TRI;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000166 MachineDominatorTree *MDT;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000167 MachineRegisterInfo *MRI;
168 LiveIntervals *LIS;
169
170 bool CoaLimitActive, TfrLimitActive;
171 unsigned CoaLimit, TfrLimit, CoaCounter, TfrCounter;
172
173 struct RegisterRef {
174 RegisterRef(const MachineOperand &Op) : Reg(Op.getReg()),
175 Sub(Op.getSubReg()) {}
176 RegisterRef(unsigned R = 0, unsigned S = 0) : Reg(R), Sub(S) {}
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000177
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000178 bool operator== (RegisterRef RR) const {
179 return Reg == RR.Reg && Sub == RR.Sub;
180 }
181 bool operator!= (RegisterRef RR) const { return !operator==(RR); }
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000182 bool operator< (RegisterRef RR) const {
183 return Reg < RR.Reg || (Reg == RR.Reg && Sub < RR.Sub);
184 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000185
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000186 unsigned Reg, Sub;
187 };
188
189 typedef DenseMap<unsigned,unsigned> ReferenceMap;
190 enum { Sub_Low = 0x1, Sub_High = 0x2, Sub_None = (Sub_Low | Sub_High) };
191 enum { Exec_Then = 0x10, Exec_Else = 0x20 };
192 unsigned getMaskForSub(unsigned Sub);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000193 bool isCondset(const MachineInstr &MI);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000194 LaneBitmask getLaneMask(unsigned Reg, unsigned Sub);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000195
196 void addRefToMap(RegisterRef RR, ReferenceMap &Map, unsigned Exec);
197 bool isRefInMap(RegisterRef, ReferenceMap &Map, unsigned Exec);
198
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000199 void updateDeadsInRange(unsigned Reg, LaneBitmask LM, LiveRange &Range);
200 void updateKillFlags(unsigned Reg);
201 void updateDeadFlags(unsigned Reg);
202 void recalculateLiveInterval(unsigned Reg);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000203 void removeInstr(MachineInstr &MI);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000204 void updateLiveness(std::set<unsigned> &RegSet, bool Recalc,
205 bool UpdateKills, bool UpdateDeads);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000206
207 unsigned getCondTfrOpcode(const MachineOperand &SO, bool Cond);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000208 MachineInstr *genCondTfrFor(MachineOperand &SrcOp,
209 MachineBasicBlock::iterator At, unsigned DstR,
210 unsigned DstSR, const MachineOperand &PredOp, bool PredSense,
211 bool ReadUndef, bool ImpUse);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000212 bool split(MachineInstr &MI, std::set<unsigned> &UpdRegs);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000213
214 bool isPredicable(MachineInstr *MI);
215 MachineInstr *getReachingDefForPred(RegisterRef RD,
216 MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000217 bool canMoveOver(MachineInstr &MI, ReferenceMap &Defs, ReferenceMap &Uses);
218 bool canMoveMemTo(MachineInstr &MI, MachineInstr &ToI, bool IsDown);
219 void predicateAt(const MachineOperand &DefOp, MachineInstr &MI,
220 MachineBasicBlock::iterator Where,
221 const MachineOperand &PredOp, bool Cond,
222 std::set<unsigned> &UpdRegs);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000223 void renameInRange(RegisterRef RO, RegisterRef RN, unsigned PredR,
224 bool Cond, MachineBasicBlock::iterator First,
225 MachineBasicBlock::iterator Last);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000226 bool predicate(MachineInstr &TfrI, bool Cond, std::set<unsigned> &UpdRegs);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000227 bool predicateInBlock(MachineBasicBlock &B,
228 std::set<unsigned> &UpdRegs);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000229
230 bool isIntReg(RegisterRef RR, unsigned &BW);
231 bool isIntraBlocks(LiveInterval &LI);
232 bool coalesceRegisters(RegisterRef R1, RegisterRef R2);
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000233 bool coalesceSegments(const SmallVectorImpl<MachineInstr*> &Condsets,
234 std::set<unsigned> &UpdRegs);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000235 };
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000236
237} // end anonymous namespace
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000238
239char HexagonExpandCondsets::ID = 0;
240
Krzysztof Parzyszek951fb362016-08-24 22:27:36 +0000241namespace llvm {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000242
Krzysztof Parzyszek951fb362016-08-24 22:27:36 +0000243 char &HexagonExpandCondsetsID = HexagonExpandCondsets::ID;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000244
245} // end namespace llvm
Krzysztof Parzyszek951fb362016-08-24 22:27:36 +0000246
Krzysztof Parzyszek764fed92016-05-27 21:15:34 +0000247INITIALIZE_PASS_BEGIN(HexagonExpandCondsets, "expand-condsets",
248 "Hexagon Expand Condsets", false, false)
249INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
250INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
251INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
252INITIALIZE_PASS_END(HexagonExpandCondsets, "expand-condsets",
253 "Hexagon Expand Condsets", false, false)
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000254
255unsigned HexagonExpandCondsets::getMaskForSub(unsigned Sub) {
256 switch (Sub) {
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000257 case Hexagon::isub_lo:
258 case Hexagon::vsub_lo:
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000259 return Sub_Low;
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000260 case Hexagon::isub_hi:
261 case Hexagon::vsub_hi:
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000262 return Sub_High;
263 case Hexagon::NoSubRegister:
264 return Sub_None;
265 }
266 llvm_unreachable("Invalid subregister");
267}
268
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000269bool HexagonExpandCondsets::isCondset(const MachineInstr &MI) {
270 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000271 switch (Opc) {
272 case Hexagon::C2_mux:
273 case Hexagon::C2_muxii:
274 case Hexagon::C2_muxir:
275 case Hexagon::C2_muxri:
Krzysztof Parzyszek258af192016-08-11 19:12:18 +0000276 case Hexagon::PS_pselect:
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000277 return true;
278 break;
279 }
280 return false;
281}
282
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000283LaneBitmask HexagonExpandCondsets::getLaneMask(unsigned Reg, unsigned Sub) {
284 assert(TargetRegisterInfo::isVirtualRegister(Reg));
285 return Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
286 : MRI->getMaxLaneMaskForVReg(Reg);
287}
288
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000289void HexagonExpandCondsets::addRefToMap(RegisterRef RR, ReferenceMap &Map,
290 unsigned Exec) {
291 unsigned Mask = getMaskForSub(RR.Sub) | Exec;
292 ReferenceMap::iterator F = Map.find(RR.Reg);
293 if (F == Map.end())
294 Map.insert(std::make_pair(RR.Reg, Mask));
295 else
296 F->second |= Mask;
297}
298
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000299bool HexagonExpandCondsets::isRefInMap(RegisterRef RR, ReferenceMap &Map,
300 unsigned Exec) {
301 ReferenceMap::iterator F = Map.find(RR.Reg);
302 if (F == Map.end())
303 return false;
304 unsigned Mask = getMaskForSub(RR.Sub) | Exec;
305 if (Mask & F->second)
306 return true;
307 return false;
308}
309
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000310void HexagonExpandCondsets::updateKillFlags(unsigned Reg) {
311 auto KillAt = [this,Reg] (SlotIndex K, LaneBitmask LM) -> void {
312 // Set the <kill> flag on a use of Reg whose lane mask is contained in LM.
313 MachineInstr *MI = LIS->getInstructionFromIndex(K);
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000314 for (auto &Op : MI->operands()) {
Krzysztof Parzyszek1bba8962016-07-01 20:45:19 +0000315 if (!Op.isReg() || !Op.isUse() || Op.getReg() != Reg)
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000316 continue;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000317 LaneBitmask SLM = getLaneMask(Reg, Op.getSubReg());
318 if ((SLM & LM) == SLM) {
319 // Only set the kill flag on the first encountered use of Reg in this
320 // instruction.
321 Op.setIsKill(true);
322 break;
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000323 }
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000324 }
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000325 };
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000326
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000327 LiveInterval &LI = LIS->getInterval(Reg);
328 for (auto I = LI.begin(), E = LI.end(); I != E; ++I) {
329 if (!I->end.isRegister())
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000330 continue;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000331 // Do not mark the end of the segment as <kill>, if the next segment
332 // starts with a predicated instruction.
333 auto NextI = std::next(I);
334 if (NextI != E && NextI->start.isRegister()) {
335 MachineInstr *DefI = LIS->getInstructionFromIndex(NextI->start);
336 if (HII->isPredicated(*DefI))
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000337 continue;
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000338 }
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000339 bool WholeReg = true;
340 if (LI.hasSubRanges()) {
341 auto EndsAtI = [I] (LiveInterval::SubRange &S) -> bool {
342 LiveRange::iterator F = S.find(I->end);
343 return F != S.end() && I->end == F->end;
344 };
345 // Check if all subranges end at I->end. If so, make sure to kill
346 // the whole register.
347 for (LiveInterval::SubRange &S : LI.subranges()) {
348 if (EndsAtI(S))
349 KillAt(I->end, S.LaneMask);
350 else
351 WholeReg = false;
352 }
353 }
354 if (WholeReg)
355 KillAt(I->end, MRI->getMaxLaneMaskForVReg(Reg));
356 }
357}
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000358
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000359void HexagonExpandCondsets::updateDeadsInRange(unsigned Reg, LaneBitmask LM,
360 LiveRange &Range) {
361 assert(TargetRegisterInfo::isVirtualRegister(Reg));
362 if (Range.empty())
363 return;
364
365 auto IsRegDef = [this,Reg,LM] (MachineOperand &Op) -> bool {
366 if (!Op.isReg() || !Op.isDef())
367 return false;
368 unsigned DR = Op.getReg(), DSR = Op.getSubReg();
369 if (!TargetRegisterInfo::isVirtualRegister(DR) || DR != Reg)
370 return false;
371 LaneBitmask SLM = getLaneMask(DR, DSR);
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000372 return (SLM & LM).any();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000373 };
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
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000382 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(Dest->pred_begin(), Dest->pred_end());
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 for (auto *P : B->predecessors())
397 Work.insert(P);
398 }
399 return true;
400 };
401
402 // First, try to extend live range within individual basic blocks. This
403 // will leave us only with dead defs that do not reach any predicated
404 // defs in the same block.
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000405 SetVector<MachineBasicBlock*> Defs;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000406 SmallVector<SlotIndex,4> PredDefs;
407 for (auto &Seg : Range) {
408 if (!Seg.start.isRegister())
409 continue;
410 MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000411 Defs.insert(DefI->getParent());
412 if (HII->isPredicated(*DefI))
413 PredDefs.push_back(Seg.start);
414 }
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000415
416 SmallVector<SlotIndex,8> Undefs;
417 LiveInterval &LI = LIS->getInterval(Reg);
418 LI.computeSubRangeUndefs(Undefs, LM, *MRI, *LIS->getSlotIndexes());
419
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000420 for (auto &SI : PredDefs) {
421 MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000422 auto P = Range.extendInBlock(Undefs, LIS->getMBBStartIdx(BB), SI);
423 if (P.first != nullptr || P.second)
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000424 SI = SlotIndex();
425 }
426
427 // Calculate reachability for those predicated defs that were not handled
428 // by the in-block extension.
429 SmallVector<SlotIndex,4> ExtTo;
430 for (auto &SI : PredDefs) {
431 if (!SI.isValid())
432 continue;
433 MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
434 if (BB->pred_empty())
435 continue;
436 // If the defs from this range reach SI via all predecessors, it is live.
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000437 // It can happen that SI is reached by the defs through some paths, but
438 // not all. In the IR coming into this optimization, SI would not be
439 // considered live, since the defs would then not jointly dominate SI.
440 // That means that SI is an overwriting def, and no implicit use is
441 // needed at this point. Do not add SI to the extension points, since
442 // extendToIndices will abort if there is no joint dominance.
443 // If the abort was avoided by adding extra undefs added to Undefs,
444 // extendToIndices could actually indicate that SI is live, contrary
445 // to the original IR.
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000446 if (Dominate(Defs, BB))
447 ExtTo.push_back(SI);
448 }
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000449
450 if (!ExtTo.empty())
451 LIS->extendToIndices(Range, ExtTo, Undefs);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000452
453 // Remove <dead> flags from all defs that are not dead after live range
454 // extension, and collect all def operands. They will be used to generate
455 // the necessary implicit uses.
456 std::set<RegisterRef> DefRegs;
457 for (auto &Seg : Range) {
458 if (!Seg.start.isRegister())
459 continue;
460 MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000461 for (auto &Op : DefI->operands()) {
462 if (Seg.start.isDead() || !IsRegDef(Op))
463 continue;
464 DefRegs.insert(Op);
465 Op.setIsDead(false);
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000466 }
467 }
468
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000469 // Finally, add implicit uses to each predicated def that is reached
Krzysztof Parzyszekcbd559f2016-08-24 16:36:37 +0000470 // by other defs.
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000471 for (auto &Seg : Range) {
472 if (!Seg.start.isRegister() || !Range.liveAt(Seg.start.getPrevSlot()))
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000473 continue;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000474 MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
475 if (!HII->isPredicated(*DefI))
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000476 continue;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000477 // Construct the set of all necessary implicit uses, based on the def
478 // operands in the instruction.
479 std::set<RegisterRef> ImpUses;
480 for (auto &Op : DefI->operands())
481 if (Op.isReg() && Op.isDef() && DefRegs.count(Op))
482 ImpUses.insert(Op);
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000483 if (ImpUses.empty())
484 continue;
485 MachineFunction &MF = *DefI->getParent()->getParent();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000486 for (RegisterRef R : ImpUses)
487 MachineInstrBuilder(MF, DefI).addReg(R.Reg, RegState::Implicit, R.Sub);
Krzysztof Parzyszek8b617592016-06-07 19:25:28 +0000488 }
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000489}
490
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000491void HexagonExpandCondsets::updateDeadFlags(unsigned Reg) {
492 LiveInterval &LI = LIS->getInterval(Reg);
493 if (LI.hasSubRanges()) {
494 for (LiveInterval::SubRange &S : LI.subranges()) {
495 updateDeadsInRange(Reg, S.LaneMask, S);
496 LIS->shrinkToUses(S, Reg);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000497 }
498 LI.clear();
499 LIS->constructMainRangeFromSubranges(LI);
500 } else {
501 updateDeadsInRange(Reg, MRI->getMaxLaneMaskForVReg(Reg), LI);
502 }
503}
504
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000505void HexagonExpandCondsets::recalculateLiveInterval(unsigned Reg) {
506 LIS->removeInterval(Reg);
507 LIS->createAndComputeVirtRegInterval(Reg);
508}
509
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000510void HexagonExpandCondsets::removeInstr(MachineInstr &MI) {
511 LIS->RemoveMachineInstrFromMaps(MI);
512 MI.eraseFromParent();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000513}
514
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000515void HexagonExpandCondsets::updateLiveness(std::set<unsigned> &RegSet,
516 bool Recalc, bool UpdateKills, bool UpdateDeads) {
517 UpdateKills |= UpdateDeads;
518 for (auto R : RegSet) {
519 if (Recalc)
520 recalculateLiveInterval(R);
521 if (UpdateKills)
522 MRI->clearKillFlags(R);
523 if (UpdateDeads)
524 updateDeadFlags(R);
525 // Fixing <dead> flags may extend live ranges, so reset <kill> flags
526 // after that.
527 if (UpdateKills)
528 updateKillFlags(R);
529 LIS->getInterval(R).verify();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000530 }
531}
532
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000533/// Get the opcode for a conditional transfer of the value in SO (source
534/// operand). The condition (true/false) is given in Cond.
535unsigned HexagonExpandCondsets::getCondTfrOpcode(const MachineOperand &SO,
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000536 bool IfTrue) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000537 using namespace Hexagon;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000538
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000539 if (SO.isReg()) {
540 unsigned PhysR;
541 RegisterRef RS = SO;
542 if (TargetRegisterInfo::isVirtualRegister(RS.Reg)) {
543 const TargetRegisterClass *VC = MRI->getRegClass(RS.Reg);
544 assert(VC->begin() != VC->end() && "Empty register class");
545 PhysR = *VC->begin();
546 } else {
547 assert(TargetRegisterInfo::isPhysicalRegister(RS.Reg));
548 PhysR = RS.Reg;
549 }
550 unsigned PhysS = (RS.Sub == 0) ? PhysR : TRI->getSubReg(PhysR, RS.Sub);
551 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysS);
552 switch (RC->getSize()) {
553 case 4:
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000554 return IfTrue ? A2_tfrt : A2_tfrf;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000555 case 8:
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000556 return IfTrue ? A2_tfrpt : A2_tfrpf;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000557 }
558 llvm_unreachable("Invalid register operand");
559 }
560 if (SO.isImm() || SO.isFPImm())
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000561 return IfTrue ? C2_cmoveit : C2_cmoveif;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000562 llvm_unreachable("Unexpected source operand");
563}
564
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000565/// Generate a conditional transfer, copying the value SrcOp to the
566/// destination register DstR:DstSR, and using the predicate register from
567/// PredOp. The Cond argument specifies whether the predicate is to be
568/// if(PredOp), or if(!PredOp).
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000569MachineInstr *HexagonExpandCondsets::genCondTfrFor(MachineOperand &SrcOp,
570 MachineBasicBlock::iterator At,
571 unsigned DstR, unsigned DstSR, const MachineOperand &PredOp,
572 bool PredSense, bool ReadUndef, bool ImpUse) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000573 MachineInstr *MI = SrcOp.getParent();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000574 MachineBasicBlock &B = *At->getParent();
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +0000575 const DebugLoc &DL = MI->getDebugLoc();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000576
577 // Don't avoid identity copies here (i.e. if the source and the destination
578 // are the same registers). It is actually better to generate them here,
579 // since this would cause the copy to potentially be predicated in the next
580 // step. The predication will remove such a copy if it is unable to
581 /// predicate.
582
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000583 unsigned Opc = getCondTfrOpcode(SrcOp, PredSense);
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000584 unsigned DstState = RegState::Define | (ReadUndef ? RegState::Undef : 0);
585 unsigned PredState = getRegState(PredOp) & ~RegState::Kill;
586 MachineInstrBuilder MIB;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000587
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000588 if (SrcOp.isReg()) {
589 unsigned SrcState = getRegState(SrcOp);
590 if (RegisterRef(SrcOp) == RegisterRef(DstR, DstSR))
591 SrcState &= ~RegState::Kill;
592 MIB = BuildMI(B, At, DL, HII->get(Opc))
593 .addReg(DstR, DstState, DstSR)
594 .addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
595 .addReg(SrcOp.getReg(), SrcState, SrcOp.getSubReg());
596 } else {
597 MIB = BuildMI(B, At, DL, HII->get(Opc))
Diana Picus116bbab2017-01-13 09:58:52 +0000598 .addReg(DstR, DstState, DstSR)
599 .addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
600 .add(SrcOp);
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +0000601 }
602
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000603 DEBUG(dbgs() << "created an initial copy: " << *MIB);
604 return &*MIB;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000605}
606
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000607/// Replace a MUX instruction MI with a pair A2_tfrt/A2_tfrf. This function
608/// performs all necessary changes to complete the replacement.
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000609bool HexagonExpandCondsets::split(MachineInstr &MI,
610 std::set<unsigned> &UpdRegs) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000611 if (TfrLimitActive) {
612 if (TfrCounter >= TfrLimit)
613 return false;
614 TfrCounter++;
615 }
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000616 DEBUG(dbgs() << "\nsplitting BB#" << MI.getParent()->getNumber() << ": "
617 << MI);
618 MachineOperand &MD = MI.getOperand(0); // Definition
619 MachineOperand &MP = MI.getOperand(1); // Predicate register
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000620 assert(MD.isDef());
621 unsigned DR = MD.getReg(), DSR = MD.getSubReg();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000622 bool ReadUndef = MD.isUndef();
623 MachineBasicBlock::iterator At = MI;
624
Krzysztof Parzyszek22586dc2016-10-31 15:45:09 +0000625 // If this is a mux of the same register, just replace it with COPY.
626 // Ideally, this would happen earlier, so that register coalescing would
627 // see it.
628 MachineOperand &ST = MI.getOperand(2);
629 MachineOperand &SF = MI.getOperand(3);
630 if (ST.isReg() && SF.isReg()) {
631 RegisterRef RT(ST);
632 if (RT == RegisterRef(SF)) {
633 MI.setDesc(HII->get(TargetOpcode::COPY));
634 unsigned S = getRegState(ST);
635 while (MI.getNumOperands() > 1)
636 MI.RemoveOperand(MI.getNumOperands()-1);
637 MachineFunction &MF = *MI.getParent()->getParent();
638 MachineInstrBuilder(MF, MI).addReg(RT.Reg, S, RT.Sub);
639 return true;
640 }
641 }
642
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000643 // First, create the two invididual conditional transfers, and add each
644 // of them to the live intervals information. Do that first and then remove
645 // the old instruction from live intervals.
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000646 MachineInstr *TfrT =
Krzysztof Parzyszek22586dc2016-10-31 15:45:09 +0000647 genCondTfrFor(ST, At, DR, DSR, MP, true, ReadUndef, false);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000648 MachineInstr *TfrF =
Krzysztof Parzyszek22586dc2016-10-31 15:45:09 +0000649 genCondTfrFor(SF, At, DR, DSR, MP, false, ReadUndef, true);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000650 LIS->InsertMachineInstrInMaps(*TfrT);
651 LIS->InsertMachineInstrInMaps(*TfrF);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000652
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000653 // Will need to recalculate live intervals for all registers in MI.
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000654 for (auto &Op : MI.operands())
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000655 if (Op.isReg())
656 UpdRegs.insert(Op.getReg());
657
658 removeInstr(MI);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000659 return true;
660}
661
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000662bool HexagonExpandCondsets::isPredicable(MachineInstr *MI) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000663 if (HII->isPredicated(*MI) || !HII->isPredicable(*MI))
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000664 return false;
665 if (MI->hasUnmodeledSideEffects() || MI->mayStore())
666 return false;
667 // Reject instructions with multiple defs (e.g. post-increment loads).
668 bool HasDef = false;
669 for (auto &Op : MI->operands()) {
670 if (!Op.isReg() || !Op.isDef())
671 continue;
672 if (HasDef)
673 return false;
674 HasDef = true;
675 }
676 for (auto &Mo : MI->memoperands())
677 if (Mo->isVolatile())
678 return false;
679 return true;
680}
681
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000682/// Find the reaching definition for a predicated use of RD. The RD is used
683/// under the conditions given by PredR and Cond, and this function will ignore
684/// definitions that set RD under the opposite conditions.
685MachineInstr *HexagonExpandCondsets::getReachingDefForPred(RegisterRef RD,
686 MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond) {
687 MachineBasicBlock &B = *UseIt->getParent();
688 MachineBasicBlock::iterator I = UseIt, S = B.begin();
689 if (I == S)
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000690 return nullptr;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000691
692 bool PredValid = true;
693 do {
694 --I;
695 MachineInstr *MI = &*I;
696 // Check if this instruction can be ignored, i.e. if it is predicated
697 // on the complementary condition.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000698 if (PredValid && HII->isPredicated(*MI)) {
699 if (MI->readsRegister(PredR) && (Cond != HII->isPredicatedTrue(*MI)))
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000700 continue;
701 }
702
703 // Check the defs. If the PredR is defined, invalidate it. If RD is
704 // defined, return the instruction or 0, depending on the circumstances.
705 for (auto &Op : MI->operands()) {
706 if (!Op.isReg() || !Op.isDef())
707 continue;
708 RegisterRef RR = Op;
709 if (RR.Reg == PredR) {
710 PredValid = false;
711 continue;
712 }
713 if (RR.Reg != RD.Reg)
714 continue;
715 // If the "Reg" part agrees, there is still the subregister to check.
716 // If we are looking for vreg1:loreg, we can skip vreg1:hireg, but
717 // not vreg1 (w/o subregisters).
718 if (RR.Sub == RD.Sub)
719 return MI;
720 if (RR.Sub == 0 || RD.Sub == 0)
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000721 return nullptr;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000722 // We have different subregisters, so we can continue looking.
723 }
724 } while (I != S);
725
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000726 return nullptr;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000727}
728
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000729/// Check if the instruction MI can be safely moved over a set of instructions
730/// whose side-effects (in terms of register defs and uses) are expressed in
731/// the maps Defs and Uses. These maps reflect the conditional defs and uses
732/// that depend on the same predicate register to allow moving instructions
733/// over instructions predicated on the opposite condition.
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000734bool HexagonExpandCondsets::canMoveOver(MachineInstr &MI, ReferenceMap &Defs,
735 ReferenceMap &Uses) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000736 // In order to be able to safely move MI over instructions that define
737 // "Defs" and use "Uses", no def operand from MI can be defined or used
738 // and no use operand can be defined.
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000739 for (auto &Op : MI.operands()) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000740 if (!Op.isReg())
741 continue;
742 RegisterRef RR = Op;
743 // For physical register we would need to check register aliases, etc.
744 // and we don't want to bother with that. It would be of little value
745 // before the actual register rewriting (from virtual to physical).
746 if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
747 return false;
748 // No redefs for any operand.
749 if (isRefInMap(RR, Defs, Exec_Then))
750 return false;
751 // For defs, there cannot be uses.
752 if (Op.isDef() && isRefInMap(RR, Uses, Exec_Then))
753 return false;
754 }
755 return true;
756}
757
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000758/// Check if the instruction accessing memory (TheI) can be moved to the
759/// location ToI.
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000760bool HexagonExpandCondsets::canMoveMemTo(MachineInstr &TheI, MachineInstr &ToI,
761 bool IsDown) {
762 bool IsLoad = TheI.mayLoad(), IsStore = TheI.mayStore();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000763 if (!IsLoad && !IsStore)
764 return true;
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000765 if (HII->areMemAccessesTriviallyDisjoint(TheI, ToI))
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000766 return true;
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000767 if (TheI.hasUnmodeledSideEffects())
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000768 return false;
769
770 MachineBasicBlock::iterator StartI = IsDown ? TheI : ToI;
771 MachineBasicBlock::iterator EndI = IsDown ? ToI : TheI;
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000772 bool Ordered = TheI.hasOrderedMemoryRef();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000773
774 // Search for aliased memory reference in (StartI, EndI).
775 for (MachineBasicBlock::iterator I = std::next(StartI); I != EndI; ++I) {
776 MachineInstr *MI = &*I;
777 if (MI->hasUnmodeledSideEffects())
778 return false;
779 bool L = MI->mayLoad(), S = MI->mayStore();
780 if (!L && !S)
781 continue;
782 if (Ordered && MI->hasOrderedMemoryRef())
783 return false;
784
785 bool Conflict = (L && IsStore) || S;
786 if (Conflict)
787 return false;
788 }
789 return true;
790}
791
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000792/// Generate a predicated version of MI (where the condition is given via
793/// PredR and Cond) at the point indicated by Where.
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000794void HexagonExpandCondsets::predicateAt(const MachineOperand &DefOp,
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000795 MachineInstr &MI,
796 MachineBasicBlock::iterator Where,
797 const MachineOperand &PredOp, bool Cond,
798 std::set<unsigned> &UpdRegs) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000799 // The problem with updating live intervals is that we can move one def
800 // past another def. In particular, this can happen when moving an A2_tfrt
801 // over an A2_tfrf defining the same register. From the point of view of
802 // live intervals, these two instructions are two separate definitions,
803 // and each one starts another live segment. LiveIntervals's "handleMove"
804 // does not allow such moves, so we need to handle it ourselves. To avoid
805 // invalidating liveness data while we are using it, the move will be
806 // implemented in 4 steps: (1) add a clone of the instruction MI at the
807 // target location, (2) update liveness, (3) delete the old instruction,
808 // and (4) update liveness again.
809
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000810 MachineBasicBlock &B = *MI.getParent();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000811 DebugLoc DL = Where->getDebugLoc(); // "Where" points to an instruction.
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000812 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000813 unsigned PredOpc = HII->getCondOpcode(Opc, !Cond);
814 MachineInstrBuilder MB = BuildMI(B, Where, DL, HII->get(PredOpc));
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000815 unsigned Ox = 0, NP = MI.getNumOperands();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000816 // Skip all defs from MI first.
817 while (Ox < NP) {
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000818 MachineOperand &MO = MI.getOperand(Ox);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000819 if (!MO.isReg() || !MO.isDef())
820 break;
821 Ox++;
822 }
823 // Add the new def, then the predicate register, then the rest of the
824 // operands.
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000825 MB.addReg(DefOp.getReg(), getRegState(DefOp), DefOp.getSubReg());
826 MB.addReg(PredOp.getReg(), PredOp.isUndef() ? RegState::Undef : 0,
827 PredOp.getSubReg());
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000828 while (Ox < NP) {
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000829 MachineOperand &MO = MI.getOperand(Ox);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000830 if (!MO.isReg() || !MO.isImplicit())
Diana Picus116bbab2017-01-13 09:58:52 +0000831 MB.add(MO);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000832 Ox++;
833 }
834
835 MachineFunction &MF = *B.getParent();
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000836 MachineInstr::mmo_iterator I = MI.memoperands_begin();
837 unsigned NR = std::distance(I, MI.memoperands_end());
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000838 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(NR);
839 for (unsigned i = 0; i < NR; ++i)
840 MemRefs[i] = *I++;
841 MB.setMemRefs(MemRefs, MemRefs+NR);
842
843 MachineInstr *NewI = MB;
844 NewI->clearKillInfo();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000845 LIS->InsertMachineInstrInMaps(*NewI);
846
847 for (auto &Op : NewI->operands())
848 if (Op.isReg())
849 UpdRegs.insert(Op.getReg());
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000850}
851
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000852/// In the range [First, Last], rename all references to the "old" register RO
853/// to the "new" register RN, but only in instructions predicated on the given
854/// condition.
855void HexagonExpandCondsets::renameInRange(RegisterRef RO, RegisterRef RN,
856 unsigned PredR, bool Cond, MachineBasicBlock::iterator First,
857 MachineBasicBlock::iterator Last) {
858 MachineBasicBlock::iterator End = std::next(Last);
859 for (MachineBasicBlock::iterator I = First; I != End; ++I) {
860 MachineInstr *MI = &*I;
861 // Do not touch instructions that are not predicated, or are predicated
862 // on the opposite condition.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000863 if (!HII->isPredicated(*MI))
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000864 continue;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000865 if (!MI->readsRegister(PredR) || (Cond != HII->isPredicatedTrue(*MI)))
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000866 continue;
867
868 for (auto &Op : MI->operands()) {
869 if (!Op.isReg() || RO != RegisterRef(Op))
870 continue;
871 Op.setReg(RN.Reg);
872 Op.setSubReg(RN.Sub);
873 // In practice, this isn't supposed to see any defs.
874 assert(!Op.isDef() && "Not expecting a def");
875 }
876 }
877}
878
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000879/// For a given conditional copy, predicate the definition of the source of
880/// the copy under the given condition (using the same predicate register as
881/// the copy).
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000882bool HexagonExpandCondsets::predicate(MachineInstr &TfrI, bool Cond,
883 std::set<unsigned> &UpdRegs) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000884 // TfrI - A2_tfr[tf] Instruction (not A2_tfrsi).
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000885 unsigned Opc = TfrI.getOpcode();
Simon Atanasyan772944a2015-03-31 19:43:47 +0000886 (void)Opc;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000887 assert(Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf);
888 DEBUG(dbgs() << "\nattempt to predicate if-" << (Cond ? "true" : "false")
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000889 << ": " << TfrI);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000890
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000891 MachineOperand &MD = TfrI.getOperand(0);
892 MachineOperand &MP = TfrI.getOperand(1);
893 MachineOperand &MS = TfrI.getOperand(2);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000894 // The source operand should be a <kill>. This is not strictly necessary,
895 // but it makes things a lot simpler. Otherwise, we would need to rename
896 // some registers, which would complicate the transformation considerably.
897 if (!MS.isKill())
898 return false;
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +0000899 // Avoid predicating instructions that define a subregister if subregister
900 // liveness tracking is not enabled.
901 if (MD.getSubReg() && !MRI->shouldTrackSubRegLiveness(MD.getReg()))
Krzysztof Parzyszeka5802732016-05-31 14:27:10 +0000902 return false;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000903
904 RegisterRef RT(MS);
905 unsigned PredR = MP.getReg();
906 MachineInstr *DefI = getReachingDefForPred(RT, TfrI, PredR, Cond);
907 if (!DefI || !isPredicable(DefI))
908 return false;
909
910 DEBUG(dbgs() << "Source def: " << *DefI);
911
912 // Collect the information about registers defined and used between the
913 // DefI and the TfrI.
914 // Map: reg -> bitmask of subregs
915 ReferenceMap Uses, Defs;
916 MachineBasicBlock::iterator DefIt = DefI, TfrIt = TfrI;
917
918 // Check if the predicate register is valid between DefI and TfrI.
919 // If it is, we can then ignore instructions predicated on the negated
920 // conditions when collecting def and use information.
921 bool PredValid = true;
922 for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000923 if (!I->modifiesRegister(PredR, nullptr))
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000924 continue;
925 PredValid = false;
926 break;
927 }
928
929 for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
930 MachineInstr *MI = &*I;
931 // If this instruction is predicated on the same register, it could
932 // potentially be ignored.
933 // By default assume that the instruction executes on the same condition
934 // as TfrI (Exec_Then), and also on the opposite one (Exec_Else).
935 unsigned Exec = Exec_Then | Exec_Else;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000936 if (PredValid && HII->isPredicated(*MI) && MI->readsRegister(PredR))
937 Exec = (Cond == HII->isPredicatedTrue(*MI)) ? Exec_Then : Exec_Else;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000938
939 for (auto &Op : MI->operands()) {
940 if (!Op.isReg())
941 continue;
942 // We don't want to deal with physical registers. The reason is that
943 // they can be aliased with other physical registers. Aliased virtual
944 // registers must share the same register number, and can only differ
945 // in the subregisters, which we are keeping track of. Physical
946 // registers ters no longer have subregisters---their super- and
947 // subregisters are other physical registers, and we are not checking
948 // that.
949 RegisterRef RR = Op;
950 if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
951 return false;
952
953 ReferenceMap &Map = Op.isDef() ? Defs : Uses;
Krzysztof Parzyszekb7eb7fc2016-11-04 20:41:03 +0000954 if (Op.isDef() && Op.isUndef()) {
955 assert(RR.Sub && "Expecting a subregister on <def,read-undef>");
956 // If this is a <def,read-undef>, then it invalidates the non-written
957 // part of the register. For the purpose of checking the validity of
958 // the move, assume that it modifies the whole register.
959 RR.Sub = 0;
960 }
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000961 addRefToMap(RR, Map, Exec);
962 }
963 }
964
965 // The situation:
966 // RT = DefI
967 // ...
968 // RD = TfrI ..., RT
969
970 // If the register-in-the-middle (RT) is used or redefined between
971 // DefI and TfrI, we may not be able proceed with this transformation.
972 // We can ignore a def that will not execute together with TfrI, and a
973 // use that will. If there is such a use (that does execute together with
974 // TfrI), we will not be able to move DefI down. If there is a use that
975 // executed if TfrI's condition is false, then RT must be available
976 // unconditionally (cannot be predicated).
977 // Essentially, we need to be able to rename RT to RD in this segment.
978 if (isRefInMap(RT, Defs, Exec_Then) || isRefInMap(RT, Uses, Exec_Else))
979 return false;
980 RegisterRef RD = MD;
981 // If the predicate register is defined between DefI and TfrI, the only
982 // potential thing to do would be to move the DefI down to TfrI, and then
983 // predicate. The reaching def (DefI) must be movable down to the location
984 // of the TfrI.
985 // If the target register of the TfrI (RD) is not used or defined between
986 // DefI and TfrI, consider moving TfrI up to DefI.
987 bool CanUp = canMoveOver(TfrI, Defs, Uses);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000988 bool CanDown = canMoveOver(*DefI, Defs, Uses);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000989 // The TfrI does not access memory, but DefI could. Check if it's safe
990 // to move DefI down to TfrI.
991 if (DefI->mayLoad() || DefI->mayStore())
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000992 if (!canMoveMemTo(*DefI, TfrI, true))
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +0000993 CanDown = false;
994
995 DEBUG(dbgs() << "Can move up: " << (CanUp ? "yes" : "no")
996 << ", can move down: " << (CanDown ? "yes\n" : "no\n"));
997 MachineBasicBlock::iterator PastDefIt = std::next(DefIt);
998 if (CanUp)
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +0000999 predicateAt(MD, *DefI, PastDefIt, MP, Cond, UpdRegs);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001000 else if (CanDown)
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +00001001 predicateAt(MD, *DefI, TfrIt, MP, Cond, UpdRegs);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001002 else
1003 return false;
1004
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001005 if (RT != RD) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001006 renameInRange(RT, RD, PredR, Cond, PastDefIt, TfrIt);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001007 UpdRegs.insert(RT.Reg);
1008 }
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001009
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001010 removeInstr(TfrI);
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +00001011 removeInstr(*DefI);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001012 return true;
1013}
1014
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001015/// Predicate all cases of conditional copies in the specified block.
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001016bool HexagonExpandCondsets::predicateInBlock(MachineBasicBlock &B,
1017 std::set<unsigned> &UpdRegs) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001018 bool Changed = false;
1019 MachineBasicBlock::iterator I, E, NextI;
1020 for (I = B.begin(), E = B.end(); I != E; I = NextI) {
1021 NextI = std::next(I);
1022 unsigned Opc = I->getOpcode();
1023 if (Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf) {
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +00001024 bool Done = predicate(*I, (Opc == Hexagon::A2_tfrt), UpdRegs);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001025 if (!Done) {
1026 // If we didn't predicate I, we may need to remove it in case it is
1027 // an "identity" copy, e.g. vreg1 = A2_tfrt vreg2, vreg1.
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001028 if (RegisterRef(I->getOperand(0)) == RegisterRef(I->getOperand(2))) {
1029 for (auto &Op : I->operands())
1030 if (Op.isReg())
1031 UpdRegs.insert(Op.getReg());
Duncan P. N. Exon Smith98226e32016-07-12 01:55:32 +00001032 removeInstr(*I);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001033 }
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001034 }
1035 Changed |= Done;
1036 }
1037 }
1038 return Changed;
1039}
1040
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001041bool HexagonExpandCondsets::isIntReg(RegisterRef RR, unsigned &BW) {
1042 if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
1043 return false;
1044 const TargetRegisterClass *RC = MRI->getRegClass(RR.Reg);
1045 if (RC == &Hexagon::IntRegsRegClass) {
1046 BW = 32;
1047 return true;
1048 }
1049 if (RC == &Hexagon::DoubleRegsRegClass) {
1050 BW = (RR.Sub != 0) ? 32 : 64;
1051 return true;
1052 }
1053 return false;
1054}
1055
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001056bool HexagonExpandCondsets::isIntraBlocks(LiveInterval &LI) {
1057 for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
1058 LiveRange::Segment &LR = *I;
1059 // Range must start at a register...
1060 if (!LR.start.isRegister())
1061 return false;
1062 // ...and end in a register or in a dead slot.
1063 if (!LR.end.isRegister() && !LR.end.isDead())
1064 return false;
1065 }
1066 return true;
1067}
1068
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001069bool HexagonExpandCondsets::coalesceRegisters(RegisterRef R1, RegisterRef R2) {
1070 if (CoaLimitActive) {
1071 if (CoaCounter >= CoaLimit)
1072 return false;
1073 CoaCounter++;
1074 }
1075 unsigned BW1, BW2;
1076 if (!isIntReg(R1, BW1) || !isIntReg(R2, BW2) || BW1 != BW2)
1077 return false;
1078 if (MRI->isLiveIn(R1.Reg))
1079 return false;
1080 if (MRI->isLiveIn(R2.Reg))
1081 return false;
1082
1083 LiveInterval &L1 = LIS->getInterval(R1.Reg);
1084 LiveInterval &L2 = LIS->getInterval(R2.Reg);
Krzysztof Parzyszek66dd6792016-08-19 14:29:43 +00001085 if (L2.empty())
1086 return false;
Krzysztof Parzyszekead77012016-11-02 17:59:54 +00001087 if (L1.hasSubRanges() || L2.hasSubRanges())
1088 return false;
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001089 bool Overlap = L1.overlaps(L2);
1090
1091 DEBUG(dbgs() << "compatible registers: ("
1092 << (Overlap ? "overlap" : "disjoint") << ")\n "
1093 << PrintReg(R1.Reg, TRI, R1.Sub) << " " << L1 << "\n "
1094 << PrintReg(R2.Reg, TRI, R2.Sub) << " " << L2 << "\n");
1095 if (R1.Sub || R2.Sub)
1096 return false;
1097 if (Overlap)
1098 return false;
1099
1100 // Coalescing could have a negative impact on scheduling, so try to limit
1101 // to some reasonable extent. Only consider coalescing segments, when one
1102 // of them does not cross basic block boundaries.
1103 if (!isIntraBlocks(L1) && !isIntraBlocks(L2))
1104 return false;
1105
1106 MRI->replaceRegWith(R2.Reg, R1.Reg);
1107
1108 // Move all live segments from L2 to L1.
1109 typedef DenseMap<VNInfo*,VNInfo*> ValueInfoMap;
1110 ValueInfoMap VM;
1111 for (LiveInterval::iterator I = L2.begin(), E = L2.end(); I != E; ++I) {
1112 VNInfo *NewVN, *OldVN = I->valno;
1113 ValueInfoMap::iterator F = VM.find(OldVN);
1114 if (F == VM.end()) {
1115 NewVN = L1.getNextValue(I->valno->def, LIS->getVNInfoAllocator());
1116 VM.insert(std::make_pair(OldVN, NewVN));
1117 } else {
1118 NewVN = F->second;
1119 }
1120 L1.addSegment(LiveRange::Segment(I->start, I->end, NewVN));
1121 }
1122 while (L2.begin() != L2.end())
1123 L2.removeSegment(*L2.begin());
Krzysztof Parzyszekead77012016-11-02 17:59:54 +00001124 LIS->removeInterval(R2.Reg);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001125
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001126 updateKillFlags(R1.Reg);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001127 DEBUG(dbgs() << "coalesced: " << L1 << "\n");
1128 L1.verify();
1129
1130 return true;
1131}
1132
Simon Pilgrim6ba672e2016-11-17 19:21:20 +00001133/// Attempt to coalesce one of the source registers to a MUX instruction with
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001134/// the destination register. This could lead to having only one predicated
1135/// instruction in the end instead of two.
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001136bool HexagonExpandCondsets::coalesceSegments(
1137 const SmallVectorImpl<MachineInstr*> &Condsets,
1138 std::set<unsigned> &UpdRegs) {
1139 SmallVector<MachineInstr*,16> TwoRegs;
1140 for (MachineInstr *MI : Condsets) {
1141 MachineOperand &S1 = MI->getOperand(2), &S2 = MI->getOperand(3);
1142 if (!S1.isReg() && !S2.isReg())
1143 continue;
1144 TwoRegs.push_back(MI);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001145 }
1146
1147 bool Changed = false;
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001148 for (MachineInstr *CI : TwoRegs) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001149 RegisterRef RD = CI->getOperand(0);
1150 RegisterRef RP = CI->getOperand(1);
1151 MachineOperand &S1 = CI->getOperand(2), &S2 = CI->getOperand(3);
1152 bool Done = false;
1153 // Consider this case:
1154 // vreg1 = instr1 ...
1155 // vreg2 = instr2 ...
1156 // vreg0 = C2_mux ..., vreg1, vreg2
1157 // If vreg0 was coalesced with vreg1, we could end up with the following
1158 // code:
1159 // vreg0 = instr1 ...
1160 // vreg2 = instr2 ...
1161 // vreg0 = A2_tfrf ..., vreg2
1162 // which will later become:
1163 // vreg0 = instr1 ...
1164 // vreg0 = instr2_cNotPt ...
1165 // i.e. there will be an unconditional definition (instr1) of vreg0
1166 // followed by a conditional one. The output dependency was there before
1167 // and it unavoidable, but if instr1 is predicable, we will no longer be
1168 // able to predicate it here.
1169 // To avoid this scenario, don't coalesce the destination register with
1170 // a source register that is defined by a predicable instruction.
1171 if (S1.isReg()) {
1172 RegisterRef RS = S1;
1173 MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, true);
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001174 if (!RDef || !HII->isPredicable(*RDef)) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001175 Done = coalesceRegisters(RD, RegisterRef(S1));
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001176 if (Done) {
1177 UpdRegs.insert(RD.Reg);
1178 UpdRegs.insert(S1.getReg());
1179 }
1180 }
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001181 }
1182 if (!Done && S2.isReg()) {
1183 RegisterRef RS = S2;
1184 MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, false);
Kirill Bobyrev1f175112016-11-02 10:00:40 +00001185 if (!RDef || !HII->isPredicable(*RDef)) {
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001186 Done = coalesceRegisters(RD, RegisterRef(S2));
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001187 if (Done) {
1188 UpdRegs.insert(RD.Reg);
1189 UpdRegs.insert(S2.getReg());
1190 }
Kirill Bobyrev1f175112016-11-02 10:00:40 +00001191 }
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001192 }
1193 Changed |= Done;
1194 }
1195 return Changed;
1196}
1197
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001198bool HexagonExpandCondsets::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor5b444a22016-04-26 19:46:28 +00001199 if (skipFunction(*MF.getFunction()))
1200 return false;
1201
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001202 HII = static_cast<const HexagonInstrInfo*>(MF.getSubtarget().getInstrInfo());
1203 TRI = MF.getSubtarget().getRegisterInfo();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001204 MDT = &getAnalysis<MachineDominatorTree>();
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001205 LIS = &getAnalysis<LiveIntervals>();
1206 MRI = &MF.getRegInfo();
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001207
1208 DEBUG(LIS->print(dbgs() << "Before expand-condsets\n",
1209 MF.getFunction()->getParent()));
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001210
1211 bool Changed = false;
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001212 std::set<unsigned> CoalUpd, PredUpd;
1213
1214 SmallVector<MachineInstr*,16> Condsets;
1215 for (auto &B : MF)
1216 for (auto &I : B)
1217 if (isCondset(I))
1218 Condsets.push_back(&I);
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001219
1220 // Try to coalesce the target of a mux with one of its sources.
1221 // This could eliminate a register copy in some circumstances.
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001222 Changed |= coalesceSegments(Condsets, CoalUpd);
1223
1224 // Update kill flags on all source operands. This is done here because
1225 // at this moment (when expand-condsets runs), there are no kill flags
1226 // in the IR (they have been removed by live range analysis).
1227 // Updating them right before we split is the easiest, because splitting
1228 // adds definitions which would interfere with updating kills afterwards.
1229 std::set<unsigned> KillUpd;
1230 for (MachineInstr *MI : Condsets)
1231 for (MachineOperand &Op : MI->operands())
1232 if (Op.isReg() && Op.isUse())
1233 if (!CoalUpd.count(Op.getReg()))
1234 KillUpd.insert(Op.getReg());
1235 updateLiveness(KillUpd, false, true, false);
1236 DEBUG(LIS->print(dbgs() << "After coalescing\n",
1237 MF.getFunction()->getParent()));
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001238
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001239 // First, simply split all muxes into a pair of conditional transfers
1240 // and update the live intervals to reflect the new arrangement. The
1241 // goal is to update the kill flags, since predication will rely on
1242 // them.
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001243 for (MachineInstr *MI : Condsets)
1244 Changed |= split(*MI, PredUpd);
1245 Condsets.clear(); // The contents of Condsets are invalid here anyway.
1246
1247 // Do not update live ranges after splitting. Recalculation of live
1248 // intervals removes kill flags, which were preserved by splitting on
1249 // the source operands of condsets. These kill flags are needed by
1250 // predication, and after splitting they are difficult to recalculate
1251 // (because of predicated defs), so make sure they are left untouched.
1252 // Predication does not use live intervals.
1253 DEBUG(LIS->print(dbgs() << "After splitting\n",
1254 MF.getFunction()->getParent()));
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001255
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001256 // Traverse all blocks and collapse predicable instructions feeding
1257 // conditional transfers into predicated instructions.
1258 // Walk over all the instructions again, so we may catch pre-existing
1259 // cases that were not created in the previous step.
1260 for (auto &B : MF)
1261 Changed |= predicateInBlock(B, PredUpd);
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001262 DEBUG(LIS->print(dbgs() << "After predicating\n",
1263 MF.getFunction()->getParent()));
Krzysztof Parzyszek9062b752016-04-22 16:47:01 +00001264
Krzysztof Parzyszek87a47be2016-10-28 15:50:22 +00001265 PredUpd.insert(CoalUpd.begin(), CoalUpd.end());
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001266 updateLiveness(PredUpd, true, true, true);
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001267
Krzysztof Parzyszekb16882d2016-06-08 12:31:16 +00001268 DEBUG({
1269 if (Changed)
1270 LIS->print(dbgs() << "After expand-condsets\n",
1271 MF.getFunction()->getParent());
1272 });
Krzysztof Parzyszek9062b752016-04-22 16:47:01 +00001273
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001274 return Changed;
1275}
1276
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001277//===----------------------------------------------------------------------===//
1278// Public Constructor Functions
1279//===----------------------------------------------------------------------===//
1280
Krzysztof Parzyszekc05dff12015-03-31 13:35:12 +00001281FunctionPass *llvm::createHexagonExpandCondsets() {
1282 return new HexagonExpandCondsets();
1283}