Bug Summary

File:llvm/lib/CodeGen/RegisterCoalescer.cpp
Warning:line 2570, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name RegisterCoalescer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/build-llvm/lib/CodeGen -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-07-11-231758-18690-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp

/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp

1//===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===//
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// This file implements the generic RegisterCoalescer interface which
10// is used as the common interface used by all clients and
11// implementations of register coalescing.
12//
13//===----------------------------------------------------------------------===//
14
15#include "RegisterCoalescer.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/LiveInterval.h"
25#include "llvm/CodeGen/LiveIntervals.h"
26#include "llvm/CodeGen/LiveRangeEdit.h"
27#include "llvm/CodeGen/MachineBasicBlock.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/MachineLoopInfo.h"
33#include "llvm/CodeGen/MachineOperand.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/Passes.h"
36#include "llvm/CodeGen/RegisterClassInfo.h"
37#include "llvm/CodeGen/SlotIndexes.h"
38#include "llvm/CodeGen/TargetInstrInfo.h"
39#include "llvm/CodeGen/TargetOpcodes.h"
40#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/TargetSubtargetInfo.h"
42#include "llvm/IR/DebugLoc.h"
43#include "llvm/InitializePasses.h"
44#include "llvm/MC/LaneBitmask.h"
45#include "llvm/MC/MCInstrDesc.h"
46#include "llvm/MC/MCRegisterInfo.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/raw_ostream.h"
53#include <algorithm>
54#include <cassert>
55#include <iterator>
56#include <limits>
57#include <tuple>
58#include <utility>
59#include <vector>
60
61using namespace llvm;
62
63#define DEBUG_TYPE"regalloc" "regalloc"
64
65STATISTIC(numJoins , "Number of interval joins performed")static llvm::Statistic numJoins = {"regalloc", "numJoins", "Number of interval joins performed"
}
;
66STATISTIC(numCrossRCs , "Number of cross class joins performed")static llvm::Statistic numCrossRCs = {"regalloc", "numCrossRCs"
, "Number of cross class joins performed"}
;
67STATISTIC(numCommutes , "Number of instruction commuting performed")static llvm::Statistic numCommutes = {"regalloc", "numCommutes"
, "Number of instruction commuting performed"}
;
68STATISTIC(numExtends , "Number of copies extended")static llvm::Statistic numExtends = {"regalloc", "numExtends"
, "Number of copies extended"}
;
69STATISTIC(NumReMats , "Number of instructions re-materialized")static llvm::Statistic NumReMats = {"regalloc", "NumReMats", "Number of instructions re-materialized"
}
;
70STATISTIC(NumInflated , "Number of register classes inflated")static llvm::Statistic NumInflated = {"regalloc", "NumInflated"
, "Number of register classes inflated"}
;
71STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested")static llvm::Statistic NumLaneConflicts = {"regalloc", "NumLaneConflicts"
, "Number of dead lane conflicts tested"}
;
72STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved")static llvm::Statistic NumLaneResolves = {"regalloc", "NumLaneResolves"
, "Number of dead lane conflicts resolved"}
;
73STATISTIC(NumShrinkToUses, "Number of shrinkToUses called")static llvm::Statistic NumShrinkToUses = {"regalloc", "NumShrinkToUses"
, "Number of shrinkToUses called"}
;
74
75static cl::opt<bool> EnableJoining("join-liveintervals",
76 cl::desc("Coalesce copies (default=true)"),
77 cl::init(true), cl::Hidden);
78
79static cl::opt<bool> UseTerminalRule("terminal-rule",
80 cl::desc("Apply the terminal rule"),
81 cl::init(false), cl::Hidden);
82
83/// Temporary flag to test critical edge unsplitting.
84static cl::opt<bool>
85EnableJoinSplits("join-splitedges",
86 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
87
88/// Temporary flag to test global copy optimization.
89static cl::opt<cl::boolOrDefault>
90EnableGlobalCopies("join-globalcopies",
91 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
92 cl::init(cl::BOU_UNSET), cl::Hidden);
93
94static cl::opt<bool>
95VerifyCoalescing("verify-coalescing",
96 cl::desc("Verify machine instrs before and after register coalescing"),
97 cl::Hidden);
98
99static cl::opt<unsigned> LateRematUpdateThreshold(
100 "late-remat-update-threshold", cl::Hidden,
101 cl::desc("During rematerialization for a copy, if the def instruction has "
102 "many other copy uses to be rematerialized, delay the multiple "
103 "separate live interval update work and do them all at once after "
104 "all those rematerialization are done. It will save a lot of "
105 "repeated work. "),
106 cl::init(100));
107
108static cl::opt<unsigned> LargeIntervalSizeThreshold(
109 "large-interval-size-threshold", cl::Hidden,
110 cl::desc("If the valnos size of an interval is larger than the threshold, "
111 "it is regarded as a large interval. "),
112 cl::init(100));
113
114static cl::opt<unsigned> LargeIntervalFreqThreshold(
115 "large-interval-freq-threshold", cl::Hidden,
116 cl::desc("For a large interval, if it is coalesed with other live "
117 "intervals many times more than the threshold, stop its "
118 "coalescing to control the compile time. "),
119 cl::init(100));
120
121namespace {
122
123 class JoinVals;
124
125 class RegisterCoalescer : public MachineFunctionPass,
126 private LiveRangeEdit::Delegate {
127 MachineFunction* MF = nullptr;
128 MachineRegisterInfo* MRI = nullptr;
129 const TargetRegisterInfo* TRI = nullptr;
130 const TargetInstrInfo* TII = nullptr;
131 LiveIntervals *LIS = nullptr;
132 const MachineLoopInfo* Loops = nullptr;
133 AliasAnalysis *AA = nullptr;
134 RegisterClassInfo RegClassInfo;
135
136 /// Position and VReg of a PHI instruction during coalescing.
137 struct PHIValPos {
138 SlotIndex SI; ///< Slot where this PHI occurs.
139 Register Reg; ///< VReg the PHI occurs in.
140 unsigned SubReg; ///< Qualifying subregister for Reg.
141 };
142
143 /// Map from debug instruction number to PHI position during coalescing.
144 DenseMap<unsigned, PHIValPos> PHIValToPos;
145 /// Index of, for each VReg, which debug instruction numbers and
146 /// corresponding PHIs are sensitive to coalescing. Each VReg may have
147 /// multiple PHI defs, at different positions.
148 DenseMap<Register, SmallVector<unsigned, 2>> RegToPHIIdx;
149
150 /// Debug variable location tracking -- for each VReg, maintain an
151 /// ordered-by-slot-index set of DBG_VALUEs, to help quick
152 /// identification of whether coalescing may change location validity.
153 using DbgValueLoc = std::pair<SlotIndex, MachineInstr*>;
154 DenseMap<Register, std::vector<DbgValueLoc>> DbgVRegToValues;
155
156 /// VRegs may be repeatedly coalesced, and have many DBG_VALUEs attached.
157 /// To avoid repeatedly merging sets of DbgValueLocs, instead record
158 /// which vregs have been coalesced, and where to. This map is from
159 /// vreg => {set of vregs merged in}.
160 DenseMap<Register, SmallVector<Register, 4>> DbgMergedVRegNums;
161
162 /// A LaneMask to remember on which subregister live ranges we need to call
163 /// shrinkToUses() later.
164 LaneBitmask ShrinkMask;
165
166 /// True if the main range of the currently coalesced intervals should be
167 /// checked for smaller live intervals.
168 bool ShrinkMainRange = false;
169
170 /// True if the coalescer should aggressively coalesce global copies
171 /// in favor of keeping local copies.
172 bool JoinGlobalCopies = false;
173
174 /// True if the coalescer should aggressively coalesce fall-thru
175 /// blocks exclusively containing copies.
176 bool JoinSplitEdges = false;
177
178 /// Copy instructions yet to be coalesced.
179 SmallVector<MachineInstr*, 8> WorkList;
180 SmallVector<MachineInstr*, 8> LocalWorkList;
181
182 /// Set of instruction pointers that have been erased, and
183 /// that may be present in WorkList.
184 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
185
186 /// Dead instructions that are about to be deleted.
187 SmallVector<MachineInstr*, 8> DeadDefs;
188
189 /// Virtual registers to be considered for register class inflation.
190 SmallVector<Register, 8> InflateRegs;
191
192 /// The collection of live intervals which should have been updated
193 /// immediately after rematerialiation but delayed until
194 /// lateLiveIntervalUpdate is called.
195 DenseSet<Register> ToBeUpdated;
196
197 /// Record how many times the large live interval with many valnos
198 /// has been tried to join with other live interval.
199 DenseMap<Register, unsigned long> LargeLIVisitCounter;
200
201 /// Recursively eliminate dead defs in DeadDefs.
202 void eliminateDeadDefs();
203
204 /// LiveRangeEdit callback for eliminateDeadDefs().
205 void LRE_WillEraseInstruction(MachineInstr *MI) override;
206
207 /// Coalesce the LocalWorkList.
208 void coalesceLocals();
209
210 /// Join compatible live intervals
211 void joinAllIntervals();
212
213 /// Coalesce copies in the specified MBB, putting
214 /// copies that cannot yet be coalesced into WorkList.
215 void copyCoalesceInMBB(MachineBasicBlock *MBB);
216
217 /// Tries to coalesce all copies in CurrList. Returns true if any progress
218 /// was made.
219 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
220
221 /// If one def has many copy like uses, and those copy uses are all
222 /// rematerialized, the live interval update needed for those
223 /// rematerializations will be delayed and done all at once instead
224 /// of being done multiple times. This is to save compile cost because
225 /// live interval update is costly.
226 void lateLiveIntervalUpdate();
227
228 /// Check if the incoming value defined by a COPY at \p SLRQ in the subrange
229 /// has no value defined in the predecessors. If the incoming value is the
230 /// same as defined by the copy itself, the value is considered undefined.
231 bool copyValueUndefInPredecessors(LiveRange &S,
232 const MachineBasicBlock *MBB,
233 LiveQueryResult SLRQ);
234
235 /// Set necessary undef flags on subregister uses after pruning out undef
236 /// lane segments from the subrange.
237 void setUndefOnPrunedSubRegUses(LiveInterval &LI, Register Reg,
238 LaneBitmask PrunedLanes);
239
240 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
241 /// src/dst of the copy instruction CopyMI. This returns true if the copy
242 /// was successfully coalesced away. If it is not currently possible to
243 /// coalesce this interval, but it may be possible if other things get
244 /// coalesced, then it returns true by reference in 'Again'.
245 bool joinCopy(MachineInstr *CopyMI, bool &Again);
246
247 /// Attempt to join these two intervals. On failure, this
248 /// returns false. The output "SrcInt" will not have been modified, so we
249 /// can use this information below to update aliases.
250 bool joinIntervals(CoalescerPair &CP);
251
252 /// Attempt joining two virtual registers. Return true on success.
253 bool joinVirtRegs(CoalescerPair &CP);
254
255 /// If a live interval has many valnos and is coalesced with other
256 /// live intervals many times, we regard such live interval as having
257 /// high compile time cost.
258 bool isHighCostLiveInterval(LiveInterval &LI);
259
260 /// Attempt joining with a reserved physreg.
261 bool joinReservedPhysReg(CoalescerPair &CP);
262
263 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
264 /// Subranges in @p LI which only partially interfere with the desired
265 /// LaneMask are split as necessary. @p LaneMask are the lanes that
266 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
267 /// lanemasks already adjusted to the coalesced register.
268 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
269 LaneBitmask LaneMask, CoalescerPair &CP,
270 unsigned DstIdx);
271
272 /// Join the liveranges of two subregisters. Joins @p RRange into
273 /// @p LRange, @p RRange may be invalid afterwards.
274 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
275 LaneBitmask LaneMask, const CoalescerPair &CP);
276
277 /// We found a non-trivially-coalescable copy. If the source value number is
278 /// defined by a copy from the destination reg see if we can merge these two
279 /// destination reg valno# into a single value number, eliminating a copy.
280 /// This returns true if an interval was modified.
281 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
282
283 /// Return true if there are definitions of IntB
284 /// other than BValNo val# that can reach uses of AValno val# of IntA.
285 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
286 VNInfo *AValNo, VNInfo *BValNo);
287
288 /// We found a non-trivially-coalescable copy.
289 /// If the source value number is defined by a commutable instruction and
290 /// its other operand is coalesced to the copy dest register, see if we
291 /// can transform the copy into a noop by commuting the definition.
292 /// This returns a pair of two flags:
293 /// - the first element is true if an interval was modified,
294 /// - the second element is true if the destination interval needs
295 /// to be shrunk after deleting the copy.
296 std::pair<bool,bool> removeCopyByCommutingDef(const CoalescerPair &CP,
297 MachineInstr *CopyMI);
298
299 /// We found a copy which can be moved to its less frequent predecessor.
300 bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
301
302 /// If the source of a copy is defined by a
303 /// trivial computation, replace the copy by rematerialize the definition.
304 bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
305 bool &IsDefCopy);
306
307 /// Return true if a copy involving a physreg should be joined.
308 bool canJoinPhys(const CoalescerPair &CP);
309
310 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
311 /// number if it is not zero. If DstReg is a physical register and the
312 /// existing subregister number of the def / use being updated is not zero,
313 /// make sure to set it to the correct physical subregister.
314 void updateRegDefsUses(Register SrcReg, Register DstReg, unsigned SubIdx);
315
316 /// If the given machine operand reads only undefined lanes add an undef
317 /// flag.
318 /// This can happen when undef uses were previously concealed by a copy
319 /// which we coalesced. Example:
320 /// %0:sub0<def,read-undef> = ...
321 /// %1 = COPY %0 <-- Coalescing COPY reveals undef
322 /// = use %1:sub1 <-- hidden undef use
323 void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
324 MachineOperand &MO, unsigned SubRegIdx);
325
326 /// Handle copies of undef values. If the undef value is an incoming
327 /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
328 /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
329 /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
330 MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
331
332 /// Check whether or not we should apply the terminal rule on the
333 /// destination (Dst) of \p Copy.
334 /// When the terminal rule applies, Copy is not profitable to
335 /// coalesce.
336 /// Dst is terminal if it has exactly one affinity (Dst, Src) and
337 /// at least one interference (Dst, Dst2). If Dst is terminal, the
338 /// terminal rule consists in checking that at least one of
339 /// interfering node, say Dst2, has an affinity of equal or greater
340 /// weight with Src.
341 /// In that case, Dst2 and Dst will not be able to be both coalesced
342 /// with Src. Since Dst2 exposes more coalescing opportunities than
343 /// Dst, we can drop \p Copy.
344 bool applyTerminalRule(const MachineInstr &Copy) const;
345
346 /// Wrapper method for \see LiveIntervals::shrinkToUses.
347 /// This method does the proper fixing of the live-ranges when the afore
348 /// mentioned method returns true.
349 void shrinkToUses(LiveInterval *LI,
350 SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
351 NumShrinkToUses++;
352 if (LIS->shrinkToUses(LI, Dead)) {
353 /// Check whether or not \p LI is composed by multiple connected
354 /// components and if that is the case, fix that.
355 SmallVector<LiveInterval*, 8> SplitLIs;
356 LIS->splitSeparateComponents(*LI, SplitLIs);
357 }
358 }
359
360 /// Wrapper Method to do all the necessary work when an Instruction is
361 /// deleted.
362 /// Optimizations should use this to make sure that deleted instructions
363 /// are always accounted for.
364 void deleteInstr(MachineInstr* MI) {
365 ErasedInstrs.insert(MI);
366 LIS->RemoveMachineInstrFromMaps(*MI);
367 MI->eraseFromParent();
368 }
369
370 /// Walk over function and initialize the DbgVRegToValues map.
371 void buildVRegToDbgValueMap(MachineFunction &MF);
372
373 /// Test whether, after merging, any DBG_VALUEs would refer to a
374 /// different value number than before merging, and whether this can
375 /// be resolved. If not, mark the DBG_VALUE as being undef.
376 void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS,
377 JoinVals &LHSVals, LiveRange &RHS,
378 JoinVals &RHSVals);
379
380 void checkMergingChangesDbgValuesImpl(Register Reg, LiveRange &OtherRange,
381 LiveRange &RegRange, JoinVals &Vals2);
382
383 public:
384 static char ID; ///< Class identification, replacement for typeinfo
385
386 RegisterCoalescer() : MachineFunctionPass(ID) {
387 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
388 }
389
390 void getAnalysisUsage(AnalysisUsage &AU) const override;
391
392 void releaseMemory() override;
393
394 /// This is the pass entry point.
395 bool runOnMachineFunction(MachineFunction&) override;
396
397 /// Implement the dump method.
398 void print(raw_ostream &O, const Module* = nullptr) const override;
399 };
400
401} // end anonymous namespace
402
403char RegisterCoalescer::ID = 0;
404
405char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
406
407INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",static void *initializeRegisterCoalescerPassOnce(PassRegistry
&Registry) {
408 "Simple Register Coalescing", false, false)static void *initializeRegisterCoalescerPassOnce(PassRegistry
&Registry) {
409INITIALIZE_PASS_DEPENDENCY(LiveIntervals)initializeLiveIntervalsPass(Registry);
410INITIALIZE_PASS_DEPENDENCY(SlotIndexes)initializeSlotIndexesPass(Registry);
411INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)initializeMachineLoopInfoPass(Registry);
412INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
413INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",PassInfo *PI = new PassInfo( "Simple Register Coalescing", "simple-register-coalescing"
, &RegisterCoalescer::ID, PassInfo::NormalCtor_t(callDefaultCtor
<RegisterCoalescer>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeRegisterCoalescerPassFlag
; void llvm::initializeRegisterCoalescerPass(PassRegistry &
Registry) { llvm::call_once(InitializeRegisterCoalescerPassFlag
, initializeRegisterCoalescerPassOnce, std::ref(Registry)); }
414 "Simple Register Coalescing", false, false)PassInfo *PI = new PassInfo( "Simple Register Coalescing", "simple-register-coalescing"
, &RegisterCoalescer::ID, PassInfo::NormalCtor_t(callDefaultCtor
<RegisterCoalescer>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeRegisterCoalescerPassFlag
; void llvm::initializeRegisterCoalescerPass(PassRegistry &
Registry) { llvm::call_once(InitializeRegisterCoalescerPassFlag
, initializeRegisterCoalescerPassOnce, std::ref(Registry)); }
415
416LLVM_NODISCARD[[clang::warn_unused_result]] static bool isMoveInstr(const TargetRegisterInfo &tri,
417 const MachineInstr *MI, Register &Src,
418 Register &Dst, unsigned &SrcSub,
419 unsigned &DstSub) {
420 if (MI->isCopy()) {
421 Dst = MI->getOperand(0).getReg();
422 DstSub = MI->getOperand(0).getSubReg();
423 Src = MI->getOperand(1).getReg();
424 SrcSub = MI->getOperand(1).getSubReg();
425 } else if (MI->isSubregToReg()) {
426 Dst = MI->getOperand(0).getReg();
427 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
428 MI->getOperand(3).getImm());
429 Src = MI->getOperand(2).getReg();
430 SrcSub = MI->getOperand(2).getSubReg();
431 } else
432 return false;
433 return true;
434}
435
436/// Return true if this block should be vacated by the coalescer to eliminate
437/// branches. The important cases to handle in the coalescer are critical edges
438/// split during phi elimination which contain only copies. Simple blocks that
439/// contain non-branches should also be vacated, but this can be handled by an
440/// earlier pass similar to early if-conversion.
441static bool isSplitEdge(const MachineBasicBlock *MBB) {
442 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
443 return false;
444
445 for (const auto &MI : *MBB) {
446 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
447 return false;
448 }
449 return true;
450}
451
452bool CoalescerPair::setRegisters(const MachineInstr *MI) {
453 SrcReg = DstReg = Register();
454 SrcIdx = DstIdx = 0;
455 NewRC = nullptr;
456 Flipped = CrossClass = false;
457
458 Register Src, Dst;
459 unsigned SrcSub = 0, DstSub = 0;
460 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
461 return false;
462 Partial = SrcSub || DstSub;
463
464 // If one register is a physreg, it must be Dst.
465 if (Register::isPhysicalRegister(Src)) {
466 if (Register::isPhysicalRegister(Dst))
467 return false;
468 std::swap(Src, Dst);
469 std::swap(SrcSub, DstSub);
470 Flipped = true;
471 }
472
473 const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
474
475 if (Register::isPhysicalRegister(Dst)) {
476 // Eliminate DstSub on a physreg.
477 if (DstSub) {
478 Dst = TRI.getSubReg(Dst, DstSub);
479 if (!Dst) return false;
480 DstSub = 0;
481 }
482
483 // Eliminate SrcSub by picking a corresponding Dst superregister.
484 if (SrcSub) {
485 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
486 if (!Dst) return false;
487 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
488 return false;
489 }
490 } else {
491 // Both registers are virtual.
492 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
493 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
494
495 // Both registers have subreg indices.
496 if (SrcSub && DstSub) {
497 // Copies between different sub-registers are never coalescable.
498 if (Src == Dst && SrcSub != DstSub)
499 return false;
500
501 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
502 SrcIdx, DstIdx);
503 if (!NewRC)
504 return false;
505 } else if (DstSub) {
506 // SrcReg will be merged with a sub-register of DstReg.
507 SrcIdx = DstSub;
508 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
509 } else if (SrcSub) {
510 // DstReg will be merged with a sub-register of SrcReg.
511 DstIdx = SrcSub;
512 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
513 } else {
514 // This is a straight copy without sub-registers.
515 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
516 }
517
518 // The combined constraint may be impossible to satisfy.
519 if (!NewRC)
520 return false;
521
522 // Prefer SrcReg to be a sub-register of DstReg.
523 // FIXME: Coalescer should support subregs symmetrically.
524 if (DstIdx && !SrcIdx) {
525 std::swap(Src, Dst);
526 std::swap(SrcIdx, DstIdx);
527 Flipped = !Flipped;
528 }
529
530 CrossClass = NewRC != DstRC || NewRC != SrcRC;
531 }
532 // Check our invariants
533 assert(Register::isVirtualRegister(Src) && "Src must be virtual")(static_cast <bool> (Register::isVirtualRegister(Src) &&
"Src must be virtual") ? void (0) : __assert_fail ("Register::isVirtualRegister(Src) && \"Src must be virtual\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 533, __extension__ __PRETTY_FUNCTION__))
;
534 assert(!(Register::isPhysicalRegister(Dst) && DstSub) &&(static_cast <bool> (!(Register::isPhysicalRegister(Dst
) && DstSub) && "Cannot have a physical SubIdx"
) ? void (0) : __assert_fail ("!(Register::isPhysicalRegister(Dst) && DstSub) && \"Cannot have a physical SubIdx\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 535, __extension__ __PRETTY_FUNCTION__))
535 "Cannot have a physical SubIdx")(static_cast <bool> (!(Register::isPhysicalRegister(Dst
) && DstSub) && "Cannot have a physical SubIdx"
) ? void (0) : __assert_fail ("!(Register::isPhysicalRegister(Dst) && DstSub) && \"Cannot have a physical SubIdx\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 535, __extension__ __PRETTY_FUNCTION__))
;
536 SrcReg = Src;
537 DstReg = Dst;
538 return true;
539}
540
541bool CoalescerPair::flip() {
542 if (Register::isPhysicalRegister(DstReg))
543 return false;
544 std::swap(SrcReg, DstReg);
545 std::swap(SrcIdx, DstIdx);
546 Flipped = !Flipped;
547 return true;
548}
549
550bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
551 if (!MI)
552 return false;
553 Register Src, Dst;
554 unsigned SrcSub = 0, DstSub = 0;
555 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
556 return false;
557
558 // Find the virtual register that is SrcReg.
559 if (Dst == SrcReg) {
560 std::swap(Src, Dst);
561 std::swap(SrcSub, DstSub);
562 } else if (Src != SrcReg) {
563 return false;
564 }
565
566 // Now check that Dst matches DstReg.
567 if (DstReg.isPhysical()) {
568 if (!Dst.isPhysical())
569 return false;
570 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.")(static_cast <bool> (!DstIdx && !SrcIdx &&
"Inconsistent CoalescerPair state.") ? void (0) : __assert_fail
("!DstIdx && !SrcIdx && \"Inconsistent CoalescerPair state.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 570, __extension__ __PRETTY_FUNCTION__))
;
571 // DstSub could be set for a physreg from INSERT_SUBREG.
572 if (DstSub)
573 Dst = TRI.getSubReg(Dst, DstSub);
574 // Full copy of Src.
575 if (!SrcSub)
576 return DstReg == Dst;
577 // This is a partial register copy. Check that the parts match.
578 return Register(TRI.getSubReg(DstReg, SrcSub)) == Dst;
579 } else {
580 // DstReg is virtual.
581 if (DstReg != Dst)
582 return false;
583 // Registers match, do the subregisters line up?
584 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
585 TRI.composeSubRegIndices(DstIdx, DstSub);
586 }
587}
588
589void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
590 AU.setPreservesCFG();
591 AU.addRequired<AAResultsWrapperPass>();
592 AU.addRequired<LiveIntervals>();
593 AU.addPreserved<LiveIntervals>();
594 AU.addPreserved<SlotIndexes>();
595 AU.addRequired<MachineLoopInfo>();
596 AU.addPreserved<MachineLoopInfo>();
597 AU.addPreservedID(MachineDominatorsID);
598 MachineFunctionPass::getAnalysisUsage(AU);
599}
600
601void RegisterCoalescer::eliminateDeadDefs() {
602 SmallVector<Register, 8> NewRegs;
603 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
604 nullptr, this).eliminateDeadDefs(DeadDefs);
605}
606
607void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
608 // MI may be in WorkList. Make sure we don't visit it.
609 ErasedInstrs.insert(MI);
610}
611
612bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
613 MachineInstr *CopyMI) {
614 assert(!CP.isPartial() && "This doesn't work for partial copies.")(static_cast <bool> (!CP.isPartial() && "This doesn't work for partial copies."
) ? void (0) : __assert_fail ("!CP.isPartial() && \"This doesn't work for partial copies.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 614, __extension__ __PRETTY_FUNCTION__))
;
615 assert(!CP.isPhys() && "This doesn't work for physreg copies.")(static_cast <bool> (!CP.isPhys() && "This doesn't work for physreg copies."
) ? void (0) : __assert_fail ("!CP.isPhys() && \"This doesn't work for physreg copies.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 615, __extension__ __PRETTY_FUNCTION__))
;
616
617 LiveInterval &IntA =
618 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
619 LiveInterval &IntB =
620 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
621 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
622
623 // We have a non-trivially-coalescable copy with IntA being the source and
624 // IntB being the dest, thus this defines a value number in IntB. If the
625 // source value number (in IntA) is defined by a copy from B, see if we can
626 // merge these two pieces of B into a single value number, eliminating a copy.
627 // For example:
628 //
629 // A3 = B0
630 // ...
631 // B1 = A3 <- this copy
632 //
633 // In this case, B0 can be extended to where the B1 copy lives, allowing the
634 // B1 value number to be replaced with B0 (which simplifies the B
635 // liveinterval).
636
637 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
638 // the example above.
639 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
640 if (BS == IntB.end()) return false;
641 VNInfo *BValNo = BS->valno;
642
643 // Get the location that B is defined at. Two options: either this value has
644 // an unknown definition point or it is defined at CopyIdx. If unknown, we
645 // can't process it.
646 if (BValNo->def != CopyIdx) return false;
647
648 // AValNo is the value number in A that defines the copy, A3 in the example.
649 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
650 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
651 // The live segment might not exist after fun with physreg coalescing.
652 if (AS == IntA.end()) return false;
653 VNInfo *AValNo = AS->valno;
654
655 // If AValNo is defined as a copy from IntB, we can potentially process this.
656 // Get the instruction that defines this value number.
657 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
658 // Don't allow any partial copies, even if isCoalescable() allows them.
659 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
660 return false;
661
662 // Get the Segment in IntB that this value number starts with.
663 LiveInterval::iterator ValS =
664 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
665 if (ValS == IntB.end())
666 return false;
667
668 // Make sure that the end of the live segment is inside the same block as
669 // CopyMI.
670 MachineInstr *ValSEndInst =
671 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
672 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
673 return false;
674
675 // Okay, we now know that ValS ends in the same block that the CopyMI
676 // live-range starts. If there are no intervening live segments between them
677 // in IntB, we can merge them.
678 if (ValS+1 != BS) return false;
679
680 LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg(), TRI))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Extending: " << printReg
(IntB.reg(), TRI); } } while (false)
;
681
682 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
683 // We are about to delete CopyMI, so need to remove it as the 'instruction
684 // that defines this value #'. Update the valnum with the new defining
685 // instruction #.
686 BValNo->def = FillerStart;
687
688 // Okay, we can merge them. We need to insert a new liverange:
689 // [ValS.end, BS.begin) of either value number, then we merge the
690 // two value numbers.
691 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
692
693 // Okay, merge "B1" into the same value number as "B0".
694 if (BValNo != ValS->valno)
695 IntB.MergeValueNumberInto(BValNo, ValS->valno);
696
697 // Do the same for the subregister segments.
698 for (LiveInterval::SubRange &S : IntB.subranges()) {
699 // Check for SubRange Segments of the form [1234r,1234d:0) which can be
700 // removed to prevent creating bogus SubRange Segments.
701 LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
702 if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
703 S.removeSegment(*SS, true);
704 continue;
705 }
706 // The subrange may have ended before FillerStart. If so, extend it.
707 if (!S.getVNInfoAt(FillerStart)) {
708 SlotIndex BBStart =
709 LIS->getMBBStartIdx(LIS->getMBBFromIndex(FillerStart));
710 S.extendInBlock(BBStart, FillerStart);
711 }
712 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
713 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
714 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
715 if (SubBValNo != SubValSNo)
716 S.MergeValueNumberInto(SubBValNo, SubValSNo);
717 }
718
719 LLVM_DEBUG(dbgs() << " result = " << IntB << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << " result = " << IntB <<
'\n'; } } while (false)
;
720
721 // If the source instruction was killing the source register before the
722 // merge, unset the isKill marker given the live range has been extended.
723 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg(), true);
724 if (UIdx != -1) {
725 ValSEndInst->getOperand(UIdx).setIsKill(false);
726 }
727
728 // Rewrite the copy.
729 CopyMI->substituteRegister(IntA.reg(), IntB.reg(), 0, *TRI);
730 // If the copy instruction was killing the destination register or any
731 // subrange before the merge trim the live range.
732 bool RecomputeLiveRange = AS->end == CopyIdx;
733 if (!RecomputeLiveRange) {
734 for (LiveInterval::SubRange &S : IntA.subranges()) {
735 LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
736 if (SS != S.end() && SS->end == CopyIdx) {
737 RecomputeLiveRange = true;
738 break;
739 }
740 }
741 }
742 if (RecomputeLiveRange)
743 shrinkToUses(&IntA);
744
745 ++numExtends;
746 return true;
747}
748
749bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
750 LiveInterval &IntB,
751 VNInfo *AValNo,
752 VNInfo *BValNo) {
753 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
754 // the PHI values.
755 if (LIS->hasPHIKill(IntA, AValNo))
756 return true;
757
758 for (LiveRange::Segment &ASeg : IntA.segments) {
759 if (ASeg.valno != AValNo) continue;
760 LiveInterval::iterator BI = llvm::upper_bound(IntB, ASeg.start);
761 if (BI != IntB.begin())
762 --BI;
763 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
764 if (BI->valno == BValNo)
765 continue;
766 if (BI->start <= ASeg.start && BI->end > ASeg.start)
767 return true;
768 if (BI->start > ASeg.start && BI->start < ASeg.end)
769 return true;
770 }
771 }
772 return false;
773}
774
775/// Copy segments with value number @p SrcValNo from liverange @p Src to live
776/// range @Dst and use value number @p DstValNo there.
777static std::pair<bool,bool>
778addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src,
779 const VNInfo *SrcValNo) {
780 bool Changed = false;
781 bool MergedWithDead = false;
782 for (const LiveRange::Segment &S : Src.segments) {
783 if (S.valno != SrcValNo)
784 continue;
785 // This is adding a segment from Src that ends in a copy that is about
786 // to be removed. This segment is going to be merged with a pre-existing
787 // segment in Dst. This works, except in cases when the corresponding
788 // segment in Dst is dead. For example: adding [192r,208r:1) from Src
789 // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst.
790 // Recognized such cases, so that the segments can be shrunk.
791 LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo);
792 LiveRange::Segment &Merged = *Dst.addSegment(Added);
793 if (Merged.end.isDead())
794 MergedWithDead = true;
795 Changed = true;
796 }
797 return std::make_pair(Changed, MergedWithDead);
798}
799
800std::pair<bool,bool>
801RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
802 MachineInstr *CopyMI) {
803 assert(!CP.isPhys())(static_cast <bool> (!CP.isPhys()) ? void (0) : __assert_fail
("!CP.isPhys()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 803, __extension__ __PRETTY_FUNCTION__))
;
804
805 LiveInterval &IntA =
806 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
807 LiveInterval &IntB =
808 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
809
810 // We found a non-trivially-coalescable copy with IntA being the source and
811 // IntB being the dest, thus this defines a value number in IntB. If the
812 // source value number (in IntA) is defined by a commutable instruction and
813 // its other operand is coalesced to the copy dest register, see if we can
814 // transform the copy into a noop by commuting the definition. For example,
815 //
816 // A3 = op A2 killed B0
817 // ...
818 // B1 = A3 <- this copy
819 // ...
820 // = op A3 <- more uses
821 //
822 // ==>
823 //
824 // B2 = op B0 killed A2
825 // ...
826 // B1 = B2 <- now an identity copy
827 // ...
828 // = op B2 <- more uses
829
830 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
831 // the example above.
832 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
833 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
834 assert(BValNo != nullptr && BValNo->def == CopyIdx)(static_cast <bool> (BValNo != nullptr && BValNo
->def == CopyIdx) ? void (0) : __assert_fail ("BValNo != nullptr && BValNo->def == CopyIdx"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 834, __extension__ __PRETTY_FUNCTION__))
;
835
836 // AValNo is the value number in A that defines the copy, A3 in the example.
837 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
838 assert(AValNo && !AValNo->isUnused() && "COPY source not live")(static_cast <bool> (AValNo && !AValNo->isUnused
() && "COPY source not live") ? void (0) : __assert_fail
("AValNo && !AValNo->isUnused() && \"COPY source not live\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 838, __extension__ __PRETTY_FUNCTION__))
;
839 if (AValNo->isPHIDef())
840 return { false, false };
841 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
842 if (!DefMI)
843 return { false, false };
844 if (!DefMI->isCommutable())
845 return { false, false };
846 // If DefMI is a two-address instruction then commuting it will change the
847 // destination register.
848 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg());
849 assert(DefIdx != -1)(static_cast <bool> (DefIdx != -1) ? void (0) : __assert_fail
("DefIdx != -1", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 849, __extension__ __PRETTY_FUNCTION__))
;
850 unsigned UseOpIdx;
851 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
852 return { false, false };
853
854 // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
855 // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
856 // passed to the method. That _other_ operand is chosen by
857 // the findCommutedOpIndices() method.
858 //
859 // That is obviously an area for improvement in case of instructions having
860 // more than 2 operands. For example, if some instruction has 3 commutable
861 // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
862 // op#2<->op#3) of commute transformation should be considered/tried here.
863 unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
864 if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
865 return { false, false };
866
867 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
868 Register NewReg = NewDstMO.getReg();
869 if (NewReg != IntB.reg() || !IntB.Query(AValNo->def).isKill())
870 return { false, false };
871
872 // Make sure there are no other definitions of IntB that would reach the
873 // uses which the new definition can reach.
874 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
875 return { false, false };
876
877 // If some of the uses of IntA.reg is already coalesced away, return false.
878 // It's not possible to determine whether it's safe to perform the coalescing.
879 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg())) {
880 MachineInstr *UseMI = MO.getParent();
881 unsigned OpNo = &MO - &UseMI->getOperand(0);
882 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
883 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
884 if (US == IntA.end() || US->valno != AValNo)
885 continue;
886 // If this use is tied to a def, we can't rewrite the register.
887 if (UseMI->isRegTiedToDefOperand(OpNo))
888 return { false, false };
889 }
890
891 LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremoveCopyByCommutingDef: "
<< AValNo->def << '\t' << *DefMI; } } while
(false)
892 << *DefMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremoveCopyByCommutingDef: "
<< AValNo->def << '\t' << *DefMI; } } while
(false)
;
893
894 // At this point we have decided that it is legal to do this
895 // transformation. Start by commuting the instruction.
896 MachineBasicBlock *MBB = DefMI->getParent();
897 MachineInstr *NewMI =
898 TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
899 if (!NewMI)
900 return { false, false };
901 if (Register::isVirtualRegister(IntA.reg()) &&
902 Register::isVirtualRegister(IntB.reg()) &&
903 !MRI->constrainRegClass(IntB.reg(), MRI->getRegClass(IntA.reg())))
904 return { false, false };
905 if (NewMI != DefMI) {
906 LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
907 MachineBasicBlock::iterator Pos = DefMI;
908 MBB->insert(Pos, NewMI);
909 MBB->erase(DefMI);
910 }
911
912 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
913 // A = or A, B
914 // ...
915 // B = A
916 // ...
917 // C = killed A
918 // ...
919 // = B
920
921 // Update uses of IntA of the specific Val# with IntB.
922 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg()),
923 UE = MRI->use_end();
924 UI != UE;
925 /* ++UI is below because of possible MI removal */) {
926 MachineOperand &UseMO = *UI;
927 ++UI;
928 if (UseMO.isUndef())
929 continue;
930 MachineInstr *UseMI = UseMO.getParent();
931 if (UseMI->isDebugInstr()) {
932 // FIXME These don't have an instruction index. Not clear we have enough
933 // info to decide whether to do this replacement or not. For now do it.
934 UseMO.setReg(NewReg);
935 continue;
936 }
937 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
938 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
939 assert(US != IntA.end() && "Use must be live")(static_cast <bool> (US != IntA.end() && "Use must be live"
) ? void (0) : __assert_fail ("US != IntA.end() && \"Use must be live\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 939, __extension__ __PRETTY_FUNCTION__))
;
940 if (US->valno != AValNo)
941 continue;
942 // Kill flags are no longer accurate. They are recomputed after RA.
943 UseMO.setIsKill(false);
944 if (Register::isPhysicalRegister(NewReg))
945 UseMO.substPhysReg(NewReg, *TRI);
946 else
947 UseMO.setReg(NewReg);
948 if (UseMI == CopyMI)
949 continue;
950 if (!UseMI->isCopy())
951 continue;
952 if (UseMI->getOperand(0).getReg() != IntB.reg() ||
953 UseMI->getOperand(0).getSubReg())
954 continue;
955
956 // This copy will become a noop. If it's defining a new val#, merge it into
957 // BValNo.
958 SlotIndex DefIdx = UseIdx.getRegSlot();
959 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
960 if (!DVNI)
961 continue;
962 LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tnoop: " << DefIdx <<
'\t' << *UseMI; } } while (false)
;
963 assert(DVNI->def == DefIdx)(static_cast <bool> (DVNI->def == DefIdx) ? void (0)
: __assert_fail ("DVNI->def == DefIdx", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
;
964 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
965 for (LiveInterval::SubRange &S : IntB.subranges()) {
966 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
967 if (!SubDVNI)
968 continue;
969 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
970 assert(SubBValNo->def == CopyIdx)(static_cast <bool> (SubBValNo->def == CopyIdx) ? void
(0) : __assert_fail ("SubBValNo->def == CopyIdx", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 970, __extension__ __PRETTY_FUNCTION__))
;
971 S.MergeValueNumberInto(SubDVNI, SubBValNo);
972 }
973
974 deleteInstr(UseMI);
975 }
976
977 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
978 // is updated.
979 bool ShrinkB = false;
980 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
981 if (IntA.hasSubRanges() || IntB.hasSubRanges()) {
982 if (!IntA.hasSubRanges()) {
983 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg());
984 IntA.createSubRangeFrom(Allocator, Mask, IntA);
985 } else if (!IntB.hasSubRanges()) {
986 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntB.reg());
987 IntB.createSubRangeFrom(Allocator, Mask, IntB);
988 }
989 SlotIndex AIdx = CopyIdx.getRegSlot(true);
990 LaneBitmask MaskA;
991 const SlotIndexes &Indexes = *LIS->getSlotIndexes();
992 for (LiveInterval::SubRange &SA : IntA.subranges()) {
993 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
994 // Even if we are dealing with a full copy, some lanes can
995 // still be undefined.
996 // E.g.,
997 // undef A.subLow = ...
998 // B = COPY A <== A.subHigh is undefined here and does
999 // not have a value number.
1000 if (!ASubValNo)
1001 continue;
1002 MaskA |= SA.LaneMask;
1003
1004 IntB.refineSubRanges(
1005 Allocator, SA.LaneMask,
1006 [&Allocator, &SA, CopyIdx, ASubValNo,
1007 &ShrinkB](LiveInterval::SubRange &SR) {
1008 VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator)
1009 : SR.getVNInfoAt(CopyIdx);
1010 assert(BSubValNo != nullptr)(static_cast <bool> (BSubValNo != nullptr) ? void (0) :
__assert_fail ("BSubValNo != nullptr", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1010, __extension__ __PRETTY_FUNCTION__))
;
1011 auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
1012 ShrinkB |= P.second;
1013 if (P.first)
1014 BSubValNo->def = ASubValNo->def;
1015 },
1016 Indexes, *TRI);
1017 }
1018 // Go over all subranges of IntB that have not been covered by IntA,
1019 // and delete the segments starting at CopyIdx. This can happen if
1020 // IntA has undef lanes that are defined in IntB.
1021 for (LiveInterval::SubRange &SB : IntB.subranges()) {
1022 if ((SB.LaneMask & MaskA).any())
1023 continue;
1024 if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx))
1025 if (S->start.getBaseIndex() == CopyIdx.getBaseIndex())
1026 SB.removeSegment(*S, true);
1027 }
1028 }
1029
1030 BValNo->def = AValNo->def;
1031 auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
1032 ShrinkB |= P.second;
1033 LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\textended: " << IntB
<< '\n'; } } while (false)
;
1034
1035 LIS->removeVRegDefAt(IntA, AValNo->def);
1036
1037 LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\ttrimmed: " << IntA
<< '\n'; } } while (false)
;
1038 ++numCommutes;
1039 return { true, ShrinkB };
1040}
1041
1042/// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
1043/// predecessor of BB2, and if B is not redefined on the way from A = B
1044/// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the
1045/// execution goes through the path from BB0 to BB2. We may move B = A
1046/// to the predecessor without such reversed copy.
1047/// So we will transform the program from:
1048/// BB0:
1049/// A = B; BB1:
1050/// ... ...
1051/// / \ /
1052/// BB2:
1053/// ...
1054/// B = A;
1055///
1056/// to:
1057///
1058/// BB0: BB1:
1059/// A = B; ...
1060/// ... B = A;
1061/// / \ /
1062/// BB2:
1063/// ...
1064///
1065/// A special case is when BB0 and BB2 are the same BB which is the only
1066/// BB in a loop:
1067/// BB1:
1068/// ...
1069/// BB0/BB2: ----
1070/// B = A; |
1071/// ... |
1072/// A = B; |
1073/// |-------
1074/// |
1075/// We may hoist B = A from BB0/BB2 to BB1.
1076///
1077/// The major preconditions for correctness to remove such partial
1078/// redundancy include:
1079/// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
1080/// the PHI is defined by the reversed copy A = B in BB0.
1081/// 2. No B is referenced from the start of BB2 to B = A.
1082/// 3. No B is defined from A = B to the end of BB0.
1083/// 4. BB1 has only one successor.
1084///
1085/// 2 and 4 implicitly ensure B is not live at the end of BB1.
1086/// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
1087/// colder place, which not only prevent endless loop, but also make sure
1088/// the movement of copy is beneficial.
1089bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
1090 MachineInstr &CopyMI) {
1091 assert(!CP.isPhys())(static_cast <bool> (!CP.isPhys()) ? void (0) : __assert_fail
("!CP.isPhys()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1091, __extension__ __PRETTY_FUNCTION__))
;
1092 if (!CopyMI.isFullCopy())
1093 return false;
1094
1095 MachineBasicBlock &MBB = *CopyMI.getParent();
1096 // If this block is the target of an invoke/inlineasm_br, moving the copy into
1097 // the predecessor is tricker, and we don't handle it.
1098 if (MBB.isEHPad() || MBB.isInlineAsmBrIndirectTarget())
1099 return false;
1100
1101 if (MBB.pred_size() != 2)
1102 return false;
1103
1104 LiveInterval &IntA =
1105 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
1106 LiveInterval &IntB =
1107 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
1108
1109 // A is defined by PHI at the entry of MBB.
1110 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
1111 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
1112 assert(AValNo && !AValNo->isUnused() && "COPY source not live")(static_cast <bool> (AValNo && !AValNo->isUnused
() && "COPY source not live") ? void (0) : __assert_fail
("AValNo && !AValNo->isUnused() && \"COPY source not live\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1112, __extension__ __PRETTY_FUNCTION__))
;
1113 if (!AValNo->isPHIDef())
1114 return false;
1115
1116 // No B is referenced before CopyMI in MBB.
1117 if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
1118 return false;
1119
1120 // MBB has two predecessors: one contains A = B so no copy will be inserted
1121 // for it. The other one will have a copy moved from MBB.
1122 bool FoundReverseCopy = false;
1123 MachineBasicBlock *CopyLeftBB = nullptr;
1124 for (MachineBasicBlock *Pred : MBB.predecessors()) {
1125 VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
1126 MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def);
1127 if (!DefMI || !DefMI->isFullCopy()) {
1128 CopyLeftBB = Pred;
1129 continue;
1130 }
1131 // Check DefMI is a reverse copy and it is in BB Pred.
1132 if (DefMI->getOperand(0).getReg() != IntA.reg() ||
1133 DefMI->getOperand(1).getReg() != IntB.reg() ||
1134 DefMI->getParent() != Pred) {
1135 CopyLeftBB = Pred;
1136 continue;
1137 }
1138 // If there is any other def of B after DefMI and before the end of Pred,
1139 // we need to keep the copy of B = A at the end of Pred if we remove
1140 // B = A from MBB.
1141 bool ValB_Changed = false;
1142 for (auto VNI : IntB.valnos) {
1143 if (VNI->isUnused())
1144 continue;
1145 if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
1146 ValB_Changed = true;
1147 break;
1148 }
1149 }
1150 if (ValB_Changed) {
1151 CopyLeftBB = Pred;
1152 continue;
1153 }
1154 FoundReverseCopy = true;
1155 }
1156
1157 // If no reverse copy is found in predecessors, nothing to do.
1158 if (!FoundReverseCopy)
1159 return false;
1160
1161 // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
1162 // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
1163 // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
1164 // update IntA/IntB.
1165 //
1166 // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
1167 // MBB is hotter than CopyLeftBB.
1168 if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
1169 return false;
1170
1171 // Now (almost sure it's) ok to move copy.
1172 if (CopyLeftBB) {
1173 // Position in CopyLeftBB where we should insert new copy.
1174 auto InsPos = CopyLeftBB->getFirstTerminator();
1175
1176 // Make sure that B isn't referenced in the terminators (if any) at the end
1177 // of the predecessor since we're about to insert a new definition of B
1178 // before them.
1179 if (InsPos != CopyLeftBB->end()) {
1180 SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
1181 if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
1182 return false;
1183 }
1184
1185 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremovePartialRedundancy: Move the copy to "
<< printMBBReference(*CopyLeftBB) << '\t' <<
CopyMI; } } while (false)
1186 << printMBBReference(*CopyLeftBB) << '\t' << CopyMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremovePartialRedundancy: Move the copy to "
<< printMBBReference(*CopyLeftBB) << '\t' <<
CopyMI; } } while (false)
;
1187
1188 // Insert new copy to CopyLeftBB.
1189 MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
1190 TII->get(TargetOpcode::COPY), IntB.reg())
1191 .addReg(IntA.reg());
1192 SlotIndex NewCopyIdx =
1193 LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
1194 IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1195 for (LiveInterval::SubRange &SR : IntB.subranges())
1196 SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1197
1198 // If the newly created Instruction has an address of an instruction that was
1199 // deleted before (object recycled by the allocator) it needs to be removed from
1200 // the deleted list.
1201 ErasedInstrs.erase(NewCopyMI);
1202 } else {
1203 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremovePartialRedundancy: Remove the copy from "
<< printMBBReference(MBB) << '\t' << CopyMI
; } } while (false)
1204 << printMBBReference(MBB) << '\t' << CopyMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremovePartialRedundancy: Remove the copy from "
<< printMBBReference(MBB) << '\t' << CopyMI
; } } while (false)
;
1205 }
1206
1207 // Remove CopyMI.
1208 // Note: This is fine to remove the copy before updating the live-ranges.
1209 // While updating the live-ranges, we only look at slot indices and
1210 // never go back to the instruction.
1211 // Mark instructions as deleted.
1212 deleteInstr(&CopyMI);
1213
1214 // Update the liveness.
1215 SmallVector<SlotIndex, 8> EndPoints;
1216 VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
1217 LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
1218 &EndPoints);
1219 BValNo->markUnused();
1220 // Extend IntB to the EndPoints of its original live interval.
1221 LIS->extendToIndices(IntB, EndPoints);
1222
1223 // Now, do the same for its subranges.
1224 for (LiveInterval::SubRange &SR : IntB.subranges()) {
1225 EndPoints.clear();
1226 VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
1227 assert(BValNo && "All sublanes should be live")(static_cast <bool> (BValNo && "All sublanes should be live"
) ? void (0) : __assert_fail ("BValNo && \"All sublanes should be live\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1227, __extension__ __PRETTY_FUNCTION__))
;
1228 LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
1229 BValNo->markUnused();
1230 // We can have a situation where the result of the original copy is live,
1231 // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes
1232 // the copy appear as an endpoint from pruneValue(), but we don't want it
1233 // to because the copy has been removed. We can go ahead and remove that
1234 // endpoint; there is no other situation here that there could be a use at
1235 // the same place as we know that the copy is a full copy.
1236 for (unsigned I = 0; I != EndPoints.size(); ) {
1237 if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) {
1238 EndPoints[I] = EndPoints.back();
1239 EndPoints.pop_back();
1240 continue;
1241 }
1242 ++I;
1243 }
1244 SmallVector<SlotIndex, 8> Undefs;
1245 IntB.computeSubRangeUndefs(Undefs, SR.LaneMask, *MRI,
1246 *LIS->getSlotIndexes());
1247 LIS->extendToIndices(SR, EndPoints, Undefs);
1248 }
1249 // If any dead defs were extended, truncate them.
1250 shrinkToUses(&IntB);
1251
1252 // Finally, update the live-range of IntA.
1253 shrinkToUses(&IntA);
1254 return true;
1255}
1256
1257/// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
1258/// defining a subregister.
1259static bool definesFullReg(const MachineInstr &MI, Register Reg) {
1260 assert(!Reg.isPhysical() && "This code cannot handle physreg aliasing")(static_cast <bool> (!Reg.isPhysical() && "This code cannot handle physreg aliasing"
) ? void (0) : __assert_fail ("!Reg.isPhysical() && \"This code cannot handle physreg aliasing\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1260, __extension__ __PRETTY_FUNCTION__))
;
1261
1262 for (const MachineOperand &Op : MI.operands()) {
1263 if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
1264 continue;
1265 // Return true if we define the full register or don't care about the value
1266 // inside other subregisters.
1267 if (Op.getSubReg() == 0 || Op.isUndef())
1268 return true;
1269 }
1270 return false;
1271}
1272
1273bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
1274 MachineInstr *CopyMI,
1275 bool &IsDefCopy) {
1276 IsDefCopy = false;
1277 Register SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
1278 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
1279 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
1280 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
1281 if (Register::isPhysicalRegister(SrcReg))
1282 return false;
1283
1284 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1285 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1286 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
1287 if (!ValNo)
1288 return false;
1289 if (ValNo->isPHIDef() || ValNo->isUnused())
1290 return false;
1291 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
1292 if (!DefMI)
1293 return false;
1294 if (DefMI->isCopyLike()) {
1295 IsDefCopy = true;
1296 return false;
1297 }
1298 if (!TII->isAsCheapAsAMove(*DefMI))
1299 return false;
1300 if (!TII->isTriviallyReMaterializable(*DefMI, AA))
1301 return false;
1302 if (!definesFullReg(*DefMI, SrcReg))
1303 return false;
1304 bool SawStore = false;
1305 if (!DefMI->isSafeToMove(AA, SawStore))
1306 return false;
1307 const MCInstrDesc &MCID = DefMI->getDesc();
1308 if (MCID.getNumDefs() != 1)
1309 return false;
1310 // Only support subregister destinations when the def is read-undef.
1311 MachineOperand &DstOperand = CopyMI->getOperand(0);
1312 Register CopyDstReg = DstOperand.getReg();
1313 if (DstOperand.getSubReg() && !DstOperand.isUndef())
1314 return false;
1315
1316 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
1317 // the register substantially (beyond both source and dest size). This is bad
1318 // for performance since it can cascade through a function, introducing many
1319 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
1320 // around after a few subreg copies).
1321 if (SrcIdx && DstIdx)
1322 return false;
1323
1324 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
1325 if (!DefMI->isImplicitDef()) {
1326 if (DstReg.isPhysical()) {
1327 Register NewDstReg = DstReg;
1328
1329 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
1330 DefMI->getOperand(0).getSubReg());
1331 if (NewDstIdx)
1332 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
1333
1334 // Finally, make sure that the physical subregister that will be
1335 // constructed later is permitted for the instruction.
1336 if (!DefRC->contains(NewDstReg))
1337 return false;
1338 } else {
1339 // Theoretically, some stack frame reference could exist. Just make sure
1340 // it hasn't actually happened.
1341 assert(Register::isVirtualRegister(DstReg) &&(static_cast <bool> (Register::isVirtualRegister(DstReg
) && "Only expect to deal with virtual or physical registers"
) ? void (0) : __assert_fail ("Register::isVirtualRegister(DstReg) && \"Only expect to deal with virtual or physical registers\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1342, __extension__ __PRETTY_FUNCTION__))
1342 "Only expect to deal with virtual or physical registers")(static_cast <bool> (Register::isVirtualRegister(DstReg
) && "Only expect to deal with virtual or physical registers"
) ? void (0) : __assert_fail ("Register::isVirtualRegister(DstReg) && \"Only expect to deal with virtual or physical registers\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1342, __extension__ __PRETTY_FUNCTION__))
;
1343 }
1344 }
1345
1346 DebugLoc DL = CopyMI->getDebugLoc();
1347 MachineBasicBlock *MBB = CopyMI->getParent();
1348 MachineBasicBlock::iterator MII =
1349 std::next(MachineBasicBlock::iterator(CopyMI));
1350 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI);
1351 MachineInstr &NewMI = *std::prev(MII);
1352 NewMI.setDebugLoc(DL);
1353
1354 // In a situation like the following:
1355 // %0:subreg = instr ; DefMI, subreg = DstIdx
1356 // %1 = copy %0:subreg ; CopyMI, SrcIdx = 0
1357 // instead of widening %1 to the register class of %0 simply do:
1358 // %1 = instr
1359 const TargetRegisterClass *NewRC = CP.getNewRC();
1360 if (DstIdx != 0) {
1361 MachineOperand &DefMO = NewMI.getOperand(0);
1362 if (DefMO.getSubReg() == DstIdx) {
1363 assert(SrcIdx == 0 && CP.isFlipped()(static_cast <bool> (SrcIdx == 0 && CP.isFlipped
() && "Shouldn't have SrcIdx+DstIdx at this point") ?
void (0) : __assert_fail ("SrcIdx == 0 && CP.isFlipped() && \"Shouldn't have SrcIdx+DstIdx at this point\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1364, __extension__ __PRETTY_FUNCTION__))
1364 && "Shouldn't have SrcIdx+DstIdx at this point")(static_cast <bool> (SrcIdx == 0 && CP.isFlipped
() && "Shouldn't have SrcIdx+DstIdx at this point") ?
void (0) : __assert_fail ("SrcIdx == 0 && CP.isFlipped() && \"Shouldn't have SrcIdx+DstIdx at this point\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1364, __extension__ __PRETTY_FUNCTION__))
;
1365 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
1366 const TargetRegisterClass *CommonRC =
1367 TRI->getCommonSubClass(DefRC, DstRC);
1368 if (CommonRC != nullptr) {
1369 NewRC = CommonRC;
1370 DstIdx = 0;
1371 DefMO.setSubReg(0);
1372 DefMO.setIsUndef(false); // Only subregs can have def+undef.
1373 }
1374 }
1375 }
1376
1377 // CopyMI may have implicit operands, save them so that we can transfer them
1378 // over to the newly materialized instruction after CopyMI is removed.
1379 SmallVector<MachineOperand, 4> ImplicitOps;
1380 ImplicitOps.reserve(CopyMI->getNumOperands() -
1381 CopyMI->getDesc().getNumOperands());
1382 for (unsigned I = CopyMI->getDesc().getNumOperands(),
1383 E = CopyMI->getNumOperands();
1384 I != E; ++I) {
1385 MachineOperand &MO = CopyMI->getOperand(I);
1386 if (MO.isReg()) {
1387 assert(MO.isImplicit() && "No explicit operands after implicit operands.")(static_cast <bool> (MO.isImplicit() && "No explicit operands after implicit operands."
) ? void (0) : __assert_fail ("MO.isImplicit() && \"No explicit operands after implicit operands.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1387, __extension__ __PRETTY_FUNCTION__))
;
1388 // Discard VReg implicit defs.
1389 if (Register::isPhysicalRegister(MO.getReg()))
1390 ImplicitOps.push_back(MO);
1391 }
1392 }
1393
1394 LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI);
1395 CopyMI->eraseFromParent();
1396 ErasedInstrs.insert(CopyMI);
1397
1398 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
1399 // We need to remember these so we can add intervals once we insert
1400 // NewMI into SlotIndexes.
1401 SmallVector<MCRegister, 4> NewMIImplDefs;
1402 for (unsigned i = NewMI.getDesc().getNumOperands(),
1403 e = NewMI.getNumOperands();
1404 i != e; ++i) {
1405 MachineOperand &MO = NewMI.getOperand(i);
1406 if (MO.isReg() && MO.isDef()) {
1407 assert(MO.isImplicit() && MO.isDead() &&(static_cast <bool> (MO.isImplicit() && MO.isDead
() && Register::isPhysicalRegister(MO.getReg())) ? void
(0) : __assert_fail ("MO.isImplicit() && MO.isDead() && Register::isPhysicalRegister(MO.getReg())"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1408, __extension__ __PRETTY_FUNCTION__))
1408 Register::isPhysicalRegister(MO.getReg()))(static_cast <bool> (MO.isImplicit() && MO.isDead
() && Register::isPhysicalRegister(MO.getReg())) ? void
(0) : __assert_fail ("MO.isImplicit() && MO.isDead() && Register::isPhysicalRegister(MO.getReg())"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1408, __extension__ __PRETTY_FUNCTION__))
;
1409 NewMIImplDefs.push_back(MO.getReg().asMCReg());
1410 }
1411 }
1412
1413 if (DstReg.isVirtual()) {
1414 unsigned NewIdx = NewMI.getOperand(0).getSubReg();
1415
1416 if (DefRC != nullptr) {
1417 if (NewIdx)
1418 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
1419 else
1420 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
1421 assert(NewRC && "subreg chosen for remat incompatible with instruction")(static_cast <bool> (NewRC && "subreg chosen for remat incompatible with instruction"
) ? void (0) : __assert_fail ("NewRC && \"subreg chosen for remat incompatible with instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1421, __extension__ __PRETTY_FUNCTION__))
;
1422 }
1423 // Remap subranges to new lanemask and change register class.
1424 LiveInterval &DstInt = LIS->getInterval(DstReg);
1425 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1426 SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
1427 }
1428 MRI->setRegClass(DstReg, NewRC);
1429
1430 // Update machine operands and add flags.
1431 updateRegDefsUses(DstReg, DstReg, DstIdx);
1432 NewMI.getOperand(0).setSubReg(NewIdx);
1433 // updateRegDefUses can add an "undef" flag to the definition, since
1434 // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
1435 // sure that "undef" is not set.
1436 if (NewIdx == 0)
1437 NewMI.getOperand(0).setIsUndef(false);
1438 // Add dead subregister definitions if we are defining the whole register
1439 // but only part of it is live.
1440 // This could happen if the rematerialization instruction is rematerializing
1441 // more than actually is used in the register.
1442 // An example would be:
1443 // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
1444 // ; Copying only part of the register here, but the rest is undef.
1445 // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit
1446 // ==>
1447 // ; Materialize all the constants but only using one
1448 // %2 = LOAD_CONSTANTS 5, 8
1449 //
1450 // at this point for the part that wasn't defined before we could have
1451 // subranges missing the definition.
1452 if (NewIdx == 0 && DstInt.hasSubRanges()) {
1453 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1454 SlotIndex DefIndex =
1455 CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1456 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
1457 VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator();
1458 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1459 if (!SR.liveAt(DefIndex))
1460 SR.createDeadDef(DefIndex, Alloc);
1461 MaxMask &= ~SR.LaneMask;
1462 }
1463 if (MaxMask.any()) {
1464 LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
1465 SR->createDeadDef(DefIndex, Alloc);
1466 }
1467 }
1468
1469 // Make sure that the subrange for resultant undef is removed
1470 // For example:
1471 // %1:sub1<def,read-undef> = LOAD CONSTANT 1
1472 // %2 = COPY %1
1473 // ==>
1474 // %2:sub1<def, read-undef> = LOAD CONSTANT 1
1475 // ; Correct but need to remove the subrange for %2:sub0
1476 // ; as it is now undef
1477 if (NewIdx != 0 && DstInt.hasSubRanges()) {
1478 // The affected subregister segments can be removed.
1479 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1480 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
1481 bool UpdatedSubRanges = false;
1482 SlotIndex DefIndex =
1483 CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1484 VNInfo::Allocator &Alloc = LIS->getVNInfoAllocator();
1485 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1486 if ((SR.LaneMask & DstMask).none()) {
1487 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Removing undefined SubRange "
<< PrintLaneMask(SR.LaneMask) << " : " << SR
<< "\n"; } } while (false)
1488 << "Removing undefined SubRange "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Removing undefined SubRange "
<< PrintLaneMask(SR.LaneMask) << " : " << SR
<< "\n"; } } while (false)
1489 << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Removing undefined SubRange "
<< PrintLaneMask(SR.LaneMask) << " : " << SR
<< "\n"; } } while (false)
;
1490 // VNI is in ValNo - remove any segments in this SubRange that have this ValNo
1491 if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) {
1492 SR.removeValNo(RmValNo);
1493 UpdatedSubRanges = true;
1494 }
1495 } else {
1496 // We know that this lane is defined by this instruction,
1497 // but at this point it may be empty because it is not used by
1498 // anything. This happens when updateRegDefUses adds the missing
1499 // lanes. Assign that lane a dead def so that the interferences
1500 // are properly modeled.
1501 if (SR.empty())
1502 SR.createDeadDef(DefIndex, Alloc);
1503 }
1504 }
1505 if (UpdatedSubRanges)
1506 DstInt.removeEmptySubRanges();
1507 }
1508 } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
1509 // The New instruction may be defining a sub-register of what's actually
1510 // been asked for. If so it must implicitly define the whole thing.
1511 assert(Register::isPhysicalRegister(DstReg) &&(static_cast <bool> (Register::isPhysicalRegister(DstReg
) && "Only expect virtual or physical registers in remat"
) ? void (0) : __assert_fail ("Register::isPhysicalRegister(DstReg) && \"Only expect virtual or physical registers in remat\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1512, __extension__ __PRETTY_FUNCTION__))
1512 "Only expect virtual or physical registers in remat")(static_cast <bool> (Register::isPhysicalRegister(DstReg
) && "Only expect virtual or physical registers in remat"
) ? void (0) : __assert_fail ("Register::isPhysicalRegister(DstReg) && \"Only expect virtual or physical registers in remat\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1512, __extension__ __PRETTY_FUNCTION__))
;
1513 NewMI.getOperand(0).setIsDead(true);
1514 NewMI.addOperand(MachineOperand::CreateReg(
1515 CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
1516 // Record small dead def live-ranges for all the subregisters
1517 // of the destination register.
1518 // Otherwise, variables that live through may miss some
1519 // interferences, thus creating invalid allocation.
1520 // E.g., i386 code:
1521 // %1 = somedef ; %1 GR8
1522 // %2 = remat ; %2 GR32
1523 // CL = COPY %2.sub_8bit
1524 // = somedef %1 ; %1 GR8
1525 // =>
1526 // %1 = somedef ; %1 GR8
1527 // dead ECX = remat ; implicit-def CL
1528 // = somedef %1 ; %1 GR8
1529 // %1 will see the interferences with CL but not with CH since
1530 // no live-ranges would have been created for ECX.
1531 // Fix that!
1532 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1533 for (MCRegUnitIterator Units(NewMI.getOperand(0).getReg(), TRI);
1534 Units.isValid(); ++Units)
1535 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1536 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1537 }
1538
1539 if (NewMI.getOperand(0).getSubReg())
1540 NewMI.getOperand(0).setIsUndef();
1541
1542 // Transfer over implicit operands to the rematerialized instruction.
1543 for (MachineOperand &MO : ImplicitOps)
1544 NewMI.addOperand(MO);
1545
1546 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1547 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
1548 MCRegister Reg = NewMIImplDefs[i];
1549 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1550 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1551 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1552 }
1553
1554 LLVM_DEBUG(dbgs() << "Remat: " << NewMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Remat: " << NewMI; } }
while (false)
;
1555 ++NumReMats;
1556
1557 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1558 // to describe DstReg instead.
1559 if (MRI->use_nodbg_empty(SrcReg)) {
1560 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg);
1561 UI != MRI->use_end();) {
1562 MachineOperand &UseMO = *UI++;
1563 MachineInstr *UseMI = UseMO.getParent();
1564 if (UseMI->isDebugInstr()) {
1565 if (Register::isPhysicalRegister(DstReg))
1566 UseMO.substPhysReg(DstReg, *TRI);
1567 else
1568 UseMO.setReg(DstReg);
1569 // Move the debug value directly after the def of the rematerialized
1570 // value in DstReg.
1571 MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
1572 LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tupdated: " << *UseMI
; } } while (false)
;
1573 }
1574 }
1575 }
1576
1577 if (ToBeUpdated.count(SrcReg))
1578 return true;
1579
1580 unsigned NumCopyUses = 0;
1581 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
1582 if (UseMO.getParent()->isCopyLike())
1583 NumCopyUses++;
1584 }
1585 if (NumCopyUses < LateRematUpdateThreshold) {
1586 // The source interval can become smaller because we removed a use.
1587 shrinkToUses(&SrcInt, &DeadDefs);
1588 if (!DeadDefs.empty())
1589 eliminateDeadDefs();
1590 } else {
1591 ToBeUpdated.insert(SrcReg);
1592 }
1593 return true;
1594}
1595
1596MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1597 // ProcessImplicitDefs may leave some copies of <undef> values, it only
1598 // removes local variables. When we have a copy like:
1599 //
1600 // %1 = COPY undef %2
1601 //
1602 // We delete the copy and remove the corresponding value number from %1.
1603 // Any uses of that value number are marked as <undef>.
1604
1605 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1606 // CoalescerPair may have a new register class with adjusted subreg indices
1607 // at this point.
1608 Register SrcReg, DstReg;
1609 unsigned SrcSubIdx = 0, DstSubIdx = 0;
1610 if(!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1611 return nullptr;
1612
1613 SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
1614 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1615 // CopyMI is undef iff SrcReg is not live before the instruction.
1616 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1617 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1618 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1619 if ((SR.LaneMask & SrcMask).none())
1620 continue;
1621 if (SR.liveAt(Idx))
1622 return nullptr;
1623 }
1624 } else if (SrcLI.liveAt(Idx))
1625 return nullptr;
1626
1627 // If the undef copy defines a live-out value (i.e. an input to a PHI def),
1628 // then replace it with an IMPLICIT_DEF.
1629 LiveInterval &DstLI = LIS->getInterval(DstReg);
1630 SlotIndex RegIndex = Idx.getRegSlot();
1631 LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
1632 assert(Seg != nullptr && "No segment for defining instruction")(static_cast <bool> (Seg != nullptr && "No segment for defining instruction"
) ? void (0) : __assert_fail ("Seg != nullptr && \"No segment for defining instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1632, __extension__ __PRETTY_FUNCTION__))
;
1633 if (VNInfo *V = DstLI.getVNInfoAt(Seg->end)) {
1634 if (V->isPHIDef()) {
1635 CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1636 for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
1637 MachineOperand &MO = CopyMI->getOperand(i-1);
1638 if (MO.isReg() && MO.isUse())
1639 CopyMI->RemoveOperand(i-1);
1640 }
1641 LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tReplaced copy of <undef> value with an "
"implicit def\n"; } } while (false)
1642 "implicit def\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tReplaced copy of <undef> value with an "
"implicit def\n"; } } while (false)
;
1643 return CopyMI;
1644 }
1645 }
1646
1647 // Remove any DstReg segments starting at the instruction.
1648 LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tEliminating copy of <undef> value\n"
; } } while (false)
;
1649
1650 // Remove value or merge with previous one in case of a subregister def.
1651 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1652 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1653 DstLI.MergeValueNumberInto(VNI, PrevVNI);
1654
1655 // The affected subregister segments can be removed.
1656 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1657 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1658 if ((SR.LaneMask & DstMask).none())
1659 continue;
1660
1661 VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1662 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex))(static_cast <bool> (SVNI != nullptr && SlotIndex
::isSameInstr(SVNI->def, RegIndex)) ? void (0) : __assert_fail
("SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex)"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1662, __extension__ __PRETTY_FUNCTION__))
;
1663 SR.removeValNo(SVNI);
1664 }
1665 DstLI.removeEmptySubRanges();
1666 } else
1667 LIS->removeVRegDefAt(DstLI, RegIndex);
1668
1669 // Mark uses as undef.
1670 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1671 if (MO.isDef() /*|| MO.isUndef()*/)
1672 continue;
1673 const MachineInstr &MI = *MO.getParent();
1674 SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1675 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1676 bool isLive;
1677 if (!UseMask.all() && DstLI.hasSubRanges()) {
1678 isLive = false;
1679 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1680 if ((SR.LaneMask & UseMask).none())
1681 continue;
1682 if (SR.liveAt(UseIdx)) {
1683 isLive = true;
1684 break;
1685 }
1686 }
1687 } else
1688 isLive = DstLI.liveAt(UseIdx);
1689 if (isLive)
1690 continue;
1691 MO.setIsUndef(true);
1692 LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tnew undef: " << UseIdx
<< '\t' << MI; } } while (false)
;
1693 }
1694
1695 // A def of a subregister may be a use of the other subregisters, so
1696 // deleting a def of a subregister may also remove uses. Since CopyMI
1697 // is still part of the function (but about to be erased), mark all
1698 // defs of DstReg in it as <undef>, so that shrinkToUses would
1699 // ignore them.
1700 for (MachineOperand &MO : CopyMI->operands())
1701 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1702 MO.setIsUndef(true);
1703 LIS->shrinkToUses(&DstLI);
1704
1705 return CopyMI;
1706}
1707
1708void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
1709 MachineOperand &MO, unsigned SubRegIdx) {
1710 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1711 if (MO.isDef())
1712 Mask = ~Mask;
1713 bool IsUndef = true;
1714 for (const LiveInterval::SubRange &S : Int.subranges()) {
1715 if ((S.LaneMask & Mask).none())
1716 continue;
1717 if (S.liveAt(UseIdx)) {
1718 IsUndef = false;
1719 break;
1720 }
1721 }
1722 if (IsUndef) {
1723 MO.setIsUndef(true);
1724 // We found out some subregister use is actually reading an undefined
1725 // value. In some cases the whole vreg has become undefined at this
1726 // point so we have to potentially shrink the main range if the
1727 // use was ending a live segment there.
1728 LiveQueryResult Q = Int.Query(UseIdx);
1729 if (Q.valueOut() == nullptr)
1730 ShrinkMainRange = true;
1731 }
1732}
1733
1734void RegisterCoalescer::updateRegDefsUses(Register SrcReg, Register DstReg,
1735 unsigned SubIdx) {
1736 bool DstIsPhys = Register::isPhysicalRegister(DstReg);
1737 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1738
1739 if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) {
1740 for (MachineOperand &MO : MRI->reg_operands(DstReg)) {
1741 unsigned SubReg = MO.getSubReg();
1742 if (SubReg == 0 || MO.isUndef())
1743 continue;
1744 MachineInstr &MI = *MO.getParent();
1745 if (MI.isDebugInstr())
1746 continue;
1747 SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true);
1748 addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1749 }
1750 }
1751
1752 SmallPtrSet<MachineInstr*, 8> Visited;
1753 for (MachineRegisterInfo::reg_instr_iterator
1754 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1755 I != E; ) {
1756 MachineInstr *UseMI = &*(I++);
1757
1758 // Each instruction can only be rewritten once because sub-register
1759 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1760 // the UseMI operands removes them from the SrcReg use-def chain, but when
1761 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1762 // operands mentioning the virtual register.
1763 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1764 continue;
1765
1766 SmallVector<unsigned,8> Ops;
1767 bool Reads, Writes;
1768 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1769
1770 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1771 // because SrcReg is a sub-register.
1772 if (DstInt && !Reads && SubIdx && !UseMI->isDebugInstr())
1773 Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
1774
1775 // Replace SrcReg with DstReg in all UseMI operands.
1776 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1777 MachineOperand &MO = UseMI->getOperand(Ops[i]);
1778
1779 // Adjust <undef> flags in case of sub-register joins. We don't want to
1780 // turn a full def into a read-modify-write sub-register def and vice
1781 // versa.
1782 if (SubIdx && MO.isDef())
1783 MO.setIsUndef(!Reads);
1784
1785 // A subreg use of a partially undef (super) register may be a complete
1786 // undef use now and then has to be marked that way.
1787 if (MO.isUse() && !DstIsPhys) {
1788 unsigned SubUseIdx = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
1789 if (SubUseIdx != 0 && MRI->shouldTrackSubRegLiveness(DstReg)) {
1790 if (!DstInt->hasSubRanges()) {
1791 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1792 LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstInt->reg());
1793 LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1794 LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1795 DstInt->createSubRangeFrom(Allocator, UsedLanes, *DstInt);
1796 // The unused lanes are just empty live-ranges at this point.
1797 // It is the caller responsibility to set the proper
1798 // dead segments if there is an actual dead def of the
1799 // unused lanes. This may happen with rematerialization.
1800 DstInt->createSubRange(Allocator, UnusedLanes);
1801 }
1802 SlotIndex MIIdx = UseMI->isDebugInstr()
1803 ? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
1804 : LIS->getInstructionIndex(*UseMI);
1805 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1806 addUndefFlag(*DstInt, UseIdx, MO, SubUseIdx);
1807 }
1808 }
1809
1810 if (DstIsPhys)
1811 MO.substPhysReg(DstReg, *TRI);
1812 else
1813 MO.substVirtReg(DstReg, SubIdx, *TRI);
1814 }
1815
1816 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI
->isDebugInstr()) dbgs() << LIS->getInstructionIndex
(*UseMI) << "\t"; dbgs() << *UseMI; }; } } while (
false)
1817 dbgs() << "\t\tupdated: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI
->isDebugInstr()) dbgs() << LIS->getInstructionIndex
(*UseMI) << "\t"; dbgs() << *UseMI; }; } } while (
false)
1818 if (!UseMI->isDebugInstr())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI
->isDebugInstr()) dbgs() << LIS->getInstructionIndex
(*UseMI) << "\t"; dbgs() << *UseMI; }; } } while (
false)
1819 dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI
->isDebugInstr()) dbgs() << LIS->getInstructionIndex
(*UseMI) << "\t"; dbgs() << *UseMI; }; } } while (
false)
1820 dbgs() << *UseMI;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI
->isDebugInstr()) dbgs() << LIS->getInstructionIndex
(*UseMI) << "\t"; dbgs() << *UseMI; }; } } while (
false)
1821 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tupdated: "; if (!UseMI
->isDebugInstr()) dbgs() << LIS->getInstructionIndex
(*UseMI) << "\t"; dbgs() << *UseMI; }; } } while (
false)
;
1822 }
1823}
1824
1825bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1826 // Always join simple intervals that are defined by a single copy from a
1827 // reserved register. This doesn't increase register pressure, so it is
1828 // always beneficial.
1829 if (!MRI->isReserved(CP.getDstReg())) {
1830 LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tCan only merge into reserved registers.\n"
; } } while (false)
;
1831 return false;
1832 }
1833
1834 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1835 if (JoinVInt.containsOneValue())
1836 return true;
1837
1838 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tCannot join complex intervals into reserved register.\n"
; } } while (false)
1839 dbgs() << "\tCannot join complex intervals into reserved register.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tCannot join complex intervals into reserved register.\n"
; } } while (false)
;
1840 return false;
1841}
1842
1843bool RegisterCoalescer::copyValueUndefInPredecessors(
1844 LiveRange &S, const MachineBasicBlock *MBB, LiveQueryResult SLRQ) {
1845 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
1846 SlotIndex PredEnd = LIS->getMBBEndIdx(Pred);
1847 if (VNInfo *V = S.getVNInfoAt(PredEnd.getPrevSlot())) {
1848 // If this is a self loop, we may be reading the same value.
1849 if (V->id != SLRQ.valueOutOrDead()->id)
1850 return false;
1851 }
1852 }
1853
1854 return true;
1855}
1856
1857void RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
1858 Register Reg,
1859 LaneBitmask PrunedLanes) {
1860 // If we had other instructions in the segment reading the undef sublane
1861 // value, we need to mark them with undef.
1862 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
1863 unsigned SubRegIdx = MO.getSubReg();
1864 if (SubRegIdx == 0 || MO.isUndef())
1865 continue;
1866
1867 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1868 SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
1869 for (LiveInterval::SubRange &S : LI.subranges()) {
1870 if (!S.liveAt(Pos) && (PrunedLanes & SubRegMask).any()) {
1871 MO.setIsUndef();
1872 break;
1873 }
1874 }
1875 }
1876
1877 LI.removeEmptySubRanges();
1878
1879 // A def of a subregister may be a use of other register lanes. Replacing
1880 // such a def with a def of a different register will eliminate the use,
1881 // and may cause the recorded live range to be larger than the actual
1882 // liveness in the program IR.
1883 LIS->shrinkToUses(&LI);
1884}
1885
1886bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1887 Again = false;
1888 LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << LIS->getInstructionIndex(*
CopyMI) << '\t' << *CopyMI; } } while (false)
;
1889
1890 CoalescerPair CP(*TRI);
1891 if (!CP.setRegisters(CopyMI)) {
1892 LLVM_DEBUG(dbgs() << "\tNot coalescable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tNot coalescable.\n"; } } while
(false)
;
1893 return false;
1894 }
1895
1896 if (CP.getNewRC()) {
1897 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1898 auto DstRC = MRI->getRegClass(CP.getDstReg());
1899 unsigned SrcIdx = CP.getSrcIdx();
1900 unsigned DstIdx = CP.getDstIdx();
1901 if (CP.isFlipped()) {
1902 std::swap(SrcIdx, DstIdx);
1903 std::swap(SrcRC, DstRC);
1904 }
1905 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1906 CP.getNewRC(), *LIS)) {
1907 LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tSubtarget bailed on coalescing.\n"
; } } while (false)
;
1908 return false;
1909 }
1910 }
1911
1912 // Dead code elimination. This really should be handled by MachineDCE, but
1913 // sometimes dead copies slip through, and we can't generate invalid live
1914 // ranges.
1915 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1916 LLVM_DEBUG(dbgs() << "\tCopy is dead.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tCopy is dead.\n"; } } while
(false)
;
1917 DeadDefs.push_back(CopyMI);
1918 eliminateDeadDefs();
1919 return true;
1920 }
1921
1922 // Eliminate undefs.
1923 if (!CP.isPhys()) {
1924 // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
1925 if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
1926 if (UndefMI->isImplicitDef())
1927 return false;
1928 deleteInstr(CopyMI);
1929 return false; // Not coalescable.
1930 }
1931 }
1932
1933 // Coalesced copies are normally removed immediately, but transformations
1934 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1935 // When that happens, just join the values and remove the copy.
1936 if (CP.getSrcReg() == CP.getDstReg()) {
1937 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1938 LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tCopy already coalesced: " <<
LI << '\n'; } } while (false)
;
1939 const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1940 LiveQueryResult LRQ = LI.Query(CopyIdx);
1941 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1942 VNInfo *ReadVNI = LRQ.valueIn();
1943 assert(ReadVNI && "No value before copy and no <undef> flag.")(static_cast <bool> (ReadVNI && "No value before copy and no <undef> flag."
) ? void (0) : __assert_fail ("ReadVNI && \"No value before copy and no <undef> flag.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1943, __extension__ __PRETTY_FUNCTION__))
;
1944 assert(ReadVNI != DefVNI && "Cannot read and define the same value.")(static_cast <bool> (ReadVNI != DefVNI && "Cannot read and define the same value."
) ? void (0) : __assert_fail ("ReadVNI != DefVNI && \"Cannot read and define the same value.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 1944, __extension__ __PRETTY_FUNCTION__))
;
1945
1946 // Track incoming undef lanes we need to eliminate from the subrange.
1947 LaneBitmask PrunedLanes;
1948 MachineBasicBlock *MBB = CopyMI->getParent();
1949
1950 // Process subregister liveranges.
1951 for (LiveInterval::SubRange &S : LI.subranges()) {
1952 LiveQueryResult SLRQ = S.Query(CopyIdx);
1953 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1954 if (VNInfo *SReadVNI = SLRQ.valueIn())
1955 SDefVNI = S.MergeValueNumberInto(SDefVNI, SReadVNI);
1956
1957 // If this copy introduced an undef subrange from an incoming value,
1958 // we need to eliminate the undef live in values from the subrange.
1959 if (copyValueUndefInPredecessors(S, MBB, SLRQ)) {
1960 LLVM_DEBUG(dbgs() << "Incoming sublane value is undef at copy\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Incoming sublane value is undef at copy\n"
; } } while (false)
;
1961 PrunedLanes |= S.LaneMask;
1962 S.removeValNo(SDefVNI);
1963 }
1964 }
1965 }
1966
1967 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1968 if (PrunedLanes.any()) {
1969 LLVM_DEBUG(dbgs() << "Pruning undef incoming lanes: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Pruning undef incoming lanes: "
<< PrunedLanes << '\n'; } } while (false)
1970 << PrunedLanes << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Pruning undef incoming lanes: "
<< PrunedLanes << '\n'; } } while (false)
;
1971 setUndefOnPrunedSubRegUses(LI, CP.getSrcReg(), PrunedLanes);
1972 }
1973
1974 LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tMerged values: " <<
LI << '\n'; } } while (false)
;
1975 }
1976 deleteInstr(CopyMI);
1977 return true;
1978 }
1979
1980 // Enforce policies.
1981 if (CP.isPhys()) {
1982 LLVM_DEBUG(dbgs() << "\tConsidering merging "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tConsidering merging " <<
printReg(CP.getSrcReg(), TRI) << " with " << printReg
(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; } } while
(false)
1983 << printReg(CP.getSrcReg(), TRI) << " with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tConsidering merging " <<
printReg(CP.getSrcReg(), TRI) << " with " << printReg
(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; } } while
(false)
1984 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tConsidering merging " <<
printReg(CP.getSrcReg(), TRI) << " with " << printReg
(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; } } while
(false)
;
1985 if (!canJoinPhys(CP)) {
1986 // Before giving up coalescing, if definition of source is defined by
1987 // trivial computation, try rematerializing it.
1988 bool IsDefCopy = false;
1989 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1990 return true;
1991 if (IsDefCopy)
1992 Again = true; // May be possible to coalesce later.
1993 return false;
1994 }
1995 } else {
1996 // When possible, let DstReg be the larger interval.
1997 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1998 LIS->getInterval(CP.getDstReg()).size())
1999 CP.flip();
2000
2001 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2002 dbgs() << "\tConsidering merging to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2003 << TRI->getRegClassName(CP.getNewRC()) << " with ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2004 if (CP.getDstIdx() && CP.getSrcIdx())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2005 dbgs() << printReg(CP.getDstReg()) << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2006 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2007 << printReg(CP.getSrcReg()) << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2008 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2009 elsedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2010 dbgs() << printReg(CP.getSrcReg(), TRI) << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2011 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
2012 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tConsidering merging to "
<< TRI->getRegClassName(CP.getNewRC()) << " with "
; if (CP.getDstIdx() && CP.getSrcIdx()) dbgs() <<
printReg(CP.getDstReg()) << " in " << TRI->getSubRegIndexName
(CP.getDstIdx()) << " and " << printReg(CP.getSrcReg
()) << " in " << TRI->getSubRegIndexName(CP.getSrcIdx
()) << '\n'; else dbgs() << printReg(CP.getSrcReg
(), TRI) << " in " << printReg(CP.getDstReg(), TRI
, CP.getSrcIdx()) << '\n'; }; } } while (false)
;
2013 }
2014
2015 ShrinkMask = LaneBitmask::getNone();
2016 ShrinkMainRange = false;
2017
2018 // Okay, attempt to join these two intervals. On failure, this returns false.
2019 // Otherwise, if one of the intervals being joined is a physreg, this method
2020 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
2021 // been modified, so we can use this information below to update aliases.
2022 if (!joinIntervals(CP)) {
2023 // Coalescing failed.
2024
2025 // If definition of source is defined by trivial computation, try
2026 // rematerializing it.
2027 bool IsDefCopy = false;
2028 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
2029 return true;
2030
2031 // If we can eliminate the copy without merging the live segments, do so
2032 // now.
2033 if (!CP.isPartial() && !CP.isPhys()) {
2034 bool Changed = adjustCopiesBackFrom(CP, CopyMI);
2035 bool Shrink = false;
2036 if (!Changed)
2037 std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI);
2038 if (Changed) {
2039 deleteInstr(CopyMI);
2040 if (Shrink) {
2041 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
2042 LiveInterval &DstLI = LIS->getInterval(DstReg);
2043 shrinkToUses(&DstLI);
2044 LLVM_DEBUG(dbgs() << "\t\tshrunk: " << DstLI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tshrunk: " << DstLI
<< '\n'; } } while (false)
;
2045 }
2046 LLVM_DEBUG(dbgs() << "\tTrivial!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tTrivial!\n"; } } while (false
)
;
2047 return true;
2048 }
2049 }
2050
2051 // Try and see if we can partially eliminate the copy by moving the copy to
2052 // its predecessor.
2053 if (!CP.isPartial() && !CP.isPhys())
2054 if (removePartialRedundancy(CP, *CopyMI))
2055 return true;
2056
2057 // Otherwise, we are unable to join the intervals.
2058 LLVM_DEBUG(dbgs() << "\tInterference!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tInterference!\n"; } } while
(false)
;
2059 Again = true; // May be possible to coalesce later.
2060 return false;
2061 }
2062
2063 // Coalescing to a virtual register that is of a sub-register class of the
2064 // other. Make sure the resulting register is set to the right register class.
2065 if (CP.isCrossClass()) {
2066 ++numCrossRCs;
2067 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
2068 }
2069
2070 // Removing sub-register copies can ease the register class constraints.
2071 // Make sure we attempt to inflate the register class of DstReg.
2072 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
2073 InflateRegs.push_back(CP.getDstReg());
2074
2075 // CopyMI has been erased by joinIntervals at this point. Remove it from
2076 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
2077 // to the work list. This keeps ErasedInstrs from growing needlessly.
2078 ErasedInstrs.erase(CopyMI);
2079
2080 // Rewrite all SrcReg operands to DstReg.
2081 // Also update DstReg operands to include DstIdx if it is set.
2082 if (CP.getDstIdx())
2083 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
2084 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
2085
2086 // Shrink subregister ranges if necessary.
2087 if (ShrinkMask.any()) {
2088 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
2089 for (LiveInterval::SubRange &S : LI.subranges()) {
2090 if ((S.LaneMask & ShrinkMask).none())
2091 continue;
2092 LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Shrink LaneUses (Lane " <<
PrintLaneMask(S.LaneMask) << ")\n"; } } while (false)
2093 << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Shrink LaneUses (Lane " <<
PrintLaneMask(S.LaneMask) << ")\n"; } } while (false)
;
2094 LIS->shrinkToUses(S, LI.reg());
2095 }
2096 LI.removeEmptySubRanges();
2097 }
2098
2099 // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live
2100 // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval
2101 // is not up-to-date, need to update the merged live interval here.
2102 if (ToBeUpdated.count(CP.getSrcReg()))
2103 ShrinkMainRange = true;
2104
2105 if (ShrinkMainRange) {
2106 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
2107 shrinkToUses(&LI);
2108 }
2109
2110 // SrcReg is guaranteed to be the register whose live interval that is
2111 // being merged.
2112 LIS->removeInterval(CP.getSrcReg());
2113
2114 // Update regalloc hint.
2115 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
2116
2117 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2118 dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2119 << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2120 dbgs() << "\tResult = ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2121 if (CP.isPhys())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2122 dbgs() << printReg(CP.getDstReg(), TRI);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2123 elsedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2124 dbgs() << LIS->getInterval(CP.getDstReg());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2125 dbgs() << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
2126 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\tSuccess: " << printReg
(CP.getSrcReg(), TRI, CP.getSrcIdx()) << " -> " <<
printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
dbgs() << "\tResult = "; if (CP.isPhys()) dbgs() <<
printReg(CP.getDstReg(), TRI); else dbgs() << LIS->
getInterval(CP.getDstReg()); dbgs() << '\n'; }; } } while
(false)
;
2127
2128 ++numJoins;
2129 return true;
2130}
2131
2132bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
2133 Register DstReg = CP.getDstReg();
2134 Register SrcReg = CP.getSrcReg();
2135 assert(CP.isPhys() && "Must be a physreg copy")(static_cast <bool> (CP.isPhys() && "Must be a physreg copy"
) ? void (0) : __assert_fail ("CP.isPhys() && \"Must be a physreg copy\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2135, __extension__ __PRETTY_FUNCTION__))
;
2136 assert(MRI->isReserved(DstReg) && "Not a reserved register")(static_cast <bool> (MRI->isReserved(DstReg) &&
"Not a reserved register") ? void (0) : __assert_fail ("MRI->isReserved(DstReg) && \"Not a reserved register\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2136, __extension__ __PRETTY_FUNCTION__))
;
2137 LiveInterval &RHS = LIS->getInterval(SrcReg);
2138 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tRHS = " << RHS <<
'\n'; } } while (false)
;
2139
2140 assert(RHS.containsOneValue() && "Invalid join with reserved register")(static_cast <bool> (RHS.containsOneValue() && "Invalid join with reserved register"
) ? void (0) : __assert_fail ("RHS.containsOneValue() && \"Invalid join with reserved register\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2140, __extension__ __PRETTY_FUNCTION__))
;
2141
2142 // Optimization for reserved registers like ESP. We can only merge with a
2143 // reserved physreg if RHS has a single value that is a copy of DstReg.
2144 // The live range of the reserved register will look like a set of dead defs
2145 // - we don't properly track the live range of reserved registers.
2146
2147 // Deny any overlapping intervals. This depends on all the reserved
2148 // register live ranges to look like dead defs.
2149 if (!MRI->isConstantPhysReg(DstReg)) {
2150 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
2151 // Abort if not all the regunits are reserved.
2152 for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) {
2153 if (!MRI->isReserved(*RI))
2154 return false;
2155 }
2156 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
2157 LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tInterference: " <<
printRegUnit(*UI, TRI) << '\n'; } } while (false)
2158 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tInterference: " <<
printRegUnit(*UI, TRI) << '\n'; } } while (false)
;
2159 return false;
2160 }
2161 }
2162
2163 // We must also check for overlaps with regmask clobbers.
2164 BitVector RegMaskUsable;
2165 if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
2166 !RegMaskUsable.test(DstReg)) {
2167 LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tRegMask interference\n";
} } while (false)
;
2168 return false;
2169 }
2170 }
2171
2172 // Skip any value computations, we are not adding new values to the
2173 // reserved register. Also skip merging the live ranges, the reserved
2174 // register live range doesn't need to be accurate as long as all the
2175 // defs are there.
2176
2177 // Delete the identity copy.
2178 MachineInstr *CopyMI;
2179 if (CP.isFlipped()) {
2180 // Physreg is copied into vreg
2181 // %y = COPY %physreg_x
2182 // ... //< no other def of %physreg_x here
2183 // use %y
2184 // =>
2185 // ...
2186 // use %physreg_x
2187 CopyMI = MRI->getVRegDef(SrcReg);
2188 } else {
2189 // VReg is copied into physreg:
2190 // %y = def
2191 // ... //< no other def or use of %physreg_x here
2192 // %physreg_x = COPY %y
2193 // =>
2194 // %physreg_x = def
2195 // ...
2196 if (!MRI->hasOneNonDBGUse(SrcReg)) {
2197 LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tMultiple vreg uses!\n"; }
} while (false)
;
2198 return false;
2199 }
2200
2201 if (!LIS->intervalIsInOneMBB(RHS)) {
2202 LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tComplex control flow!\n"
; } } while (false)
;
2203 return false;
2204 }
2205
2206 MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
2207 CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
2208 SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
2209 SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
2210
2211 if (!MRI->isConstantPhysReg(DstReg)) {
2212 // We checked above that there are no interfering defs of the physical
2213 // register. However, for this case, where we intend to move up the def of
2214 // the physical register, we also need to check for interfering uses.
2215 SlotIndexes *Indexes = LIS->getSlotIndexes();
2216 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
2217 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
2218 MachineInstr *MI = LIS->getInstructionFromIndex(SI);
2219 if (MI->readsRegister(DstReg, TRI)) {
2220 LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tInterference (read): " <<
*MI; } } while (false)
;
2221 return false;
2222 }
2223 }
2224 }
2225
2226 // We're going to remove the copy which defines a physical reserved
2227 // register, so remove its valno, etc.
2228 LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tRemoving phys reg def of "
<< printReg(DstReg, TRI) << " at " << CopyRegIdx
<< "\n"; } } while (false)
2229 << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tRemoving phys reg def of "
<< printReg(DstReg, TRI) << " at " << CopyRegIdx
<< "\n"; } } while (false)
;
2230
2231 LIS->removePhysRegDefAt(DstReg.asMCReg(), CopyRegIdx);
2232 // Create a new dead def at the new def location.
2233 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
2234 LiveRange &LR = LIS->getRegUnit(*UI);
2235 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
2236 }
2237 }
2238
2239 deleteInstr(CopyMI);
2240
2241 // We don't track kills for reserved registers.
2242 MRI->clearKillFlags(CP.getSrcReg());
2243
2244 return true;
2245}
2246
2247//===----------------------------------------------------------------------===//
2248// Interference checking and interval joining
2249//===----------------------------------------------------------------------===//
2250//
2251// In the easiest case, the two live ranges being joined are disjoint, and
2252// there is no interference to consider. It is quite common, though, to have
2253// overlapping live ranges, and we need to check if the interference can be
2254// resolved.
2255//
2256// The live range of a single SSA value forms a sub-tree of the dominator tree.
2257// This means that two SSA values overlap if and only if the def of one value
2258// is contained in the live range of the other value. As a special case, the
2259// overlapping values can be defined at the same index.
2260//
2261// The interference from an overlapping def can be resolved in these cases:
2262//
2263// 1. Coalescable copies. The value is defined by a copy that would become an
2264// identity copy after joining SrcReg and DstReg. The copy instruction will
2265// be removed, and the value will be merged with the source value.
2266//
2267// There can be several copies back and forth, causing many values to be
2268// merged into one. We compute a list of ultimate values in the joined live
2269// range as well as a mappings from the old value numbers.
2270//
2271// 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
2272// predecessors have a live out value. It doesn't cause real interference,
2273// and can be merged into the value it overlaps. Like a coalescable copy, it
2274// can be erased after joining.
2275//
2276// 3. Copy of external value. The overlapping def may be a copy of a value that
2277// is already in the other register. This is like a coalescable copy, but
2278// the live range of the source register must be trimmed after erasing the
2279// copy instruction:
2280//
2281// %src = COPY %ext
2282// %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
2283//
2284// 4. Clobbering undefined lanes. Vector registers are sometimes built by
2285// defining one lane at a time:
2286//
2287// %dst:ssub0<def,read-undef> = FOO
2288// %src = BAR
2289// %dst:ssub1 = COPY %src
2290//
2291// The live range of %src overlaps the %dst value defined by FOO, but
2292// merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
2293// which was undef anyway.
2294//
2295// The value mapping is more complicated in this case. The final live range
2296// will have different value numbers for both FOO and BAR, but there is no
2297// simple mapping from old to new values. It may even be necessary to add
2298// new PHI values.
2299//
2300// 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
2301// is live, but never read. This can happen because we don't compute
2302// individual live ranges per lane.
2303//
2304// %dst = FOO
2305// %src = BAR
2306// %dst:ssub1 = COPY %src
2307//
2308// This kind of interference is only resolved locally. If the clobbered
2309// lane value escapes the block, the join is aborted.
2310
2311namespace {
2312
2313/// Track information about values in a single virtual register about to be
2314/// joined. Objects of this class are always created in pairs - one for each
2315/// side of the CoalescerPair (or one for each lane of a side of the coalescer
2316/// pair)
2317class JoinVals {
2318 /// Live range we work on.
2319 LiveRange &LR;
2320
2321 /// (Main) register we work on.
2322 const Register Reg;
2323
2324 /// Reg (and therefore the values in this liverange) will end up as
2325 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
2326 /// CP.SrcIdx.
2327 const unsigned SubIdx;
2328
2329 /// The LaneMask that this liverange will occupy the coalesced register. May
2330 /// be smaller than the lanemask produced by SubIdx when merging subranges.
2331 const LaneBitmask LaneMask;
2332
2333 /// This is true when joining sub register ranges, false when joining main
2334 /// ranges.
2335 const bool SubRangeJoin;
2336
2337 /// Whether the current LiveInterval tracks subregister liveness.
2338 const bool TrackSubRegLiveness;
2339
2340 /// Values that will be present in the final live range.
2341 SmallVectorImpl<VNInfo*> &NewVNInfo;
2342
2343 const CoalescerPair &CP;
2344 LiveIntervals *LIS;
2345 SlotIndexes *Indexes;
2346 const TargetRegisterInfo *TRI;
2347
2348 /// Value number assignments. Maps value numbers in LI to entries in
2349 /// NewVNInfo. This is suitable for passing to LiveInterval::join().
2350 SmallVector<int, 8> Assignments;
2351
2352 public:
2353 /// Conflict resolution for overlapping values.
2354 enum ConflictResolution {
2355 /// No overlap, simply keep this value.
2356 CR_Keep,
2357
2358 /// Merge this value into OtherVNI and erase the defining instruction.
2359 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
2360 /// values.
2361 CR_Erase,
2362
2363 /// Merge this value into OtherVNI but keep the defining instruction.
2364 /// This is for the special case where OtherVNI is defined by the same
2365 /// instruction.
2366 CR_Merge,
2367
2368 /// Keep this value, and have it replace OtherVNI where possible. This
2369 /// complicates value mapping since OtherVNI maps to two different values
2370 /// before and after this def.
2371 /// Used when clobbering undefined or dead lanes.
2372 CR_Replace,
2373
2374 /// Unresolved conflict. Visit later when all values have been mapped.
2375 CR_Unresolved,
2376
2377 /// Unresolvable conflict. Abort the join.
2378 CR_Impossible
2379 };
2380
2381 private:
2382 /// Per-value info for LI. The lane bit masks are all relative to the final
2383 /// joined register, so they can be compared directly between SrcReg and
2384 /// DstReg.
2385 struct Val {
2386 ConflictResolution Resolution = CR_Keep;
2387
2388 /// Lanes written by this def, 0 for unanalyzed values.
2389 LaneBitmask WriteLanes;
2390
2391 /// Lanes with defined values in this register. Other lanes are undef and
2392 /// safe to clobber.
2393 LaneBitmask ValidLanes;
2394
2395 /// Value in LI being redefined by this def.
2396 VNInfo *RedefVNI = nullptr;
2397
2398 /// Value in the other live range that overlaps this def, if any.
2399 VNInfo *OtherVNI = nullptr;
2400
2401 /// Is this value an IMPLICIT_DEF that can be erased?
2402 ///
2403 /// IMPLICIT_DEF values should only exist at the end of a basic block that
2404 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
2405 /// safely erased if they are overlapping a live value in the other live
2406 /// interval.
2407 ///
2408 /// Weird control flow graphs and incomplete PHI handling in
2409 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
2410 /// longer live ranges. Such IMPLICIT_DEF values should be treated like
2411 /// normal values.
2412 bool ErasableImplicitDef = false;
2413
2414 /// True when the live range of this value will be pruned because of an
2415 /// overlapping CR_Replace value in the other live range.
2416 bool Pruned = false;
2417
2418 /// True once Pruned above has been computed.
2419 bool PrunedComputed = false;
2420
2421 /// True if this value is determined to be identical to OtherVNI
2422 /// (in valuesIdentical). This is used with CR_Erase where the erased
2423 /// copy is redundant, i.e. the source value is already the same as
2424 /// the destination. In such cases the subranges need to be updated
2425 /// properly. See comment at pruneSubRegValues for more info.
2426 bool Identical = false;
2427
2428 Val() = default;
2429
2430 bool isAnalyzed() const { return WriteLanes.any(); }
2431 };
2432
2433 /// One entry per value number in LI.
2434 SmallVector<Val, 8> Vals;
2435
2436 /// Compute the bitmask of lanes actually written by DefMI.
2437 /// Set Redef if there are any partial register definitions that depend on the
2438 /// previous value of the register.
2439 LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
2440
2441 /// Find the ultimate value that VNI was copied from.
2442 std::pair<const VNInfo *, Register> followCopyChain(const VNInfo *VNI) const;
2443
2444 bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const;
2445
2446 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
2447 /// Return a conflict resolution when possible, but leave the hard cases as
2448 /// CR_Unresolved.
2449 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
2450 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
2451 /// The recursion always goes upwards in the dominator tree, making loops
2452 /// impossible.
2453 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
2454
2455 /// Compute the value assignment for ValNo in RI.
2456 /// This may be called recursively by analyzeValue(), but never for a ValNo on
2457 /// the stack.
2458 void computeAssignment(unsigned ValNo, JoinVals &Other);
2459
2460 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
2461 /// the extent of the tainted lanes in the block.
2462 ///
2463 /// Multiple values in Other.LR can be affected since partial redefinitions
2464 /// can preserve previously tainted lanes.
2465 ///
2466 /// 1 %dst = VLOAD <-- Define all lanes in %dst
2467 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
2468 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
2469 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
2470 ///
2471 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
2472 /// entry to TaintedVals.
2473 ///
2474 /// Returns false if the tainted lanes extend beyond the basic block.
2475 bool
2476 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2477 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
2478
2479 /// Return true if MI uses any of the given Lanes from Reg.
2480 /// This does not include partial redefinitions of Reg.
2481 bool usesLanes(const MachineInstr &MI, Register, unsigned, LaneBitmask) const;
2482
2483 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
2484 /// be pruned:
2485 ///
2486 /// %dst = COPY %src
2487 /// %src = COPY %dst <-- This value to be pruned.
2488 /// %dst = COPY %src <-- This value is a copy of a pruned value.
2489 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
2490
2491public:
2492 JoinVals(LiveRange &LR, Register Reg, unsigned SubIdx, LaneBitmask LaneMask,
2493 SmallVectorImpl<VNInfo *> &newVNInfo, const CoalescerPair &cp,
2494 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
2495 bool TrackSubRegLiveness)
2496 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2497 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2498 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2499 TRI(TRI), Assignments(LR.getNumValNums(), -1),
2500 Vals(LR.getNumValNums()) {}
2501
2502 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
2503 /// Returns false if any conflicts were impossible to resolve.
2504 bool mapValues(JoinVals &Other);
2505
2506 /// Try to resolve conflicts that require all values to be mapped.
2507 /// Returns false if any conflicts were impossible to resolve.
2508 bool resolveConflicts(JoinVals &Other);
2509
2510 /// Prune the live range of values in Other.LR where they would conflict with
2511 /// CR_Replace values in LR. Collect end points for restoring the live range
2512 /// after joining.
2513 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
2514 bool changeInstrs);
2515
2516 /// Removes subranges starting at copies that get removed. This sometimes
2517 /// happens when undefined subranges are copied around. These ranges contain
2518 /// no useful information and can be removed.
2519 void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
2520
2521 /// Pruning values in subranges can lead to removing segments in these
2522 /// subranges started by IMPLICIT_DEFs. The corresponding segments in
2523 /// the main range also need to be removed. This function will mark
2524 /// the corresponding values in the main range as pruned, so that
2525 /// eraseInstrs can do the final cleanup.
2526 /// The parameter @p LI must be the interval whose main range is the
2527 /// live range LR.
2528 void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
2529
2530 /// Erase any machine instructions that have been coalesced away.
2531 /// Add erased instructions to ErasedInstrs.
2532 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
2533 /// the erased instrs.
2534 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2535 SmallVectorImpl<Register> &ShrinkRegs,
2536 LiveInterval *LI = nullptr);
2537
2538 /// Remove liverange defs at places where implicit defs will be removed.
2539 void removeImplicitDefs();
2540
2541 /// Get the value assignments suitable for passing to LiveInterval::join.
2542 const int *getAssignments() const { return Assignments.data(); }
2543
2544 /// Get the conflict resolution for a value number.
2545 ConflictResolution getResolution(unsigned Num) const {
2546 return Vals[Num].Resolution;
2547 }
2548};
2549
2550} // end anonymous namespace
2551
2552LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
2553 const {
2554 LaneBitmask L;
2555 for (const MachineOperand &MO : DefMI->operands()) {
2556 if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef())
2557 continue;
2558 L |= TRI->getSubRegIndexLaneMask(
2559 TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
2560 if (MO.readsReg())
2561 Redef = true;
2562 }
2563 return L;
2564}
2565
2566std::pair<const VNInfo *, Register>
2567JoinVals::followCopyChain(const VNInfo *VNI) const {
2568 Register TrackReg = Reg;
2569
2570 while (!VNI->isPHIDef()) {
2
Calling 'VNInfo::isPHIDef'
8
Returning from 'VNInfo::isPHIDef'
9
Loop condition is true. Entering loop body
26
Called C++ object pointer is null
2571 SlotIndex Def = VNI->def;
2572 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2573 assert(MI && "No defining instruction")(static_cast <bool> (MI && "No defining instruction"
) ? void (0) : __assert_fail ("MI && \"No defining instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2573, __extension__ __PRETTY_FUNCTION__))
;
10
Assuming 'MI' is non-null
11
'?' condition is true
2574 if (!MI->isFullCopy())
12
Taking false branch
2575 return std::make_pair(VNI, TrackReg);
2576 Register SrcReg = MI->getOperand(1).getReg();
2577 if (!SrcReg.isVirtual())
13
Taking false branch
2578 return std::make_pair(VNI, TrackReg);
2579
2580 const LiveInterval &LI = LIS->getInterval(SrcReg);
2581 const VNInfo *ValueIn;
2582 // No subrange involved.
2583 if (!SubRangeJoin || !LI.hasSubRanges()) {
14
Assuming field 'SubRangeJoin' is false
2584 LiveQueryResult LRQ = LI.Query(Def);
2585 ValueIn = LRQ.valueIn();
2586 } else {
2587 // Query subranges. Ensure that all matching ones take us to the same def
2588 // (allowing some of them to be undef).
2589 ValueIn = nullptr;
2590 for (const LiveInterval::SubRange &S : LI.subranges()) {
2591 // Transform lanemask to a mask in the joined live interval.
2592 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
2593 if ((SMask & LaneMask).none())
2594 continue;
2595 LiveQueryResult LRQ = S.Query(Def);
2596 if (!ValueIn) {
2597 ValueIn = LRQ.valueIn();
2598 continue;
2599 }
2600 if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
2601 return std::make_pair(VNI, TrackReg);
2602 }
2603 }
2604 if (ValueIn == nullptr) {
15
Assuming the condition is true
16
Taking true branch
2605 // Reaching an undefined value is legitimate, for example:
2606 //
2607 // 1 undef %0.sub1 = ... ;; %0.sub0 == undef
2608 // 2 %1 = COPY %0 ;; %1 is defined here.
2609 // 3 %0 = COPY %1 ;; Now %0.sub0 has a definition,
2610 // ;; but it's equivalent to "undef".
2611 return std::make_pair(nullptr, SrcReg);
2612 }
2613 VNI = ValueIn;
2614 TrackReg = SrcReg;
2615 }
2616 return std::make_pair(VNI, TrackReg);
2617}
2618
2619bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2620 const JoinVals &Other) const {
2621 const VNInfo *Orig0;
2622 Register Reg0;
2623 std::tie(Orig0, Reg0) = followCopyChain(Value0);
1
Calling 'JoinVals::followCopyChain'
17
Returning from 'JoinVals::followCopyChain'
2624 if (Orig0 == Value1 && Reg0 == Other.Reg)
18
Assuming 'Orig0' is equal to 'Value1'
19
Calling 'Register::operator=='
22
Returning from 'Register::operator=='
23
Taking false branch
2625 return true;
2626
2627 const VNInfo *Orig1;
2628 Register Reg1;
2629 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
24
Passing null pointer value via 1st parameter 'VNI'
25
Calling 'JoinVals::followCopyChain'
2630 // If both values are undefined, and the source registers are the same
2631 // register, the values are identical. Filter out cases where only one
2632 // value is defined.
2633 if (Orig0 == nullptr || Orig1 == nullptr)
2634 return Orig0 == Orig1 && Reg0 == Reg1;
2635
2636 // The values are equal if they are defined at the same place and use the
2637 // same register. Note that we cannot compare VNInfos directly as some of
2638 // them might be from a copy created in mergeSubRangeInto() while the other
2639 // is from the original LiveInterval.
2640 return Orig0->def == Orig1->def && Reg0 == Reg1;
2641}
2642
2643JoinVals::ConflictResolution
2644JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
2645 Val &V = Vals[ValNo];
2646 assert(!V.isAnalyzed() && "Value has already been analyzed!")(static_cast <bool> (!V.isAnalyzed() && "Value has already been analyzed!"
) ? void (0) : __assert_fail ("!V.isAnalyzed() && \"Value has already been analyzed!\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2646, __extension__ __PRETTY_FUNCTION__))
;
2647 VNInfo *VNI = LR.getValNumInfo(ValNo);
2648 if (VNI->isUnused()) {
2649 V.WriteLanes = LaneBitmask::getAll();
2650 return CR_Keep;
2651 }
2652
2653 // Get the instruction defining this value, compute the lanes written.
2654 const MachineInstr *DefMI = nullptr;
2655 if (VNI->isPHIDef()) {
2656 // Conservatively assume that all lanes in a PHI are valid.
2657 LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
2658 : TRI->getSubRegIndexLaneMask(SubIdx);
2659 V.ValidLanes = V.WriteLanes = Lanes;
2660 } else {
2661 DefMI = Indexes->getInstructionFromIndex(VNI->def);
2662 assert(DefMI != nullptr)(static_cast <bool> (DefMI != nullptr) ? void (0) : __assert_fail
("DefMI != nullptr", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2662, __extension__ __PRETTY_FUNCTION__))
;
2663 if (SubRangeJoin) {
2664 // We don't care about the lanes when joining subregister ranges.
2665 V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
2666 if (DefMI->isImplicitDef()) {
2667 V.ValidLanes = LaneBitmask::getNone();
2668 V.ErasableImplicitDef = true;
2669 }
2670 } else {
2671 bool Redef = false;
2672 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2673
2674 // If this is a read-modify-write instruction, there may be more valid
2675 // lanes than the ones written by this instruction.
2676 // This only covers partial redef operands. DefMI may have normal use
2677 // operands reading the register. They don't contribute valid lanes.
2678 //
2679 // This adds ssub1 to the set of valid lanes in %src:
2680 //
2681 // %src:ssub1 = FOO
2682 //
2683 // This leaves only ssub1 valid, making any other lanes undef:
2684 //
2685 // %src:ssub1<def,read-undef> = FOO %src:ssub2
2686 //
2687 // The <read-undef> flag on the def operand means that old lane values are
2688 // not important.
2689 if (Redef) {
2690 V.RedefVNI = LR.Query(VNI->def).valueIn();
2691 assert((TrackSubRegLiveness || V.RedefVNI) &&(static_cast <bool> ((TrackSubRegLiveness || V.RedefVNI
) && "Instruction is reading nonexistent value") ? void
(0) : __assert_fail ("(TrackSubRegLiveness || V.RedefVNI) && \"Instruction is reading nonexistent value\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2692, __extension__ __PRETTY_FUNCTION__))
2692 "Instruction is reading nonexistent value")(static_cast <bool> ((TrackSubRegLiveness || V.RedefVNI
) && "Instruction is reading nonexistent value") ? void
(0) : __assert_fail ("(TrackSubRegLiveness || V.RedefVNI) && \"Instruction is reading nonexistent value\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2692, __extension__ __PRETTY_FUNCTION__))
;
2693 if (V.RedefVNI != nullptr) {
2694 computeAssignment(V.RedefVNI->id, Other);
2695 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2696 }
2697 }
2698
2699 // An IMPLICIT_DEF writes undef values.
2700 if (DefMI->isImplicitDef()) {
2701 // We normally expect IMPLICIT_DEF values to be live only until the end
2702 // of their block. If the value is really live longer and gets pruned in
2703 // another block, this flag is cleared again.
2704 //
2705 // Clearing the valid lanes is deferred until it is sure this can be
2706 // erased.
2707 V.ErasableImplicitDef = true;
2708 }
2709 }
2710 }
2711
2712 // Find the value in Other that overlaps VNI->def, if any.
2713 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
2714
2715 // It is possible that both values are defined by the same instruction, or
2716 // the values are PHIs defined in the same block. When that happens, the two
2717 // values should be merged into one, but not into any preceding value.
2718 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
2719 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
2720 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ")(static_cast <bool> (SlotIndex::isSameInstr(VNI->def
, OtherVNI->def) && "Broken LRQ") ? void (0) : __assert_fail
("SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && \"Broken LRQ\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2720, __extension__ __PRETTY_FUNCTION__))
;
2721
2722 // One value stays, the other is merged. Keep the earlier one, or the first
2723 // one we see.
2724 if (OtherVNI->def < VNI->def)
2725 Other.computeAssignment(OtherVNI->id, *this);
2726 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
2727 // This is an early-clobber def overlapping a live-in value in the other
2728 // register. Not mergeable.
2729 V.OtherVNI = OtherLRQ.valueIn();
2730 return CR_Impossible;
2731 }
2732 V.OtherVNI = OtherVNI;
2733 Val &OtherV = Other.Vals[OtherVNI->id];
2734 // Keep this value, check for conflicts when analyzing OtherVNI.
2735 if (!OtherV.isAnalyzed())
2736 return CR_Keep;
2737 // Both sides have been analyzed now.
2738 // Allow overlapping PHI values. Any real interference would show up in a
2739 // predecessor, the PHI itself can't introduce any conflicts.
2740 if (VNI->isPHIDef())
2741 return CR_Merge;
2742 if ((V.ValidLanes & OtherV.ValidLanes).any())
2743 // Overlapping lanes can't be resolved.
2744 return CR_Impossible;
2745 else
2746 return CR_Merge;
2747 }
2748
2749 // No simultaneous def. Is Other live at the def?
2750 V.OtherVNI = OtherLRQ.valueIn();
2751 if (!V.OtherVNI)
2752 // No overlap, no conflict.
2753 return CR_Keep;
2754
2755 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ")(static_cast <bool> (!SlotIndex::isSameInstr(VNI->def
, V.OtherVNI->def) && "Broken LRQ") ? void (0) : __assert_fail
("!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && \"Broken LRQ\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2755, __extension__ __PRETTY_FUNCTION__))
;
2756
2757 // We have overlapping values, or possibly a kill of Other.
2758 // Recursively compute assignments up the dominator tree.
2759 Other.computeAssignment(V.OtherVNI->id, *this);
2760 Val &OtherV = Other.Vals[V.OtherVNI->id];
2761
2762 if (OtherV.ErasableImplicitDef) {
2763 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
2764 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
2765 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
2766 // technically.
2767 //
2768 // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
2769 // to erase the IMPLICIT_DEF instruction.
2770 if (DefMI &&
2771 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
2772 LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " <<
V.OtherVNI->def << " extends into " << printMBBReference
(*DefMI->getParent()) << ", keeping it.\n"; } } while
(false)
2773 << " extends into "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " <<
V.OtherVNI->def << " extends into " << printMBBReference
(*DefMI->getParent()) << ", keeping it.\n"; } } while
(false)
2774 << printMBBReference(*DefMI->getParent())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " <<
V.OtherVNI->def << " extends into " << printMBBReference
(*DefMI->getParent()) << ", keeping it.\n"; } } while
(false)
2775 << ", keeping it.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "IMPLICIT_DEF defined at " <<
V.OtherVNI->def << " extends into " << printMBBReference
(*DefMI->getParent()) << ", keeping it.\n"; } } while
(false)
;
2776 OtherV.ErasableImplicitDef = false;
2777 } else {
2778 // We deferred clearing these lanes in case we needed to save them
2779 OtherV.ValidLanes &= ~OtherV.WriteLanes;
2780 }
2781 }
2782
2783 // Allow overlapping PHI values. Any real interference would show up in a
2784 // predecessor, the PHI itself can't introduce any conflicts.
2785 if (VNI->isPHIDef())
2786 return CR_Replace;
2787
2788 // Check for simple erasable conflicts.
2789 if (DefMI->isImplicitDef())
2790 return CR_Erase;
2791
2792 // Include the non-conflict where DefMI is a coalescable copy that kills
2793 // OtherVNI. We still want the copy erased and value numbers merged.
2794 if (CP.isCoalescable(DefMI)) {
2795 // Some of the lanes copied from OtherVNI may be undef, making them undef
2796 // here too.
2797 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2798 return CR_Erase;
2799 }
2800
2801 // This may not be a real conflict if DefMI simply kills Other and defines
2802 // VNI.
2803 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
2804 return CR_Keep;
2805
2806 // Handle the case where VNI and OtherVNI can be proven to be identical:
2807 //
2808 // %other = COPY %ext
2809 // %this = COPY %ext <-- Erase this copy
2810 //
2811 if (DefMI->isFullCopy() && !CP.isPartial() &&
2812 valuesIdentical(VNI, V.OtherVNI, Other)) {
2813 V.Identical = true;
2814 return CR_Erase;
2815 }
2816
2817 // The remaining checks apply to the lanes, which aren't tracked here. This
2818 // was already decided to be OK via the following CR_Replace condition.
2819 // CR_Replace.
2820 if (SubRangeJoin)
2821 return CR_Replace;
2822
2823 // If the lanes written by this instruction were all undef in OtherVNI, it is
2824 // still safe to join the live ranges. This can't be done with a simple value
2825 // mapping, though - OtherVNI will map to multiple values:
2826 //
2827 // 1 %dst:ssub0 = FOO <-- OtherVNI
2828 // 2 %src = BAR <-- VNI
2829 // 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy.
2830 // 4 BAZ killed %dst
2831 // 5 QUUX killed %src
2832 //
2833 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
2834 // handles this complex value mapping.
2835 if ((V.WriteLanes & OtherV.ValidLanes).none())
2836 return CR_Replace;
2837
2838 // If the other live range is killed by DefMI and the live ranges are still
2839 // overlapping, it must be because we're looking at an early clobber def:
2840 //
2841 // %dst<def,early-clobber> = ASM killed %src
2842 //
2843 // In this case, it is illegal to merge the two live ranges since the early
2844 // clobber def would clobber %src before it was read.
2845 if (OtherLRQ.isKill()) {
2846 // This case where the def doesn't overlap the kill is handled above.
2847 assert(VNI->def.isEarlyClobber() &&(static_cast <bool> (VNI->def.isEarlyClobber() &&
"Only early clobber defs can overlap a kill") ? void (0) : __assert_fail
("VNI->def.isEarlyClobber() && \"Only early clobber defs can overlap a kill\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2848, __extension__ __PRETTY_FUNCTION__))
2848 "Only early clobber defs can overlap a kill")(static_cast <bool> (VNI->def.isEarlyClobber() &&
"Only early clobber defs can overlap a kill") ? void (0) : __assert_fail
("VNI->def.isEarlyClobber() && \"Only early clobber defs can overlap a kill\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2848, __extension__ __PRETTY_FUNCTION__))
;
2849 return CR_Impossible;
2850 }
2851
2852 // VNI is clobbering live lanes in OtherVNI, but there is still the
2853 // possibility that no instructions actually read the clobbered lanes.
2854 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2855 // Otherwise Other.RI wouldn't be live here.
2856 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
2857 return CR_Impossible;
2858
2859 // We need to verify that no instructions are reading the clobbered lanes. To
2860 // save compile time, we'll only check that locally. Don't allow the tainted
2861 // value to escape the basic block.
2862 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2863 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2864 return CR_Impossible;
2865
2866 // There are still some things that could go wrong besides clobbered lanes
2867 // being read, for example OtherVNI may be only partially redefined in MBB,
2868 // and some clobbered lanes could escape the block. Save this analysis for
2869 // resolveConflicts() when all values have been mapped. We need to know
2870 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2871 // that now - the recursive analyzeValue() calls must go upwards in the
2872 // dominator tree.
2873 return CR_Unresolved;
2874}
2875
2876void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2877 Val &V = Vals[ValNo];
2878 if (V.isAnalyzed()) {
2879 // Recursion should always move up the dominator tree, so ValNo is not
2880 // supposed to reappear before it has been assigned.
2881 assert(Assignments[ValNo] != -1 && "Bad recursion?")(static_cast <bool> (Assignments[ValNo] != -1 &&
"Bad recursion?") ? void (0) : __assert_fail ("Assignments[ValNo] != -1 && \"Bad recursion?\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2881, __extension__ __PRETTY_FUNCTION__))
;
2882 return;
2883 }
2884 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2885 case CR_Erase:
2886 case CR_Merge:
2887 // Merge this ValNo into OtherVNI.
2888 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.")(static_cast <bool> (V.OtherVNI && "OtherVNI not assigned, can't merge."
) ? void (0) : __assert_fail ("V.OtherVNI && \"OtherVNI not assigned, can't merge.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2888, __extension__ __PRETTY_FUNCTION__))
;
2889 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion")(static_cast <bool> (Other.Vals[V.OtherVNI->id].isAnalyzed
() && "Missing recursion") ? void (0) : __assert_fail
("Other.Vals[V.OtherVNI->id].isAnalyzed() && \"Missing recursion\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2889, __extension__ __PRETTY_FUNCTION__))
;
2890 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2891 LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tmerge " << printReg
(Reg) << ':' << ValNo << '@' << LR.getValNumInfo
(ValNo)->def << " into " << printReg(Other.Reg
) << ':' << V.OtherVNI->id << '@' <<
V.OtherVNI->def << " --> @" << NewVNInfo[Assignments
[ValNo]]->def << '\n'; } } while (false)
2892 << LR.getValNumInfo(ValNo)->def << " into "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tmerge " << printReg
(Reg) << ':' << ValNo << '@' << LR.getValNumInfo
(ValNo)->def << " into " << printReg(Other.Reg
) << ':' << V.OtherVNI->id << '@' <<
V.OtherVNI->def << " --> @" << NewVNInfo[Assignments
[ValNo]]->def << '\n'; } } while (false)
2893 << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tmerge " << printReg
(Reg) << ':' << ValNo << '@' << LR.getValNumInfo
(ValNo)->def << " into " << printReg(Other.Reg
) << ':' << V.OtherVNI->id << '@' <<
V.OtherVNI->def << " --> @" << NewVNInfo[Assignments
[ValNo]]->def << '\n'; } } while (false)
2894 << V.OtherVNI->def << " --> @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tmerge " << printReg
(Reg) << ':' << ValNo << '@' << LR.getValNumInfo
(ValNo)->def << " into " << printReg(Other.Reg
) << ':' << V.OtherVNI->id << '@' <<
V.OtherVNI->def << " --> @" << NewVNInfo[Assignments
[ValNo]]->def << '\n'; } } while (false)
2895 << NewVNInfo[Assignments[ValNo]]->def << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tmerge " << printReg
(Reg) << ':' << ValNo << '@' << LR.getValNumInfo
(ValNo)->def << " into " << printReg(Other.Reg
) << ':' << V.OtherVNI->id << '@' <<
V.OtherVNI->def << " --> @" << NewVNInfo[Assignments
[ValNo]]->def << '\n'; } } while (false)
;
2896 break;
2897 case CR_Replace:
2898 case CR_Unresolved: {
2899 // The other value is going to be pruned if this join is successful.
2900 assert(V.OtherVNI && "OtherVNI not assigned, can't prune")(static_cast <bool> (V.OtherVNI && "OtherVNI not assigned, can't prune"
) ? void (0) : __assert_fail ("V.OtherVNI && \"OtherVNI not assigned, can't prune\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2900, __extension__ __PRETTY_FUNCTION__))
;
2901 Val &OtherV = Other.Vals[V.OtherVNI->id];
2902 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2903 // its lanes.
2904 if (OtherV.ErasableImplicitDef &&
2905 TrackSubRegLiveness &&
2906 (OtherV.WriteLanes & ~V.ValidLanes).any()) {
2907 LLVM_DEBUG(dbgs() << "Cannot erase implicit_def with missing values\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Cannot erase implicit_def with missing values\n"
; } } while (false)
;
2908
2909 OtherV.ErasableImplicitDef = false;
2910 // The valid lanes written by the implicit_def were speculatively cleared
2911 // before, so make this more conservative. It may be better to track this,
2912 // I haven't found a testcase where it matters.
2913 OtherV.ValidLanes = LaneBitmask::getAll();
2914 }
2915
2916 OtherV.Pruned = true;
2917 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2918 }
2919 default:
2920 // This value number needs to go in the final joined live range.
2921 Assignments[ValNo] = NewVNInfo.size();
2922 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2923 break;
2924 }
2925}
2926
2927bool JoinVals::mapValues(JoinVals &Other) {
2928 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2929 computeAssignment(i, Other);
2930 if (Vals[i].Resolution == CR_Impossible) {
2931 LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tinterference at " <<
printReg(Reg) << ':' << i << '@' << LR
.getValNumInfo(i)->def << '\n'; } } while (false)
2932 << '@' << LR.getValNumInfo(i)->def << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tinterference at " <<
printReg(Reg) << ':' << i << '@' << LR
.getValNumInfo(i)->def << '\n'; } } while (false)
;
2933 return false;
2934 }
2935 }
2936 return true;
2937}
2938
2939bool JoinVals::
2940taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2941 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
2942 VNInfo *VNI = LR.getValNumInfo(ValNo);
2943 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2944 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2945
2946 // Scan Other.LR from VNI.def to MBBEnd.
2947 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2948 assert(OtherI != Other.LR.end() && "No conflict?")(static_cast <bool> (OtherI != Other.LR.end() &&
"No conflict?") ? void (0) : __assert_fail ("OtherI != Other.LR.end() && \"No conflict?\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2948, __extension__ __PRETTY_FUNCTION__))
;
2949 do {
2950 // OtherI is pointing to a tainted value. Abort the join if the tainted
2951 // lanes escape the block.
2952 SlotIndex End = OtherI->end;
2953 if (End >= MBBEnd) {
2954 LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\ttaints global " <<
printReg(Other.Reg) << ':' << OtherI->valno->
id << '@' << OtherI->start << '\n'; } } while
(false)
2955 << OtherI->valno->id << '@' << OtherI->start << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\ttaints global " <<
printReg(Other.Reg) << ':' << OtherI->valno->
id << '@' << OtherI->start << '\n'; } } while
(false)
;
2956 return false;
2957 }
2958 LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\ttaints local " << printReg
(Other.Reg) << ':' << OtherI->valno->id <<
'@' << OtherI->start << " to " << End <<
'\n'; } } while (false)
2959 << OtherI->valno->id << '@' << OtherI->start << " to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\ttaints local " << printReg
(Other.Reg) << ':' << OtherI->valno->id <<
'@' << OtherI->start << " to " << End <<
'\n'; } } while (false)
2960 << End << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\ttaints local " << printReg
(Other.Reg) << ':' << OtherI->valno->id <<
'@' << OtherI->start << " to " << End <<
'\n'; } } while (false)
;
2961 // A dead def is not a problem.
2962 if (End.isDead())
2963 break;
2964 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2965
2966 // Check for another def in the MBB.
2967 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2968 break;
2969
2970 // Lanes written by the new def are no longer tainted.
2971 const Val &OV = Other.Vals[OtherI->valno->id];
2972 TaintedLanes &= ~OV.WriteLanes;
2973 if (!OV.RedefVNI)
2974 break;
2975 } while (TaintedLanes.any());
2976 return true;
2977}
2978
2979bool JoinVals::usesLanes(const MachineInstr &MI, Register Reg, unsigned SubIdx,
2980 LaneBitmask Lanes) const {
2981 if (MI.isDebugOrPseudoInstr())
2982 return false;
2983 for (const MachineOperand &MO : MI.operands()) {
2984 if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg)
2985 continue;
2986 if (!MO.readsReg())
2987 continue;
2988 unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
2989 if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
2990 return true;
2991 }
2992 return false;
2993}
2994
2995bool JoinVals::resolveConflicts(JoinVals &Other) {
2996 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2997 Val &V = Vals[i];
2998 assert(V.Resolution != CR_Impossible && "Unresolvable conflict")(static_cast <bool> (V.Resolution != CR_Impossible &&
"Unresolvable conflict") ? void (0) : __assert_fail ("V.Resolution != CR_Impossible && \"Unresolvable conflict\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 2998, __extension__ __PRETTY_FUNCTION__))
;
2999 if (V.Resolution != CR_Unresolved)
3000 continue;
3001 LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tconflict at " << printReg
(Reg) << ':' << i << '@' << LR.getValNumInfo
(i)->def << ' ' << PrintLaneMask(LaneMask) <<
'\n'; } } while (false)
3002 << LR.getValNumInfo(i)->defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tconflict at " << printReg
(Reg) << ':' << i << '@' << LR.getValNumInfo
(i)->def << ' ' << PrintLaneMask(LaneMask) <<
'\n'; } } while (false)
3003 << ' ' << PrintLaneMask(LaneMask) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tconflict at " << printReg
(Reg) << ':' << i << '@' << LR.getValNumInfo
(i)->def << ' ' << PrintLaneMask(LaneMask) <<
'\n'; } } while (false)
;
3004 if (SubRangeJoin)
3005 return false;
3006
3007 ++NumLaneConflicts;
3008 assert(V.OtherVNI && "Inconsistent conflict resolution.")(static_cast <bool> (V.OtherVNI && "Inconsistent conflict resolution."
) ? void (0) : __assert_fail ("V.OtherVNI && \"Inconsistent conflict resolution.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3008, __extension__ __PRETTY_FUNCTION__))
;
3009 VNInfo *VNI = LR.getValNumInfo(i);
3010 const Val &OtherV = Other.Vals[V.OtherVNI->id];
3011
3012 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
3013 // join, those lanes will be tainted with a wrong value. Get the extent of
3014 // the tainted lanes.
3015 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
3016 SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
3017 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
3018 // Tainted lanes would extend beyond the basic block.
3019 return false;
3020
3021 assert(!TaintExtent.empty() && "There should be at least one conflict.")(static_cast <bool> (!TaintExtent.empty() && "There should be at least one conflict."
) ? void (0) : __assert_fail ("!TaintExtent.empty() && \"There should be at least one conflict.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3021, __extension__ __PRETTY_FUNCTION__))
;
3022
3023 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
3024 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3025 MachineBasicBlock::iterator MI = MBB->begin();
3026 if (!VNI->isPHIDef()) {
3027 MI = Indexes->getInstructionFromIndex(VNI->def);
3028 // No need to check the instruction defining VNI for reads.
3029 ++MI;
3030 }
3031 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&(static_cast <bool> (!SlotIndex::isSameInstr(VNI->def
, TaintExtent.front().first) && "Interference ends on VNI->def. Should have been handled earlier"
) ? void (0) : __assert_fail ("!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) && \"Interference ends on VNI->def. Should have been handled earlier\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3032, __extension__ __PRETTY_FUNCTION__))
3032 "Interference ends on VNI->def. Should have been handled earlier")(static_cast <bool> (!SlotIndex::isSameInstr(VNI->def
, TaintExtent.front().first) && "Interference ends on VNI->def. Should have been handled earlier"
) ? void (0) : __assert_fail ("!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) && \"Interference ends on VNI->def. Should have been handled earlier\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3032, __extension__ __PRETTY_FUNCTION__))
;
3033 MachineInstr *LastMI =
3034 Indexes->getInstructionFromIndex(TaintExtent.front().first);
3035 assert(LastMI && "Range must end at a proper instruction")(static_cast <bool> (LastMI && "Range must end at a proper instruction"
) ? void (0) : __assert_fail ("LastMI && \"Range must end at a proper instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3035, __extension__ __PRETTY_FUNCTION__))
;
3036 unsigned TaintNum = 0;
3037 while (true) {
3038 assert(MI != MBB->end() && "Bad LastMI")(static_cast <bool> (MI != MBB->end() && "Bad LastMI"
) ? void (0) : __assert_fail ("MI != MBB->end() && \"Bad LastMI\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3038, __extension__ __PRETTY_FUNCTION__))
;
3039 if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
3040 LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\ttainted lanes used by: "
<< *MI; } } while (false)
;
3041 return false;
3042 }
3043 // LastMI is the last instruction to use the current value.
3044 if (&*MI == LastMI) {
3045 if (++TaintNum == TaintExtent.size())
3046 break;
3047 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
3048 assert(LastMI && "Range must end at a proper instruction")(static_cast <bool> (LastMI && "Range must end at a proper instruction"
) ? void (0) : __assert_fail ("LastMI && \"Range must end at a proper instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3048, __extension__ __PRETTY_FUNCTION__))
;
3049 TaintedLanes = TaintExtent[TaintNum].second;
3050 }
3051 ++MI;
3052 }
3053
3054 // The tainted lanes are unused.
3055 V.Resolution = CR_Replace;
3056 ++NumLaneResolves;
3057 }
3058 return true;
3059}
3060
3061bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
3062 Val &V = Vals[ValNo];
3063 if (V.Pruned || V.PrunedComputed)
3064 return V.Pruned;
3065
3066 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
3067 return V.Pruned;
3068
3069 // Follow copies up the dominator tree and check if any intermediate value
3070 // has been pruned.
3071 V.PrunedComputed = true;
3072 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
3073 return V.Pruned;
3074}
3075
3076void JoinVals::pruneValues(JoinVals &Other,
3077 SmallVectorImpl<SlotIndex> &EndPoints,
3078 bool changeInstrs) {
3079 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3080 SlotIndex Def = LR.getValNumInfo(i)->def;
3081 switch (Vals[i].Resolution) {
3082 case CR_Keep:
3083 break;
3084 case CR_Replace: {
3085 // This value takes precedence over the value in Other.LR.
3086 LIS->pruneValue(Other.LR, Def, &EndPoints);
3087 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
3088 // instructions are only inserted to provide a live-out value for PHI
3089 // predecessors, so the instruction should simply go away once its value
3090 // has been replaced.
3091 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
3092 bool EraseImpDef = OtherV.ErasableImplicitDef &&
3093 OtherV.Resolution == CR_Keep;
3094 if (!Def.isBlock()) {
3095 if (changeInstrs) {
3096 // Remove <def,read-undef> flags. This def is now a partial redef.
3097 // Also remove dead flags since the joined live range will
3098 // continue past this instruction.
3099 for (MachineOperand &MO :
3100 Indexes->getInstructionFromIndex(Def)->operands()) {
3101 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
3102 if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
3103 MO.setIsUndef(false);
3104 MO.setIsDead(false);
3105 }
3106 }
3107 }
3108 // This value will reach instructions below, but we need to make sure
3109 // the live range also reaches the instruction at Def.
3110 if (!EraseImpDef)
3111 EndPoints.push_back(Def);
3112 }
3113 LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tpruned " << printReg
(Other.Reg) << " at " << Def << ": " <<
Other.LR << '\n'; } } while (false)
3114 << ": " << Other.LR << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tpruned " << printReg
(Other.Reg) << " at " << Def << ": " <<
Other.LR << '\n'; } } while (false)
;
3115 break;
3116 }
3117 case CR_Erase:
3118 case CR_Merge:
3119 if (isPrunedValue(i, Other)) {
3120 // This value is ultimately a copy of a pruned value in LR or Other.LR.
3121 // We can no longer trust the value mapping computed by
3122 // computeAssignment(), the value that was originally copied could have
3123 // been replaced.
3124 LIS->pruneValue(LR, Def, &EndPoints);
3125 LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tpruned all of " <<
printReg(Reg) << " at " << Def << ": " <<
LR << '\n'; } } while (false)
3126 << Def << ": " << LR << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tpruned all of " <<
printReg(Reg) << " at " << Def << ": " <<
LR << '\n'; } } while (false)
;
3127 }
3128 break;
3129 case CR_Unresolved:
3130 case CR_Impossible:
3131 llvm_unreachable("Unresolved conflicts")::llvm::llvm_unreachable_internal("Unresolved conflicts", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3131)
;
3132 }
3133 }
3134}
3135
3136// Check if the segment consists of a copied live-through value (i.e. the copy
3137// in the block only extended the liveness, of an undef value which we may need
3138// to handle).
3139static bool isLiveThrough(const LiveQueryResult Q) {
3140 return Q.valueIn() && Q.valueIn()->isPHIDef() && Q.valueIn() == Q.valueOut();
3141}
3142
3143/// Consider the following situation when coalescing the copy between
3144/// %31 and %45 at 800. (The vertical lines represent live range segments.)
3145///
3146/// Main range Subrange 0004 (sub2)
3147/// %31 %45 %31 %45
3148/// 544 %45 = COPY %28 + +
3149/// | v1 | v1
3150/// 560B bb.1: + +
3151/// 624 = %45.sub2 | v2 | v2
3152/// 800 %31 = COPY %45 + + + +
3153/// | v0 | v0
3154/// 816 %31.sub1 = ... + |
3155/// 880 %30 = COPY %31 | v1 +
3156/// 928 %45 = COPY %30 | + +
3157/// | | v0 | v0 <--+
3158/// 992B ; backedge -> bb.1 | + + |
3159/// 1040 = %31.sub0 + |
3160/// This value must remain
3161/// live-out!
3162///
3163/// Assuming that %31 is coalesced into %45, the copy at 928 becomes
3164/// redundant, since it copies the value from %45 back into it. The
3165/// conflict resolution for the main range determines that %45.v0 is
3166/// to be erased, which is ok since %31.v1 is identical to it.
3167/// The problem happens with the subrange for sub2: it has to be live
3168/// on exit from the block, but since 928 was actually a point of
3169/// definition of %45.sub2, %45.sub2 was not live immediately prior
3170/// to that definition. As a result, when 928 was erased, the value v0
3171/// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
3172/// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
3173/// providing an incorrect value to the use at 624.
3174///
3175/// Since the main-range values %31.v1 and %45.v0 were proved to be
3176/// identical, the corresponding values in subranges must also be the
3177/// same. A redundant copy is removed because it's not needed, and not
3178/// because it copied an undefined value, so any liveness that originated
3179/// from that copy cannot disappear. When pruning a value that started
3180/// at the removed copy, the corresponding identical value must be
3181/// extended to replace it.
3182void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
3183 // Look for values being erased.
3184 bool DidPrune = false;
3185 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3186 Val &V = Vals[i];
3187 // We should trigger in all cases in which eraseInstrs() does something.
3188 // match what eraseInstrs() is doing, print a message so
3189 if (V.Resolution != CR_Erase &&
3190 (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
3191 continue;
3192
3193 // Check subranges at the point where the copy will be removed.
3194 SlotIndex Def = LR.getValNumInfo(i)->def;
3195 SlotIndex OtherDef;
3196 if (V.Identical)
3197 OtherDef = V.OtherVNI->def;
3198
3199 // Print message so mismatches with eraseInstrs() can be diagnosed.
3200 LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tExpecting instruction removal at "
<< Def << '\n'; } } while (false)
3201 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tExpecting instruction removal at "
<< Def << '\n'; } } while (false)
;
3202 for (LiveInterval::SubRange &S : LI.subranges()) {
3203 LiveQueryResult Q = S.Query(Def);
3204
3205 // If a subrange starts at the copy then an undefined value has been
3206 // copied and we must remove that subrange value as well.
3207 VNInfo *ValueOut = Q.valueOutOrDead();
3208 if (ValueOut != nullptr && (Q.valueIn() == nullptr ||
3209 (V.Identical && V.Resolution == CR_Erase &&
3210 ValueOut->def == Def))) {
3211 LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tPrune sublane " <<
PrintLaneMask(S.LaneMask) << " at " << Def <<
"\n"; } } while (false)
3212 << " at " << Def << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tPrune sublane " <<
PrintLaneMask(S.LaneMask) << " at " << Def <<
"\n"; } } while (false)
;
3213 SmallVector<SlotIndex,8> EndPoints;
3214 LIS->pruneValue(S, Def, &EndPoints);
3215 DidPrune = true;
3216 // Mark value number as unused.
3217 ValueOut->markUnused();
3218
3219 if (V.Identical && S.Query(OtherDef).valueOutOrDead()) {
3220 // If V is identical to V.OtherVNI (and S was live at OtherDef),
3221 // then we can't simply prune V from S. V needs to be replaced
3222 // with V.OtherVNI.
3223 LIS->extendToIndices(S, EndPoints);
3224 }
3225
3226 // We may need to eliminate the subrange if the copy introduced a live
3227 // out undef value.
3228 if (ValueOut->isPHIDef())
3229 ShrinkMask |= S.LaneMask;
3230 continue;
3231 }
3232
3233 // If a subrange ends at the copy, then a value was copied but only
3234 // partially used later. Shrink the subregister range appropriately.
3235 //
3236 // Ultimately this calls shrinkToUses, so assuming ShrinkMask is
3237 // conservatively correct.
3238 if ((Q.valueIn() != nullptr && Q.valueOut() == nullptr) ||
3239 (V.Resolution == CR_Erase && isLiveThrough(Q))) {
3240 LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tDead uses at sublane " <<
PrintLaneMask(S.LaneMask) << " at " << Def <<
"\n"; } } while (false)
3241 << PrintLaneMask(S.LaneMask) << " at " << Defdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tDead uses at sublane " <<
PrintLaneMask(S.LaneMask) << " at " << Def <<
"\n"; } } while (false)
3242 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tDead uses at sublane " <<
PrintLaneMask(S.LaneMask) << " at " << Def <<
"\n"; } } while (false)
;
3243 ShrinkMask |= S.LaneMask;
3244 }
3245 }
3246 }
3247 if (DidPrune)
3248 LI.removeEmptySubRanges();
3249}
3250
3251/// Check if any of the subranges of @p LI contain a definition at @p Def.
3252static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) {
3253 for (LiveInterval::SubRange &SR : LI.subranges()) {
3254 if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
3255 if (VNI->def == Def)
3256 return true;
3257 }
3258 return false;
3259}
3260
3261void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
3262 assert(&static_cast<LiveRange&>(LI) == &LR)(static_cast <bool> (&static_cast<LiveRange&
>(LI) == &LR) ? void (0) : __assert_fail ("&static_cast<LiveRange&>(LI) == &LR"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3262, __extension__ __PRETTY_FUNCTION__))
;
3263
3264 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3265 if (Vals[i].Resolution != CR_Keep)
3266 continue;
3267 VNInfo *VNI = LR.getValNumInfo(i);
3268 if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
3269 continue;
3270 Vals[i].Pruned = true;
3271 ShrinkMainRange = true;
3272 }
3273}
3274
3275void JoinVals::removeImplicitDefs() {
3276 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3277 Val &V = Vals[i];
3278 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
3279 continue;
3280
3281 VNInfo *VNI = LR.getValNumInfo(i);
3282 VNI->markUnused();
3283 LR.removeValNo(VNI);
3284 }
3285}
3286
3287void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
3288 SmallVectorImpl<Register> &ShrinkRegs,
3289 LiveInterval *LI) {
3290 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3291 // Get the def location before markUnused() below invalidates it.
3292 VNInfo *VNI = LR.getValNumInfo(i);
3293 SlotIndex Def = VNI->def;
3294 switch (Vals[i].Resolution) {
3295 case CR_Keep: {
3296 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
3297 // longer. The IMPLICIT_DEF instructions are only inserted by
3298 // PHIElimination to guarantee that all PHI predecessors have a value.
3299 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
3300 break;
3301 // Remove value number i from LR.
3302 // For intervals with subranges, removing a segment from the main range
3303 // may require extending the previous segment: for each definition of
3304 // a subregister, there will be a corresponding def in the main range.
3305 // That def may fall in the middle of a segment from another subrange.
3306 // In such cases, removing this def from the main range must be
3307 // complemented by extending the main range to account for the liveness
3308 // of the other subrange.
3309 // The new end point of the main range segment to be extended.
3310 SlotIndex NewEnd;
3311 if (LI != nullptr) {
3312 LiveRange::iterator I = LR.FindSegmentContaining(Def);
3313 assert(I != LR.end())(static_cast <bool> (I != LR.end()) ? void (0) : __assert_fail
("I != LR.end()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3313, __extension__ __PRETTY_FUNCTION__))
;
3314 // Do not extend beyond the end of the segment being removed.
3315 // The segment may have been pruned in preparation for joining
3316 // live ranges.
3317 NewEnd = I->end;
3318 }
3319
3320 LR.removeValNo(VNI);
3321 // Note that this VNInfo is reused and still referenced in NewVNInfo,
3322 // make it appear like an unused value number.
3323 VNI->markUnused();
3324
3325 if (LI != nullptr && LI->hasSubRanges()) {
3326 assert(static_cast<LiveRange*>(LI) == &LR)(static_cast <bool> (static_cast<LiveRange*>(LI) ==
&LR) ? void (0) : __assert_fail ("static_cast<LiveRange*>(LI) == &LR"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3326, __extension__ __PRETTY_FUNCTION__))
;
3327 // Determine the end point based on the subrange information:
3328 // minimum of (earliest def of next segment,
3329 // latest end point of containing segment)
3330 SlotIndex ED, LE;
3331 for (LiveInterval::SubRange &SR : LI->subranges()) {
3332 LiveRange::iterator I = SR.find(Def);
3333 if (I == SR.end())
3334 continue;
3335 if (I->start > Def)
3336 ED = ED.isValid() ? std::min(ED, I->start) : I->start;
3337 else
3338 LE = LE.isValid() ? std::max(LE, I->end) : I->end;
3339 }
3340 if (LE.isValid())
3341 NewEnd = std::min(NewEnd, LE);
3342 if (ED.isValid())
3343 NewEnd = std::min(NewEnd, ED);
3344
3345 // We only want to do the extension if there was a subrange that
3346 // was live across Def.
3347 if (LE.isValid()) {
3348 LiveRange::iterator S = LR.find(Def);
3349 if (S != LR.begin())
3350 std::prev(S)->end = NewEnd;
3351 }
3352 }
3353 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tremoved " << i <<
'@' << Def << ": " << LR << '\n'; if
(LI != nullptr) dbgs() << "\t\t LHS = " << *LI <<
'\n'; }; } } while (false)
3354 dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tremoved " << i <<
'@' << Def << ": " << LR << '\n'; if
(LI != nullptr) dbgs() << "\t\t LHS = " << *LI <<
'\n'; }; } } while (false)
3355 if (LI != nullptr)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tremoved " << i <<
'@' << Def << ": " << LR << '\n'; if
(LI != nullptr) dbgs() << "\t\t LHS = " << *LI <<
'\n'; }; } } while (false)
3356 dbgs() << "\t\t LHS = " << *LI << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tremoved " << i <<
'@' << Def << ": " << LR << '\n'; if
(LI != nullptr) dbgs() << "\t\t LHS = " << *LI <<
'\n'; }; } } while (false)
3357 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\tremoved " << i <<
'@' << Def << ": " << LR << '\n'; if
(LI != nullptr) dbgs() << "\t\t LHS = " << *LI <<
'\n'; }; } } while (false)
;
3358 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3359 }
3360
3361 case CR_Erase: {
3362 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
3363 assert(MI && "No instruction to erase")(static_cast <bool> (MI && "No instruction to erase"
) ? void (0) : __assert_fail ("MI && \"No instruction to erase\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3363, __extension__ __PRETTY_FUNCTION__))
;
3364 if (MI->isCopy()) {
3365 Register Reg = MI->getOperand(1).getReg();
3366 if (Register::isVirtualRegister(Reg) && Reg != CP.getSrcReg() &&
3367 Reg != CP.getDstReg())
3368 ShrinkRegs.push_back(Reg);
3369 }
3370 ErasedInstrs.insert(MI);
3371 LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\terased:\t" << Def <<
'\t' << *MI; } } while (false)
;
3372 LIS->RemoveMachineInstrFromMaps(*MI);
3373 MI->eraseFromParent();
3374 break;
3375 }
3376 default:
3377 break;
3378 }
3379 }
3380}
3381
3382void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
3383 LaneBitmask LaneMask,
3384 const CoalescerPair &CP) {
3385 SmallVector<VNInfo*, 16> NewVNInfo;
3386 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
3387 NewVNInfo, CP, LIS, TRI, true, true);
3388 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
3389 NewVNInfo, CP, LIS, TRI, true, true);
3390
3391 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
3392 // We should be able to resolve all conflicts here as we could successfully do
3393 // it on the mainrange already. There is however a problem when multiple
3394 // ranges get mapped to the "overflow" lane mask bit which creates unexpected
3395 // interferences.
3396 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
3397 // We already determined that it is legal to merge the intervals, so this
3398 // should never fail.
3399 llvm_unreachable("*** Couldn't join subrange!\n")::llvm::llvm_unreachable_internal("*** Couldn't join subrange!\n"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3399)
;
3400 }
3401 if (!LHSVals.resolveConflicts(RHSVals) ||
3402 !RHSVals.resolveConflicts(LHSVals)) {
3403 // We already determined that it is legal to merge the intervals, so this
3404 // should never fail.
3405 llvm_unreachable("*** Couldn't join subrange!\n")::llvm::llvm_unreachable_internal("*** Couldn't join subrange!\n"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3405)
;
3406 }
3407
3408 // The merging algorithm in LiveInterval::join() can't handle conflicting
3409 // value mappings, so we need to remove any live ranges that overlap a
3410 // CR_Replace resolution. Collect a set of end points that can be used to
3411 // restore the live range after joining.
3412 SmallVector<SlotIndex, 8> EndPoints;
3413 LHSVals.pruneValues(RHSVals, EndPoints, false);
3414 RHSVals.pruneValues(LHSVals, EndPoints, false);
3415
3416 LHSVals.removeImplicitDefs();
3417 RHSVals.removeImplicitDefs();
3418
3419 LRange.verify();
3420 RRange.verify();
3421
3422 // Join RRange into LHS.
3423 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
3424 NewVNInfo);
3425
3426 LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tjoined lanes: " <<
PrintLaneMask(LaneMask) << ' ' << LRange <<
"\n"; } } while (false)
3427 << ' ' << LRange << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tjoined lanes: " <<
PrintLaneMask(LaneMask) << ' ' << LRange <<
"\n"; } } while (false)
;
3428 if (EndPoints.empty())
3429 return;
3430
3431 // Recompute the parts of the live range we had to remove because of
3432 // CR_Replace conflicts.
3433 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3434 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3435 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3436 dbgs() << EndPoints[i];do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3437 if (i != n-1)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3438 dbgs() << ',';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3439 }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3440 dbgs() << ": " << LRange << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
3441 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LRange << '\n'; }; } } while (false)
;
3442 LIS->extendToIndices(LRange, EndPoints);
3443}
3444
3445void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
3446 const LiveRange &ToMerge,
3447 LaneBitmask LaneMask,
3448 CoalescerPair &CP,
3449 unsigned ComposeSubRegIdx) {
3450 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
3451 LI.refineSubRanges(
3452 Allocator, LaneMask,
3453 [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) {
3454 if (SR.empty()) {
3455 SR.assign(ToMerge, Allocator);
3456 } else {
3457 // joinSubRegRange() destroys the merged range, so we need a copy.
3458 LiveRange RangeCopy(ToMerge, Allocator);
3459 joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
3460 }
3461 },
3462 *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx);
3463}
3464
3465bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) {
3466 if (LI.valnos.size() < LargeIntervalSizeThreshold)
3467 return false;
3468 auto &Counter = LargeLIVisitCounter[LI.reg()];
3469 if (Counter < LargeIntervalFreqThreshold) {
3470 Counter++;
3471 return false;
3472 }
3473 return true;
3474}
3475
3476bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
3477 SmallVector<VNInfo*, 16> NewVNInfo;
3478 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
3479 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
3480 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
3481 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
3482 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3483 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
3484 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3485
3486 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tRHS = " << RHS <<
"\n\t\tLHS = " << LHS << '\n'; } } while (false)
;
3487
3488 if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS))
3489 return false;
3490
3491 // First compute NewVNInfo and the simple value mappings.
3492 // Detect impossible conflicts early.
3493 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
3494 return false;
3495
3496 // Some conflicts can only be resolved after all values have been mapped.
3497 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
3498 return false;
3499
3500 // All clear, the live ranges can be merged.
3501 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
3502 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
3503
3504 // Transform lanemasks from the LHS to masks in the coalesced register and
3505 // create initial subranges if necessary.
3506 unsigned DstIdx = CP.getDstIdx();
3507 if (!LHS.hasSubRanges()) {
3508 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
3509 : TRI->getSubRegIndexLaneMask(DstIdx);
3510 // LHS must support subregs or we wouldn't be in this codepath.
3511 assert(Mask.any())(static_cast <bool> (Mask.any()) ? void (0) : __assert_fail
("Mask.any()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3511, __extension__ __PRETTY_FUNCTION__))
;
3512 LHS.createSubRangeFrom(Allocator, Mask, LHS);
3513 } else if (DstIdx != 0) {
3514 // Transform LHS lanemasks to new register class if necessary.
3515 for (LiveInterval::SubRange &R : LHS.subranges()) {
3516 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
3517 R.LaneMask = Mask;
3518 }
3519 }
3520 LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHSdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tLHST = " << printReg
(CP.getDstReg()) << ' ' << LHS << '\n'; } }
while (false)
3521 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t\tLHST = " << printReg
(CP.getDstReg()) << ' ' << LHS << '\n'; } }
while (false)
;
3522
3523 // Determine lanemasks of RHS in the coalesced register and merge subranges.
3524 unsigned SrcIdx = CP.getSrcIdx();
3525 if (!RHS.hasSubRanges()) {
3526 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
3527 : TRI->getSubRegIndexLaneMask(SrcIdx);
3528 mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx);
3529 } else {
3530 // Pair up subranges and merge.
3531 for (LiveInterval::SubRange &R : RHS.subranges()) {
3532 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3533 mergeSubRangeInto(LHS, R, Mask, CP, DstIdx);
3534 }
3535 }
3536 LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tJoined SubRanges " <<
LHS << "\n"; } } while (false)
;
3537
3538 // Pruning implicit defs from subranges may result in the main range
3539 // having stale segments.
3540 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3541
3542 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
3543 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
3544 }
3545
3546 // The merging algorithm in LiveInterval::join() can't handle conflicting
3547 // value mappings, so we need to remove any live ranges that overlap a
3548 // CR_Replace resolution. Collect a set of end points that can be used to
3549 // restore the live range after joining.
3550 SmallVector<SlotIndex, 8> EndPoints;
3551 LHSVals.pruneValues(RHSVals, EndPoints, true);
3552 RHSVals.pruneValues(LHSVals, EndPoints, true);
3553
3554 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
3555 // registers to require trimming.
3556 SmallVector<Register, 8> ShrinkRegs;
3557 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3558 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3559 while (!ShrinkRegs.empty())
3560 shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
3561
3562 // Scan and mark undef any DBG_VALUEs that would refer to a different value.
3563 checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals);
3564
3565 // If the RHS covers any PHI locations that were tracked for debug-info, we
3566 // must update tracking information to reflect the join.
3567 auto RegIt = RegToPHIIdx.find(CP.getSrcReg());
3568 if (RegIt != RegToPHIIdx.end()) {
3569 // Iterate over all the debug instruction numbers assigned this register.
3570 for (unsigned InstID : RegIt->second) {
3571 auto PHIIt = PHIValToPos.find(InstID);
3572 assert(PHIIt != PHIValToPos.end())(static_cast <bool> (PHIIt != PHIValToPos.end()) ? void
(0) : __assert_fail ("PHIIt != PHIValToPos.end()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3572, __extension__ __PRETTY_FUNCTION__))
;
3573 const SlotIndex &SI = PHIIt->second.SI;
3574
3575 // Does the RHS cover the position of this PHI?
3576 auto LII = RHS.find(SI);
3577 if (LII == RHS.end() || LII->start > SI)
3578 continue;
3579
3580 // Accept two kinds of subregister movement:
3581 // * When we merge from one register class into a larger register:
3582 // %1:gr16 = some-inst
3583 // ->
3584 // %2:gr32.sub_16bit = some-inst
3585 // * When the PHI is already in a subregister, and the larger class
3586 // is coalesced:
3587 // %2:gr32.sub_16bit = some-inst
3588 // %3:gr32 = COPY %2
3589 // ->
3590 // %3:gr32.sub_16bit = some-inst
3591 // Test for subregister move:
3592 if (CP.getSrcIdx() != 0 || CP.getDstIdx() != 0)
3593 // If we're moving between different subregisters, ignore this join.
3594 // The PHI will not get a location, dropping variable locations.
3595 if (PHIIt->second.SubReg && PHIIt->second.SubReg != CP.getSrcIdx())
3596 continue;
3597
3598 // Update our tracking of where the PHI is.
3599 PHIIt->second.Reg = CP.getDstReg();
3600
3601 // If we merge into a sub-register of a larger class (test above),
3602 // update SubReg.
3603 if (CP.getSrcIdx() != 0)
3604 PHIIt->second.SubReg = CP.getSrcIdx();
3605 }
3606
3607 // Rebuild the register index in RegToPHIIdx to account for PHIs tracking
3608 // different VRegs now. Copy old collection of debug instruction numbers and
3609 // erase the old one:
3610 auto InstrNums = RegIt->second;
3611 RegToPHIIdx.erase(RegIt);
3612
3613 // There might already be PHIs being tracked in the destination VReg. Insert
3614 // into an existing tracking collection, or insert a new one.
3615 RegIt = RegToPHIIdx.find(CP.getDstReg());
3616 if (RegIt != RegToPHIIdx.end())
3617 RegIt->second.insert(RegIt->second.end(), InstrNums.begin(),
3618 InstrNums.end());
3619 else
3620 RegToPHIIdx.insert({CP.getDstReg(), InstrNums});
3621 }
3622
3623 // Join RHS into LHS.
3624 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3625
3626 // Kill flags are going to be wrong if the live ranges were overlapping.
3627 // Eventually, we should simply clear all kill flags when computing live
3628 // ranges. They are reinserted after register allocation.
3629 MRI->clearKillFlags(LHS.reg());
3630 MRI->clearKillFlags(RHS.reg());
3631
3632 if (!EndPoints.empty()) {
3633 // Recompute the parts of the live range we had to remove because of
3634 // CR_Replace conflicts.
3635 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3636 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3637 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3638 dbgs() << EndPoints[i];do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3639 if (i != n-1)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3640 dbgs() << ',';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3641 }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3642 dbgs() << ": " << LHS << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
3643 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\t\trestoring liveness to "
<< EndPoints.size() << " points: "; for (unsigned
i = 0, n = EndPoints.size(); i != n; ++i) { dbgs() << EndPoints
[i]; if (i != n-1) dbgs() << ','; } dbgs() << ": "
<< LHS << '\n'; }; } } while (false)
;
3644 LIS->extendToIndices((LiveRange&)LHS, EndPoints);
3645 }
3646
3647 return true;
3648}
3649
3650bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
3651 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
3652}
3653
3654void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF)
3655{
3656 const SlotIndexes &Slots = *LIS->getSlotIndexes();
3657 SmallVector<MachineInstr *, 8> ToInsert;
3658
3659 // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
3660 // vreg => DbgValueLoc map.
3661 auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) {
3662 for (auto *X : ToInsert) {
3663 for (auto Op : X->debug_operands()) {
3664 if (Op.isReg() && Op.getReg().isVirtual())
3665 DbgVRegToValues[Op.getReg()].push_back({Slot, X});
3666 }
3667 }
3668
3669 ToInsert.clear();
3670 };
3671
3672 // Iterate over all instructions, collecting them into the ToInsert vector.
3673 // Once a non-debug instruction is found, record the slot index of the
3674 // collected DBG_VALUEs.
3675 for (auto &MBB : MF) {
3676 SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB);
3677
3678 for (auto &MI : MBB) {
3679 if (MI.isDebugValue()) {
3680 if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
3681 return MO.isReg() && MO.getReg().isVirtual();
3682 }))
3683 ToInsert.push_back(&MI);
3684 } else if (!MI.isDebugOrPseudoInstr()) {
3685 CurrentSlot = Slots.getInstructionIndex(MI);
3686 CloseNewDVRange(CurrentSlot);
3687 }
3688 }
3689
3690 // Close range of DBG_VALUEs at the end of blocks.
3691 CloseNewDVRange(Slots.getMBBEndIdx(&MBB));
3692 }
3693
3694 // Sort all DBG_VALUEs we've seen by slot number.
3695 for (auto &Pair : DbgVRegToValues)
3696 llvm::sort(Pair.second);
3697}
3698
3699void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP,
3700 LiveRange &LHS,
3701 JoinVals &LHSVals,
3702 LiveRange &RHS,
3703 JoinVals &RHSVals) {
3704 auto ScanForDstReg = [&](Register Reg) {
3705 checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals);
3706 };
3707
3708 auto ScanForSrcReg = [&](Register Reg) {
3709 checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals);
3710 };
3711
3712 // Scan for potentially unsound DBG_VALUEs: examine first the register number
3713 // Reg, and then any other vregs that may have been merged into it.
3714 auto PerformScan = [this](Register Reg, std::function<void(Register)> Func) {
3715 Func(Reg);
3716 if (DbgMergedVRegNums.count(Reg))
3717 for (Register X : DbgMergedVRegNums[Reg])
3718 Func(X);
3719 };
3720
3721 // Scan for unsound updates of both the source and destination register.
3722 PerformScan(CP.getSrcReg(), ScanForSrcReg);
3723 PerformScan(CP.getDstReg(), ScanForDstReg);
3724}
3725
3726void RegisterCoalescer::checkMergingChangesDbgValuesImpl(Register Reg,
3727 LiveRange &OtherLR,
3728 LiveRange &RegLR,
3729 JoinVals &RegVals) {
3730 // Are there any DBG_VALUEs to examine?
3731 auto VRegMapIt = DbgVRegToValues.find(Reg);
3732 if (VRegMapIt == DbgVRegToValues.end())
3733 return;
3734
3735 auto &DbgValueSet = VRegMapIt->second;
3736 auto DbgValueSetIt = DbgValueSet.begin();
3737 auto SegmentIt = OtherLR.begin();
3738
3739 bool LastUndefResult = false;
3740 SlotIndex LastUndefIdx;
3741
3742 // If the "Other" register is live at a slot Idx, test whether Reg can
3743 // safely be merged with it, or should be marked undef.
3744 auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult,
3745 &LastUndefIdx](SlotIndex Idx) -> bool {
3746 // Our worst-case performance typically happens with asan, causing very
3747 // many DBG_VALUEs of the same location. Cache a copy of the most recent
3748 // result for this edge-case.
3749 if (LastUndefIdx == Idx)
3750 return LastUndefResult;
3751
3752 // If the other range was live, and Reg's was not, the register coalescer
3753 // will not have tried to resolve any conflicts. We don't know whether
3754 // the DBG_VALUE will refer to the same value number, so it must be made
3755 // undef.
3756 auto OtherIt = RegLR.find(Idx);
3757 if (OtherIt == RegLR.end())
3758 return true;
3759
3760 // Both the registers were live: examine the conflict resolution record for
3761 // the value number Reg refers to. CR_Keep meant that this value number
3762 // "won" and the merged register definitely refers to that value. CR_Erase
3763 // means the value number was a redundant copy of the other value, which
3764 // was coalesced and Reg deleted. It's safe to refer to the other register
3765 // (which will be the source of the copy).
3766 auto Resolution = RegVals.getResolution(OtherIt->valno->id);
3767 LastUndefResult = Resolution != JoinVals::CR_Keep &&
3768 Resolution != JoinVals::CR_Erase;
3769 LastUndefIdx = Idx;
3770 return LastUndefResult;
3771 };
3772
3773 // Iterate over both the live-range of the "Other" register, and the set of
3774 // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest
3775 // slot index. This relies on the DbgValueSet being ordered.
3776 while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) {
3777 if (DbgValueSetIt->first < SegmentIt->end) {
3778 // "Other" is live and there is a DBG_VALUE of Reg: test if we should
3779 // set it undef.
3780 if (DbgValueSetIt->first >= SegmentIt->start) {
3781 bool HasReg = DbgValueSetIt->second->hasDebugOperandForReg(Reg);
3782 bool ShouldUndefReg = ShouldUndef(DbgValueSetIt->first);
3783 if (HasReg && ShouldUndefReg) {
3784 // Mark undef, erase record of this DBG_VALUE to avoid revisiting.
3785 DbgValueSetIt->second->setDebugValueUndef();
3786 continue;
3787 }
3788 }
3789 ++DbgValueSetIt;
3790 } else {
3791 ++SegmentIt;
3792 }
3793 }
3794}
3795
3796namespace {
3797
3798/// Information concerning MBB coalescing priority.
3799struct MBBPriorityInfo {
3800 MachineBasicBlock *MBB;
3801 unsigned Depth;
3802 bool IsSplit;
3803
3804 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
3805 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
3806};
3807
3808} // end anonymous namespace
3809
3810/// C-style comparator that sorts first based on the loop depth of the basic
3811/// block (the unsigned), and then on the MBB number.
3812///
3813/// EnableGlobalCopies assumes that the primary sort key is loop depth.
3814static int compareMBBPriority(const MBBPriorityInfo *LHS,
3815 const MBBPriorityInfo *RHS) {
3816 // Deeper loops first
3817 if (LHS->Depth != RHS->Depth)
3818 return LHS->Depth > RHS->Depth ? -1 : 1;
3819
3820 // Try to unsplit critical edges next.
3821 if (LHS->IsSplit != RHS->IsSplit)
3822 return LHS->IsSplit ? -1 : 1;
3823
3824 // Prefer blocks that are more connected in the CFG. This takes care of
3825 // the most difficult copies first while intervals are short.
3826 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
3827 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
3828 if (cl != cr)
3829 return cl > cr ? -1 : 1;
3830
3831 // As a last resort, sort by block number.
3832 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
3833}
3834
3835/// \returns true if the given copy uses or defines a local live range.
3836static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
3837 if (!Copy->isCopy())
3838 return false;
3839
3840 if (Copy->getOperand(1).isUndef())
3841 return false;
3842
3843 Register SrcReg = Copy->getOperand(1).getReg();
3844 Register DstReg = Copy->getOperand(0).getReg();
3845 if (Register::isPhysicalRegister(SrcReg) ||
3846 Register::isPhysicalRegister(DstReg))
3847 return false;
3848
3849 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
3850 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
3851}
3852
3853void RegisterCoalescer::lateLiveIntervalUpdate() {
3854 for (Register reg : ToBeUpdated) {
3855 if (!LIS->hasInterval(reg))
3856 continue;
3857 LiveInterval &LI = LIS->getInterval(reg);
3858 shrinkToUses(&LI, &DeadDefs);
3859 if (!DeadDefs.empty())
3860 eliminateDeadDefs();
3861 }
3862 ToBeUpdated.clear();
3863}
3864
3865bool RegisterCoalescer::
3866copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
3867 bool Progress = false;
3868 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
3869 if (!CurrList[i])
3870 continue;
3871 // Skip instruction pointers that have already been erased, for example by
3872 // dead code elimination.
3873 if (ErasedInstrs.count(CurrList[i])) {
3874 CurrList[i] = nullptr;
3875 continue;
3876 }
3877 bool Again = false;
3878 bool Success = joinCopy(CurrList[i], Again);
3879 Progress |= Success;
3880 if (Success || !Again)
3881 CurrList[i] = nullptr;
3882 }
3883 return Progress;
3884}
3885
3886/// Check if DstReg is a terminal node.
3887/// I.e., it does not have any affinity other than \p Copy.
3888static bool isTerminalReg(Register DstReg, const MachineInstr &Copy,
3889 const MachineRegisterInfo *MRI) {
3890 assert(Copy.isCopyLike())(static_cast <bool> (Copy.isCopyLike()) ? void (0) : __assert_fail
("Copy.isCopyLike()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3890, __extension__ __PRETTY_FUNCTION__))
;
3891 // Check if the destination of this copy as any other affinity.
3892 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
3893 if (&MI != &Copy && MI.isCopyLike())
3894 return false;
3895 return true;
3896}
3897
3898bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
3899 assert(Copy.isCopyLike())(static_cast <bool> (Copy.isCopyLike()) ? void (0) : __assert_fail
("Copy.isCopyLike()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 3899, __extension__ __PRETTY_FUNCTION__))
;
3900 if (!UseTerminalRule)
3901 return false;
3902 Register SrcReg, DstReg;
3903 unsigned SrcSubReg = 0, DstSubReg = 0;
3904 if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
3905 return false;
3906 // Check if the destination of this copy has any other affinity.
3907 if (DstReg.isPhysical() ||
3908 // If SrcReg is a physical register, the copy won't be coalesced.
3909 // Ignoring it may have other side effect (like missing
3910 // rematerialization). So keep it.
3911 SrcReg.isPhysical() || !isTerminalReg(DstReg, Copy, MRI))
3912 return false;
3913
3914 // DstReg is a terminal node. Check if it interferes with any other
3915 // copy involving SrcReg.
3916 const MachineBasicBlock *OrigBB = Copy.getParent();
3917 const LiveInterval &DstLI = LIS->getInterval(DstReg);
3918 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
3919 // Technically we should check if the weight of the new copy is
3920 // interesting compared to the other one and update the weight
3921 // of the copies accordingly. However, this would only work if
3922 // we would gather all the copies first then coalesce, whereas
3923 // right now we interleave both actions.
3924 // For now, just consider the copies that are in the same block.
3925 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
3926 continue;
3927 Register OtherSrcReg, OtherReg;
3928 unsigned OtherSrcSubReg = 0, OtherSubReg = 0;
3929 if (!isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
3930 OtherSubReg))
3931 return false;
3932 if (OtherReg == SrcReg)
3933 OtherReg = OtherSrcReg;
3934 // Check if OtherReg is a non-terminal.
3935 if (Register::isPhysicalRegister(OtherReg) ||
3936 isTerminalReg(OtherReg, MI, MRI))
3937 continue;
3938 // Check that OtherReg interfere with DstReg.
3939 if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
3940 LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Apply terminal rule for: " <<
printReg(DstReg) << '\n'; } } while (false)
3941 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Apply terminal rule for: " <<
printReg(DstReg) << '\n'; } } while (false)
;
3942 return true;
3943 }
3944 }
3945 return false;
3946}
3947
3948void
3949RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
3950 LLVM_DEBUG(dbgs() << MBB->getName() << ":\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << MBB->getName() << ":\n"
; } } while (false)
;
3951
3952 // Collect all copy-like instructions in MBB. Don't start coalescing anything
3953 // yet, it might invalidate the iterator.
3954 const unsigned PrevSize = WorkList.size();
3955 if (JoinGlobalCopies) {
3956 SmallVector<MachineInstr*, 2> LocalTerminals;
3957 SmallVector<MachineInstr*, 2> GlobalTerminals;
3958 // Coalesce copies bottom-up to coalesce local defs before local uses. They
3959 // are not inherently easier to resolve, but slightly preferable until we
3960 // have local live range splitting. In particular this is required by
3961 // cmp+jmp macro fusion.
3962 for (MachineInstr &MI : *MBB) {
3963 if (!MI.isCopyLike())
3964 continue;
3965 bool ApplyTerminalRule = applyTerminalRule(MI);
3966 if (isLocalCopy(&MI, LIS)) {
3967 if (ApplyTerminalRule)
3968 LocalTerminals.push_back(&MI);
3969 else
3970 LocalWorkList.push_back(&MI);
3971 } else {
3972 if (ApplyTerminalRule)
3973 GlobalTerminals.push_back(&MI);
3974 else
3975 WorkList.push_back(&MI);
3976 }
3977 }
3978 // Append the copies evicted by the terminal rule at the end of the list.
3979 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
3980 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
3981 }
3982 else {
3983 SmallVector<MachineInstr*, 2> Terminals;
3984 for (MachineInstr &MII : *MBB)
3985 if (MII.isCopyLike()) {
3986 if (applyTerminalRule(MII))
3987 Terminals.push_back(&MII);
3988 else
3989 WorkList.push_back(&MII);
3990 }
3991 // Append the copies evicted by the terminal rule at the end of the list.
3992 WorkList.append(Terminals.begin(), Terminals.end());
3993 }
3994 // Try coalescing the collected copies immediately, and remove the nulls.
3995 // This prevents the WorkList from getting too large since most copies are
3996 // joinable on the first attempt.
3997 MutableArrayRef<MachineInstr*>
3998 CurrList(WorkList.begin() + PrevSize, WorkList.end());
3999 if (copyCoalesceWorkList(CurrList))
4000 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
4001 nullptr), WorkList.end());
4002}
4003
4004void RegisterCoalescer::coalesceLocals() {
4005 copyCoalesceWorkList(LocalWorkList);
4006 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
4007 if (LocalWorkList[j])
4008 WorkList.push_back(LocalWorkList[j]);
4009 }
4010 LocalWorkList.clear();
4011}
4012
4013void RegisterCoalescer::joinAllIntervals() {
4014 LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "********** JOINING INTERVALS ***********\n"
; } } while (false)
;
4015 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.")(static_cast <bool> (WorkList.empty() && LocalWorkList
.empty() && "Old data still around.") ? void (0) : __assert_fail
("WorkList.empty() && LocalWorkList.empty() && \"Old data still around.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 4015, __extension__ __PRETTY_FUNCTION__))
;
4016
4017 std::vector<MBBPriorityInfo> MBBs;
4018 MBBs.reserve(MF->size());
4019 for (MachineBasicBlock &MBB : *MF) {
4020 MBBs.push_back(MBBPriorityInfo(&MBB, Loops->getLoopDepth(&MBB),
4021 JoinSplitEdges && isSplitEdge(&MBB)));
4022 }
4023 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
4024
4025 // Coalesce intervals in MBB priority order.
4026 unsigned CurrDepth = std::numeric_limits<unsigned>::max();
4027 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
4028 // Try coalescing the collected local copies for deeper loops.
4029 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
4030 coalesceLocals();
4031 CurrDepth = MBBs[i].Depth;
4032 }
4033 copyCoalesceInMBB(MBBs[i].MBB);
4034 }
4035 lateLiveIntervalUpdate();
4036 coalesceLocals();
4037
4038 // Joining intervals can allow other intervals to be joined. Iteratively join
4039 // until we make no progress.
4040 while (copyCoalesceWorkList(WorkList))
4041 /* empty */ ;
4042 lateLiveIntervalUpdate();
4043}
4044
4045void RegisterCoalescer::releaseMemory() {
4046 ErasedInstrs.clear();
4047 WorkList.clear();
4048 DeadDefs.clear();
4049 InflateRegs.clear();
4050 LargeLIVisitCounter.clear();
4051}
4052
4053bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
4054 LLVM_DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
<< "********** Function: " << fn.getName() <<
'\n'; } } while (false)
4055 << "********** Function: " << fn.getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
<< "********** Function: " << fn.getName() <<
'\n'; } } while (false)
;
4056
4057 // Variables changed between a setjmp and a longjump can have undefined value
4058 // after the longjmp. This behaviour can be observed if such a variable is
4059 // spilled, so longjmp won't restore the value in the spill slot.
4060 // RegisterCoalescer should not run in functions with a setjmp to avoid
4061 // merging such undefined variables with predictable ones.
4062 //
4063 // TODO: Could specifically disable coalescing registers live across setjmp
4064 // calls
4065 if (fn.exposesReturnsTwice()) {
4066 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "* Skipped as it exposes funcions that returns twice.\n"
; } } while (false)
4067 dbgs() << "* Skipped as it exposes funcions that returns twice.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "* Skipped as it exposes funcions that returns twice.\n"
; } } while (false)
;
4068 return false;
4069 }
4070
4071 MF = &fn;
4072 MRI = &fn.getRegInfo();
4073 const TargetSubtargetInfo &STI = fn.getSubtarget();
4074 TRI = STI.getRegisterInfo();
4075 TII = STI.getInstrInfo();
4076 LIS = &getAnalysis<LiveIntervals>();
4077 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4078 Loops = &getAnalysis<MachineLoopInfo>();
4079 if (EnableGlobalCopies == cl::BOU_UNSET)
4080 JoinGlobalCopies = STI.enableJoinGlobalCopies();
4081 else
4082 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
4083
4084 // If there are PHIs tracked by debug-info, they will need updating during
4085 // coalescing. Build an index of those PHIs to ease updating.
4086 SlotIndexes *Slots = LIS->getSlotIndexes();
4087 for (const auto &DebugPHI : MF->DebugPHIPositions) {
4088 MachineBasicBlock *MBB = DebugPHI.second.MBB;
4089 Register Reg = DebugPHI.second.Reg;
4090 unsigned SubReg = DebugPHI.second.SubReg;
4091 SlotIndex SI = Slots->getMBBStartIdx(MBB);
4092 PHIValPos P = {SI, Reg, SubReg};
4093 PHIValToPos.insert(std::make_pair(DebugPHI.first, P));
4094 RegToPHIIdx[Reg].push_back(DebugPHI.first);
4095 }
4096
4097 // The MachineScheduler does not currently require JoinSplitEdges. This will
4098 // either be enabled unconditionally or replaced by a more general live range
4099 // splitting optimization.
4100 JoinSplitEdges = EnableJoinSplits;
4101
4102 if (VerifyCoalescing)
4103 MF->verify(this, "Before register coalescing");
4104
4105 DbgVRegToValues.clear();
4106 DbgMergedVRegNums.clear();
4107 buildVRegToDbgValueMap(fn);
4108
4109 RegClassInfo.runOnMachineFunction(fn);
4110
4111 // Join (coalesce) intervals if requested.
4112 if (EnableJoining)
4113 joinAllIntervals();
4114
4115 // After deleting a lot of copies, register classes may be less constrained.
4116 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
4117 // DPR inflation.
4118 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
4119 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
4120 InflateRegs.end());
4121 LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Trying to inflate " <<
InflateRegs.size() << " regs.\n"; } } while (false)
4122 << " regs.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Trying to inflate " <<
InflateRegs.size() << " regs.\n"; } } while (false)
;
4123 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
4124 Register Reg = InflateRegs[i];
4125 if (MRI->reg_nodbg_empty(Reg))
4126 continue;
4127 if (MRI->recomputeRegClass(Reg)) {
4128 LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << printReg(Reg) << " inflated to "
<< TRI->getRegClassName(MRI->getRegClass(Reg)) <<
'\n'; } } while (false)
4129 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << printReg(Reg) << " inflated to "
<< TRI->getRegClassName(MRI->getRegClass(Reg)) <<
'\n'; } } while (false)
;
4130 ++NumInflated;
4131
4132 LiveInterval &LI = LIS->getInterval(Reg);
4133 if (LI.hasSubRanges()) {
4134 // If the inflated register class does not support subregisters anymore
4135 // remove the subranges.
4136 if (!MRI->shouldTrackSubRegLiveness(Reg)) {
4137 LI.clearSubRanges();
4138 } else {
4139#ifndef NDEBUG
4140 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
4141 // If subranges are still supported, then the same subregs
4142 // should still be supported.
4143 for (LiveInterval::SubRange &S : LI.subranges()) {
4144 assert((S.LaneMask & ~MaxMask).none())(static_cast <bool> ((S.LaneMask & ~MaxMask).none()
) ? void (0) : __assert_fail ("(S.LaneMask & ~MaxMask).none()"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 4144, __extension__ __PRETTY_FUNCTION__))
;
4145 }
4146#endif
4147 }
4148 }
4149 }
4150 }
4151
4152 // After coalescing, update any PHIs that are being tracked by debug-info
4153 // with their new VReg locations.
4154 for (auto &p : MF->DebugPHIPositions) {
4155 auto it = PHIValToPos.find(p.first);
4156 assert(it != PHIValToPos.end())(static_cast <bool> (it != PHIValToPos.end()) ? void (0
) : __assert_fail ("it != PHIValToPos.end()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/lib/CodeGen/RegisterCoalescer.cpp"
, 4156, __extension__ __PRETTY_FUNCTION__))
;
4157 p.second.Reg = it->second.Reg;
4158 p.second.SubReg = it->second.SubReg;
4159 }
4160
4161 PHIValToPos.clear();
4162 RegToPHIIdx.clear();
4163
4164 LLVM_DEBUG(dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dump(); } } while (false)
;
4165 if (VerifyCoalescing)
4166 MF->verify(this, "After register coalescing");
4167 return true;
4168}
4169
4170void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
4171 LIS->print(O, m);
4172}

/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h

1//===- llvm/CodeGen/LiveInterval.h - Interval representation ----*- C++ -*-===//
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// This file implements the LiveRange and LiveInterval classes. Given some
10// numbering of each the machine instructions an interval [i, j) is said to be a
11// live range for register v if there is no instruction with number j' >= j
12// such that v is live at j' and there is no instruction with number i' < i such
13// that v is live at i'. In this implementation ranges can have holes,
14// i.e. a range might look like [1,20), [50,65), [1000,1001). Each
15// individual segment is represented as an instance of LiveRange::Segment,
16// and the whole range is represented as an instance of LiveRange.
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_CODEGEN_LIVEINTERVAL_H
21#define LLVM_CODEGEN_LIVEINTERVAL_H
22
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/IntEqClasses.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/CodeGen/Register.h"
29#include "llvm/CodeGen/SlotIndexes.h"
30#include "llvm/MC/LaneBitmask.h"
31#include "llvm/Support/Allocator.h"
32#include "llvm/Support/MathExtras.h"
33#include <algorithm>
34#include <cassert>
35#include <cstddef>
36#include <functional>
37#include <memory>
38#include <set>
39#include <tuple>
40#include <utility>
41
42namespace llvm {
43
44 class CoalescerPair;
45 class LiveIntervals;
46 class MachineRegisterInfo;
47 class raw_ostream;
48
49 /// VNInfo - Value Number Information.
50 /// This class holds information about a machine level values, including
51 /// definition and use points.
52 ///
53 class VNInfo {
54 public:
55 using Allocator = BumpPtrAllocator;
56
57 /// The ID number of this value.
58 unsigned id;
59
60 /// The index of the defining instruction.
61 SlotIndex def;
62
63 /// VNInfo constructor.
64 VNInfo(unsigned i, SlotIndex d) : id(i), def(d) {}
65
66 /// VNInfo constructor, copies values from orig, except for the value number.
67 VNInfo(unsigned i, const VNInfo &orig) : id(i), def(orig.def) {}
68
69 /// Copy from the parameter into this VNInfo.
70 void copyFrom(VNInfo &src) {
71 def = src.def;
72 }
73
74 /// Returns true if this value is defined by a PHI instruction (or was,
75 /// PHI instructions may have been eliminated).
76 /// PHI-defs begin at a block boundary, all other defs begin at register or
77 /// EC slots.
78 bool isPHIDef() const { return def.isBlock(); }
3
Calling 'SlotIndex::isBlock'
6
Returning from 'SlotIndex::isBlock'
7
Returning zero, which participates in a condition later
79
80 /// Returns true if this value is unused.
81 bool isUnused() const { return !def.isValid(); }
82
83 /// Mark this value as unused.
84 void markUnused() { def = SlotIndex(); }
85 };
86
87 /// Result of a LiveRange query. This class hides the implementation details
88 /// of live ranges, and it should be used as the primary interface for
89 /// examining live ranges around instructions.
90 class LiveQueryResult {
91 VNInfo *const EarlyVal;
92 VNInfo *const LateVal;
93 const SlotIndex EndPoint;
94 const bool Kill;
95
96 public:
97 LiveQueryResult(VNInfo *EarlyVal, VNInfo *LateVal, SlotIndex EndPoint,
98 bool Kill)
99 : EarlyVal(EarlyVal), LateVal(LateVal), EndPoint(EndPoint), Kill(Kill)
100 {}
101
102 /// Return the value that is live-in to the instruction. This is the value
103 /// that will be read by the instruction's use operands. Return NULL if no
104 /// value is live-in.
105 VNInfo *valueIn() const {
106 return EarlyVal;
107 }
108
109 /// Return true if the live-in value is killed by this instruction. This
110 /// means that either the live range ends at the instruction, or it changes
111 /// value.
112 bool isKill() const {
113 return Kill;
114 }
115
116 /// Return true if this instruction has a dead def.
117 bool isDeadDef() const {
118 return EndPoint.isDead();
119 }
120
121 /// Return the value leaving the instruction, if any. This can be a
122 /// live-through value, or a live def. A dead def returns NULL.
123 VNInfo *valueOut() const {
124 return isDeadDef() ? nullptr : LateVal;
125 }
126
127 /// Returns the value alive at the end of the instruction, if any. This can
128 /// be a live-through value, a live def or a dead def.
129 VNInfo *valueOutOrDead() const {
130 return LateVal;
131 }
132
133 /// Return the value defined by this instruction, if any. This includes
134 /// dead defs, it is the value created by the instruction's def operands.
135 VNInfo *valueDefined() const {
136 return EarlyVal == LateVal ? nullptr : LateVal;
137 }
138
139 /// Return the end point of the last live range segment to interact with
140 /// the instruction, if any.
141 ///
142 /// The end point is an invalid SlotIndex only if the live range doesn't
143 /// intersect the instruction at all.
144 ///
145 /// The end point may be at or past the end of the instruction's basic
146 /// block. That means the value was live out of the block.
147 SlotIndex endPoint() const {
148 return EndPoint;
149 }
150 };
151
152 /// This class represents the liveness of a register, stack slot, etc.
153 /// It manages an ordered list of Segment objects.
154 /// The Segments are organized in a static single assignment form: At places
155 /// where a new value is defined or different values reach a CFG join a new
156 /// segment with a new value number is used.
157 class LiveRange {
158 public:
159 /// This represents a simple continuous liveness interval for a value.
160 /// The start point is inclusive, the end point exclusive. These intervals
161 /// are rendered as [start,end).
162 struct Segment {
163 SlotIndex start; // Start point of the interval (inclusive)
164 SlotIndex end; // End point of the interval (exclusive)
165 VNInfo *valno = nullptr; // identifier for the value contained in this
166 // segment.
167
168 Segment() = default;
169
170 Segment(SlotIndex S, SlotIndex E, VNInfo *V)
171 : start(S), end(E), valno(V) {
172 assert(S < E && "Cannot create empty or backwards segment")(static_cast <bool> (S < E && "Cannot create empty or backwards segment"
) ? void (0) : __assert_fail ("S < E && \"Cannot create empty or backwards segment\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 172, __extension__ __PRETTY_FUNCTION__))
;
173 }
174
175 /// Return true if the index is covered by this segment.
176 bool contains(SlotIndex I) const {
177 return start <= I && I < end;
178 }
179
180 /// Return true if the given interval, [S, E), is covered by this segment.
181 bool containsInterval(SlotIndex S, SlotIndex E) const {
182 assert((S < E) && "Backwards interval?")(static_cast <bool> ((S < E) && "Backwards interval?"
) ? void (0) : __assert_fail ("(S < E) && \"Backwards interval?\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 182, __extension__ __PRETTY_FUNCTION__))
;
183 return (start <= S && S < end) && (start < E && E <= end);
184 }
185
186 bool operator<(const Segment &Other) const {
187 return std::tie(start, end) < std::tie(Other.start, Other.end);
188 }
189 bool operator==(const Segment &Other) const {
190 return start == Other.start && end == Other.end;
191 }
192
193 bool operator!=(const Segment &Other) const {
194 return !(*this == Other);
195 }
196
197 void dump() const;
198 };
199
200 using Segments = SmallVector<Segment, 2>;
201 using VNInfoList = SmallVector<VNInfo *, 2>;
202
203 Segments segments; // the liveness segments
204 VNInfoList valnos; // value#'s
205
206 // The segment set is used temporarily to accelerate initial computation
207 // of live ranges of physical registers in computeRegUnitRange.
208 // After that the set is flushed to the segment vector and deleted.
209 using SegmentSet = std::set<Segment>;
210 std::unique_ptr<SegmentSet> segmentSet;
211
212 using iterator = Segments::iterator;
213 using const_iterator = Segments::const_iterator;
214
215 iterator begin() { return segments.begin(); }
216 iterator end() { return segments.end(); }
217
218 const_iterator begin() const { return segments.begin(); }
219 const_iterator end() const { return segments.end(); }
220
221 using vni_iterator = VNInfoList::iterator;
222 using const_vni_iterator = VNInfoList::const_iterator;
223
224 vni_iterator vni_begin() { return valnos.begin(); }
225 vni_iterator vni_end() { return valnos.end(); }
226
227 const_vni_iterator vni_begin() const { return valnos.begin(); }
228 const_vni_iterator vni_end() const { return valnos.end(); }
229
230 /// Constructs a new LiveRange object.
231 LiveRange(bool UseSegmentSet = false)
232 : segmentSet(UseSegmentSet ? std::make_unique<SegmentSet>()
233 : nullptr) {}
234
235 /// Constructs a new LiveRange object by copying segments and valnos from
236 /// another LiveRange.
237 LiveRange(const LiveRange &Other, BumpPtrAllocator &Allocator) {
238 assert(Other.segmentSet == nullptr &&(static_cast <bool> (Other.segmentSet == nullptr &&
"Copying of LiveRanges with active SegmentSets is not supported"
) ? void (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 239, __extension__ __PRETTY_FUNCTION__))
239 "Copying of LiveRanges with active SegmentSets is not supported")(static_cast <bool> (Other.segmentSet == nullptr &&
"Copying of LiveRanges with active SegmentSets is not supported"
) ? void (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 239, __extension__ __PRETTY_FUNCTION__))
;
240 assign(Other, Allocator);
241 }
242
243 /// Copies values numbers and live segments from \p Other into this range.
244 void assign(const LiveRange &Other, BumpPtrAllocator &Allocator) {
245 if (this == &Other)
246 return;
247
248 assert(Other.segmentSet == nullptr &&(static_cast <bool> (Other.segmentSet == nullptr &&
"Copying of LiveRanges with active SegmentSets is not supported"
) ? void (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 249, __extension__ __PRETTY_FUNCTION__))
249 "Copying of LiveRanges with active SegmentSets is not supported")(static_cast <bool> (Other.segmentSet == nullptr &&
"Copying of LiveRanges with active SegmentSets is not supported"
) ? void (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 249, __extension__ __PRETTY_FUNCTION__))
;
250 // Duplicate valnos.
251 for (const VNInfo *VNI : Other.valnos)
252 createValueCopy(VNI, Allocator);
253 // Now we can copy segments and remap their valnos.
254 for (const Segment &S : Other.segments)
255 segments.push_back(Segment(S.start, S.end, valnos[S.valno->id]));
256 }
257
258 /// advanceTo - Advance the specified iterator to point to the Segment
259 /// containing the specified position, or end() if the position is past the
260 /// end of the range. If no Segment contains this position, but the
261 /// position is in a hole, this method returns an iterator pointing to the
262 /// Segment immediately after the hole.
263 iterator advanceTo(iterator I, SlotIndex Pos) {
264 assert(I != end())(static_cast <bool> (I != end()) ? void (0) : __assert_fail
("I != end()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 264, __extension__ __PRETTY_FUNCTION__))
;
265 if (Pos >= endIndex())
266 return end();
267 while (I->end <= Pos) ++I;
268 return I;
269 }
270
271 const_iterator advanceTo(const_iterator I, SlotIndex Pos) const {
272 assert(I != end())(static_cast <bool> (I != end()) ? void (0) : __assert_fail
("I != end()", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 272, __extension__ __PRETTY_FUNCTION__))
;
273 if (Pos >= endIndex())
274 return end();
275 while (I->end <= Pos) ++I;
276 return I;
277 }
278
279 /// find - Return an iterator pointing to the first segment that ends after
280 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
281 /// when searching large ranges.
282 ///
283 /// If Pos is contained in a Segment, that segment is returned.
284 /// If Pos is in a hole, the following Segment is returned.
285 /// If Pos is beyond endIndex, end() is returned.
286 iterator find(SlotIndex Pos);
287
288 const_iterator find(SlotIndex Pos) const {
289 return const_cast<LiveRange*>(this)->find(Pos);
290 }
291
292 void clear() {
293 valnos.clear();
294 segments.clear();
295 }
296
297 size_t size() const {
298 return segments.size();
299 }
300
301 bool hasAtLeastOneValue() const { return !valnos.empty(); }
302
303 bool containsOneValue() const { return valnos.size() == 1; }
304
305 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
306
307 /// getValNumInfo - Returns pointer to the specified val#.
308 ///
309 inline VNInfo *getValNumInfo(unsigned ValNo) {
310 return valnos[ValNo];
311 }
312 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
313 return valnos[ValNo];
314 }
315
316 /// containsValue - Returns true if VNI belongs to this range.
317 bool containsValue(const VNInfo *VNI) const {
318 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
319 }
320
321 /// getNextValue - Create a new value number and return it. MIIdx specifies
322 /// the instruction that defines the value number.
323 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
324 VNInfo *VNI =
325 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
326 valnos.push_back(VNI);
327 return VNI;
328 }
329
330 /// createDeadDef - Make sure the range has a value defined at Def.
331 /// If one already exists, return it. Otherwise allocate a new value and
332 /// add liveness for a dead def.
333 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc);
334
335 /// Create a def of value @p VNI. Return @p VNI. If there already exists
336 /// a definition at VNI->def, the value defined there must be @p VNI.
337 VNInfo *createDeadDef(VNInfo *VNI);
338
339 /// Create a copy of the given value. The new value will be identical except
340 /// for the Value number.
341 VNInfo *createValueCopy(const VNInfo *orig,
342 VNInfo::Allocator &VNInfoAllocator) {
343 VNInfo *VNI =
344 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
345 valnos.push_back(VNI);
346 return VNI;
347 }
348
349 /// RenumberValues - Renumber all values in order of appearance and remove
350 /// unused values.
351 void RenumberValues();
352
353 /// MergeValueNumberInto - This method is called when two value numbers
354 /// are found to be equivalent. This eliminates V1, replacing all
355 /// segments with the V1 value number with the V2 value number. This can
356 /// cause merging of V1/V2 values numbers and compaction of the value space.
357 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
358
359 /// Merge all of the live segments of a specific val# in RHS into this live
360 /// range as the specified value number. The segments in RHS are allowed
361 /// to overlap with segments in the current range, it will replace the
362 /// value numbers of the overlaped live segments with the specified value
363 /// number.
364 void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo);
365
366 /// MergeValueInAsValue - Merge all of the segments of a specific val#
367 /// in RHS into this live range as the specified value number.
368 /// The segments in RHS are allowed to overlap with segments in the
369 /// current range, but only if the overlapping segments have the
370 /// specified value number.
371 void MergeValueInAsValue(const LiveRange &RHS,
372 const VNInfo *RHSValNo, VNInfo *LHSValNo);
373
374 bool empty() const { return segments.empty(); }
375
376 /// beginIndex - Return the lowest numbered slot covered.
377 SlotIndex beginIndex() const {
378 assert(!empty() && "Call to beginIndex() on empty range.")(static_cast <bool> (!empty() && "Call to beginIndex() on empty range."
) ? void (0) : __assert_fail ("!empty() && \"Call to beginIndex() on empty range.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 378, __extension__ __PRETTY_FUNCTION__))
;
379 return segments.front().start;
380 }
381
382 /// endNumber - return the maximum point of the range of the whole,
383 /// exclusive.
384 SlotIndex endIndex() const {
385 assert(!empty() && "Call to endIndex() on empty range.")(static_cast <bool> (!empty() && "Call to endIndex() on empty range."
) ? void (0) : __assert_fail ("!empty() && \"Call to endIndex() on empty range.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 385, __extension__ __PRETTY_FUNCTION__))
;
386 return segments.back().end;
387 }
388
389 bool expiredAt(SlotIndex index) const {
390 return index >= endIndex();
391 }
392
393 bool liveAt(SlotIndex index) const {
394 const_iterator r = find(index);
395 return r != end() && r->start <= index;
396 }
397
398 /// Return the segment that contains the specified index, or null if there
399 /// is none.
400 const Segment *getSegmentContaining(SlotIndex Idx) const {
401 const_iterator I = FindSegmentContaining(Idx);
402 return I == end() ? nullptr : &*I;
403 }
404
405 /// Return the live segment that contains the specified index, or null if
406 /// there is none.
407 Segment *getSegmentContaining(SlotIndex Idx) {
408 iterator I = FindSegmentContaining(Idx);
409 return I == end() ? nullptr : &*I;
410 }
411
412 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
413 VNInfo *getVNInfoAt(SlotIndex Idx) const {
414 const_iterator I = FindSegmentContaining(Idx);
415 return I == end() ? nullptr : I->valno;
416 }
417
418 /// getVNInfoBefore - Return the VNInfo that is live up to but not
419 /// necessarilly including Idx, or NULL. Use this to find the reaching def
420 /// used by an instruction at this SlotIndex position.
421 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
422 const_iterator I = FindSegmentContaining(Idx.getPrevSlot());
423 return I == end() ? nullptr : I->valno;
424 }
425
426 /// Return an iterator to the segment that contains the specified index, or
427 /// end() if there is none.
428 iterator FindSegmentContaining(SlotIndex Idx) {
429 iterator I = find(Idx);
430 return I != end() && I->start <= Idx ? I : end();
431 }
432
433 const_iterator FindSegmentContaining(SlotIndex Idx) const {
434 const_iterator I = find(Idx);
435 return I != end() && I->start <= Idx ? I : end();
436 }
437
438 /// overlaps - Return true if the intersection of the two live ranges is
439 /// not empty.
440 bool overlaps(const LiveRange &other) const {
441 if (other.empty())
442 return false;
443 return overlapsFrom(other, other.begin());
444 }
445
446 /// overlaps - Return true if the two ranges have overlapping segments
447 /// that are not coalescable according to CP.
448 ///
449 /// Overlapping segments where one range is defined by a coalescable
450 /// copy are allowed.
451 bool overlaps(const LiveRange &Other, const CoalescerPair &CP,
452 const SlotIndexes&) const;
453
454 /// overlaps - Return true if the live range overlaps an interval specified
455 /// by [Start, End).
456 bool overlaps(SlotIndex Start, SlotIndex End) const;
457
458 /// overlapsFrom - Return true if the intersection of the two live ranges
459 /// is not empty. The specified iterator is a hint that we can begin
460 /// scanning the Other range starting at I.
461 bool overlapsFrom(const LiveRange &Other, const_iterator StartPos) const;
462
463 /// Returns true if all segments of the @p Other live range are completely
464 /// covered by this live range.
465 /// Adjacent live ranges do not affect the covering:the liverange
466 /// [1,5](5,10] covers (3,7].
467 bool covers(const LiveRange &Other) const;
468
469 /// Add the specified Segment to this range, merging segments as
470 /// appropriate. This returns an iterator to the inserted segment (which
471 /// may have grown since it was inserted).
472 iterator addSegment(Segment S);
473
474 /// Attempt to extend a value defined after @p StartIdx to include @p Use.
475 /// Both @p StartIdx and @p Use should be in the same basic block. In case
476 /// of subranges, an extension could be prevented by an explicit "undef"
477 /// caused by a <def,read-undef> on a non-overlapping lane. The list of
478 /// location of such "undefs" should be provided in @p Undefs.
479 /// The return value is a pair: the first element is VNInfo of the value
480 /// that was extended (possibly nullptr), the second is a boolean value
481 /// indicating whether an "undef" was encountered.
482 /// If this range is live before @p Use in the basic block that starts at
483 /// @p StartIdx, and there is no intervening "undef", extend it to be live
484 /// up to @p Use, and return the pair {value, false}. If there is no
485 /// segment before @p Use and there is no "undef" between @p StartIdx and
486 /// @p Use, return {nullptr, false}. If there is an "undef" before @p Use,
487 /// return {nullptr, true}.
488 std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
489 SlotIndex StartIdx, SlotIndex Kill);
490
491 /// Simplified version of the above "extendInBlock", which assumes that
492 /// no register lanes are undefined by <def,read-undef> operands.
493 /// If this range is live before @p Use in the basic block that starts
494 /// at @p StartIdx, extend it to be live up to @p Use, and return the
495 /// value. If there is no segment before @p Use, return nullptr.
496 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
497
498 /// join - Join two live ranges (this, and other) together. This applies
499 /// mappings to the value numbers in the LHS/RHS ranges as specified. If
500 /// the ranges are not joinable, this aborts.
501 void join(LiveRange &Other,
502 const int *ValNoAssignments,
503 const int *RHSValNoAssignments,
504 SmallVectorImpl<VNInfo *> &NewVNInfo);
505
506 /// True iff this segment is a single segment that lies between the
507 /// specified boundaries, exclusively. Vregs live across a backedge are not
508 /// considered local. The boundaries are expected to lie within an extended
509 /// basic block, so vregs that are not live out should contain no holes.
510 bool isLocal(SlotIndex Start, SlotIndex End) const {
511 return beginIndex() > Start.getBaseIndex() &&
512 endIndex() < End.getBoundaryIndex();
513 }
514
515 /// Remove the specified segment from this range. Note that the segment
516 /// must be a single Segment in its entirety.
517 void removeSegment(SlotIndex Start, SlotIndex End,
518 bool RemoveDeadValNo = false);
519
520 void removeSegment(Segment S, bool RemoveDeadValNo = false) {
521 removeSegment(S.start, S.end, RemoveDeadValNo);
522 }
523
524 /// Remove segment pointed to by iterator @p I from this range. This does
525 /// not remove dead value numbers.
526 iterator removeSegment(iterator I) {
527 return segments.erase(I);
528 }
529
530 /// Query Liveness at Idx.
531 /// The sub-instruction slot of Idx doesn't matter, only the instruction
532 /// it refers to is considered.
533 LiveQueryResult Query(SlotIndex Idx) const {
534 // Find the segment that enters the instruction.
535 const_iterator I = find(Idx.getBaseIndex());
536 const_iterator E = end();
537 if (I == E)
538 return LiveQueryResult(nullptr, nullptr, SlotIndex(), false);
539
540 // Is this an instruction live-in segment?
541 // If Idx is the start index of a basic block, include live-in segments
542 // that start at Idx.getBaseIndex().
543 VNInfo *EarlyVal = nullptr;
544 VNInfo *LateVal = nullptr;
545 SlotIndex EndPoint;
546 bool Kill = false;
547 if (I->start <= Idx.getBaseIndex()) {
548 EarlyVal = I->valno;
549 EndPoint = I->end;
550 // Move to the potentially live-out segment.
551 if (SlotIndex::isSameInstr(Idx, I->end)) {
552 Kill = true;
553 if (++I == E)
554 return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
555 }
556 // Special case: A PHIDef value can have its def in the middle of a
557 // segment if the value happens to be live out of the layout
558 // predecessor.
559 // Such a value is not live-in.
560 if (EarlyVal->def == Idx.getBaseIndex())
561 EarlyVal = nullptr;
562 }
563 // I now points to the segment that may be live-through, or defined by
564 // this instr. Ignore segments starting after the current instr.
565 if (!SlotIndex::isEarlierInstr(Idx, I->start)) {
566 LateVal = I->valno;
567 EndPoint = I->end;
568 }
569 return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
570 }
571
572 /// removeValNo - Remove all the segments defined by the specified value#.
573 /// Also remove the value# from value# list.
574 void removeValNo(VNInfo *ValNo);
575
576 /// Returns true if the live range is zero length, i.e. no live segments
577 /// span instructions. It doesn't pay to spill such a range.
578 bool isZeroLength(SlotIndexes *Indexes) const {
579 for (const Segment &S : segments)
580 if (Indexes->getNextNonNullIndex(S.start).getBaseIndex() <
581 S.end.getBaseIndex())
582 return false;
583 return true;
584 }
585
586 // Returns true if any segment in the live range contains any of the
587 // provided slot indexes. Slots which occur in holes between
588 // segments will not cause the function to return true.
589 bool isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const;
590
591 bool operator<(const LiveRange& other) const {
592 const SlotIndex &thisIndex = beginIndex();
593 const SlotIndex &otherIndex = other.beginIndex();
594 return thisIndex < otherIndex;
595 }
596
597 /// Returns true if there is an explicit "undef" between @p Begin
598 /// @p End.
599 bool isUndefIn(ArrayRef<SlotIndex> Undefs, SlotIndex Begin,
600 SlotIndex End) const {
601 return llvm::any_of(Undefs, [Begin, End](SlotIndex Idx) -> bool {
602 return Begin <= Idx && Idx < End;
603 });
604 }
605
606 /// Flush segment set into the regular segment vector.
607 /// The method is to be called after the live range
608 /// has been created, if use of the segment set was
609 /// activated in the constructor of the live range.
610 void flushSegmentSet();
611
612 /// Stores indexes from the input index sequence R at which this LiveRange
613 /// is live to the output O iterator.
614 /// R is a range of _ascending sorted_ _random_ access iterators
615 /// to the input indexes. Indexes stored at O are ascending sorted so it
616 /// can be used directly in the subsequent search (for example for
617 /// subranges). Returns true if found at least one index.
618 template <typename Range, typename OutputIt>
619 bool findIndexesLiveAt(Range &&R, OutputIt O) const {
620 assert(llvm::is_sorted(R))(static_cast <bool> (llvm::is_sorted(R)) ? void (0) : __assert_fail
("llvm::is_sorted(R)", "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/LiveInterval.h"
, 620, __extension__ __PRETTY_FUNCTION__))
;
621 auto Idx = R.begin(), EndIdx = R.end();
622 auto Seg = segments.begin(), EndSeg = segments.end();
623 bool Found = false;
624 while (Idx != EndIdx && Seg != EndSeg) {
625 // if the Seg is lower find first segment that is above Idx using binary
626 // search
627 if (Seg->end <= *Idx) {
628 Seg = std::upper_bound(
629 ++Seg, EndSeg, *Idx,
630 [=](std::remove_reference_t<decltype(*Idx)> V,
631 const std::remove_reference_t<decltype(*Seg)> &S) {
632 return V < S.end;
633 });
634 if (Seg == EndSeg)
635 break;
636 }
637 auto NotLessStart = std::lower_bound(Idx, EndIdx, Seg->start);
638 if (NotLessStart == EndIdx)
639 break;
640 auto NotLessEnd = std::lower_bound(NotLessStart, EndIdx, Seg->end);
641 if (NotLessEnd != NotLessStart) {
642 Found = true;
643 O = std::copy(NotLessStart, NotLessEnd, O);
644 }
645 Idx = NotLessEnd;
646 ++Seg;
647 }
648 return Found;
649 }
650
651 void print(raw_ostream &OS) const;
652 void dump() const;
653
654 /// Walk the range and assert if any invariants fail to hold.
655 ///
656 /// Note that this is a no-op when asserts are disabled.
657#ifdef NDEBUG
658 void verify() const {}
659#else
660 void verify() const;
661#endif
662
663 protected:
664 /// Append a segment to the list of segments.
665 void append(const LiveRange::Segment S);
666
667 private:
668 friend class LiveRangeUpdater;
669 void addSegmentToSet(Segment S);
670 void markValNoForDeletion(VNInfo *V);
671 };
672
673 inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
674 LR.print(OS);
675 return OS;
676 }
677
678 /// LiveInterval - This class represents the liveness of a register,
679 /// or stack slot.
680 class LiveInterval : public LiveRange {
681 public:
682 using super = LiveRange;
683
684 /// A live range for subregisters. The LaneMask specifies which parts of the
685 /// super register are covered by the interval.
686 /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
687 class SubRange : public LiveRange {
688 public:
689 SubRange *Next = nullptr;
690 LaneBitmask LaneMask;
691
692 /// Constructs a new SubRange object.
693 SubRange(LaneBitmask LaneMask) : LaneMask(LaneMask) {}
694
695 /// Constructs a new SubRange object by copying liveness from @p Other.
696 SubRange(LaneBitmask LaneMask, const LiveRange &Other,
697 BumpPtrAllocator &Allocator)
698 : LiveRange(Other, Allocator), LaneMask(LaneMask) {}
699
700 void print(raw_ostream &OS) const;
701 void dump() const;
702 };
703
704 private:
705 SubRange *SubRanges = nullptr; ///< Single linked list of subregister live
706 /// ranges.
707 const Register Reg; // the register or stack slot of this interval.
708 float Weight = 0.0; // weight of this interval
709
710 public:
711 Register reg() const { return Reg; }
712 float weight() const { return Weight; }
713 void incrementWeight(float Inc) { Weight += Inc; }
714 void setWeight(float Value) { Weight = Value; }
715
716 LiveInterval(unsigned Reg, float Weight) : Reg(Reg), Weight(Weight) {}
717
718 ~LiveInterval() {
719 clearSubRanges();
720 }
721
722 template<typename T>
723 class SingleLinkedListIterator {
724 T *P;
725
726 public:
727 SingleLinkedListIterator<T>(T *P) : P(P) {}
728
729 SingleLinkedListIterator<T> &operator++() {
730 P = P->Next;
731 return *this;
732 }
733 SingleLinkedListIterator<T> operator++(int) {
734 SingleLinkedListIterator res = *this;
735 ++*this;
736 return res;
737 }
738 bool operator!=(const SingleLinkedListIterator<T> &Other) const {
739 return P != Other.operator->();
740 }
741 bool operator==(const SingleLinkedListIterator<T> &Other) const {
742 return P == Other.operator->();
743 }
744 T &operator*() const {
745 return *P;
746 }
747 T *operator->() const {
748 return P;
749 }
750 };
751
752 using subrange_iterator = SingleLinkedListIterator<SubRange>;
753 using const_subrange_iterator = SingleLinkedListIterator<const SubRange>;
754
755 subrange_iterator subrange_begin() {
756 return subrange_iterator(SubRanges);
757 }
758 subrange_iterator subrange_end() {
759 return subrange_iterator(nullptr);
760 }
761
762 const_subrange_iterator subrange_begin() const {
763 return const_subrange_iterator(SubRanges);
764 }
765 const_subrange_iterator subrange_end() const {
766 return const_subrange_iterator(nullptr);
767 }
768
769 iterator_range<subrange_iterator> subranges() {
770 return make_range(subrange_begin(), subrange_end());
771 }
772
773 iterator_range<const_subrange_iterator> subranges() const {
774 return make_range(subrange_begin(), subrange_end());
775 }
776
777 /// Creates a new empty subregister live range. The range is added at the
778 /// beginning of the subrange list; subrange iterators stay valid.
779 SubRange *createSubRange(BumpPtrAllocator &Allocator,
780 LaneBitmask LaneMask) {
781 SubRange *Range = new (Allocator) SubRange(LaneMask);
782 appendSubRange(Range);
783 return Range;
784 }
785
786 /// Like createSubRange() but the new range is filled with a copy of the
787 /// liveness information in @p CopyFrom.
788 SubRange *createSubRangeFrom(BumpPtrAllocator &Allocator,
789 LaneBitmask LaneMask,
790 const LiveRange &CopyFrom) {
791 SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
792 appendSubRange(Range);
793 return Range;
794 }
795
796 /// Returns true if subregister liveness information is available.
797 bool hasSubRanges() const {
798 return SubRanges != nullptr;
799 }
800
801 /// Removes all subregister liveness information.
802 void clearSubRanges();
803
804 /// Removes all subranges without any segments (subranges without segments
805 /// are not considered valid and should only exist temporarily).
806 void removeEmptySubRanges();
807
808 /// getSize - Returns the sum of sizes of all the LiveRange's.
809 ///
810 unsigned getSize() const;
811
812 /// isSpillable - Can this interval be spilled?
813 bool isSpillable() const { return Weight != huge_valf; }
814
815 /// markNotSpillable - Mark interval as not spillable
816 void markNotSpillable() { Weight = huge_valf; }
817
818 /// For a given lane mask @p LaneMask, compute indexes at which the
819 /// lane is marked undefined by subregister <def,read-undef> definitions.
820 void computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
821 LaneBitmask LaneMask,
822 const MachineRegisterInfo &MRI,
823 const SlotIndexes &Indexes) const;
824
825 /// Refines the subranges to support \p LaneMask. This may only be called
826 /// for LI.hasSubrange()==true. Subregister ranges are split or created
827 /// until \p LaneMask can be matched exactly. \p Mod is executed on the
828 /// matching subranges.
829 ///
830 /// Example:
831 /// Given an interval with subranges with lanemasks L0F00, L00F0 and
832 /// L000F, refining for mask L0018. Will split the L00F0 lane into
833 /// L00E0 and L0010 and the L000F lane into L0007 and L0008. The Mod
834 /// function will be applied to the L0010 and L0008 subranges.
835 ///
836 /// \p Indexes and \p TRI are required to clean up the VNIs that
837 /// don't define the related lane masks after they get shrunk. E.g.,
838 /// when L000F gets split into L0007 and L0008 maybe only a subset
839 /// of the VNIs that defined L000F defines L0007.
840 ///
841 /// The clean up of the VNIs need to look at the actual instructions
842 /// to decide what is or is not live at a definition point. If the
843 /// update of the subranges occurs while the IR does not reflect these
844 /// changes, \p ComposeSubRegIdx can be used to specify how the
845 /// definition are going to be rewritten.
846 /// E.g., let say we want to merge:
847 /// V1.sub1:<2 x s32> = COPY V2.sub3:<4 x s32>
848 /// We do that by choosing a class where sub1:<2 x s32> and sub3:<4 x s32>
849 /// overlap, i.e., by choosing a class where we can find "offset + 1 == 3".
850 /// Put differently we align V2's sub3 with V1's sub1:
851 /// V2: sub0 sub1 sub2 sub3
852 /// V1: <offset> sub0 sub1
853 ///
854 /// This offset will look like a composed subregidx in the the class:
855 /// V1.(composed sub2 with sub1):<4 x s32> = COPY V2.sub3:<4 x s32>
856 /// => V1.(composed sub2 with sub1):<4 x s32> = COPY V2.sub3:<4 x s32>
857 ///
858 /// Now if we didn't rewrite the uses and def of V1, all the checks for V1
859 /// need to account for this offset.
860 /// This happens during coalescing where we update the live-ranges while
861 /// still having the old IR around because updating the IR on-the-fly
862 /// would actually clobber some information on how the live-ranges that
863 /// are being updated look like.
864 void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
865 std::function<void(LiveInterval::SubRange &)> Apply,
866 const SlotIndexes &Indexes,
867 const TargetRegisterInfo &TRI,
868 unsigned ComposeSubRegIdx = 0);
869
870 bool operator<(const LiveInterval& other) const {
871 const SlotIndex &thisIndex = beginIndex();
872 const SlotIndex &otherIndex = other.beginIndex();
873 return std::tie(thisIndex, Reg) < std::tie(otherIndex, other.Reg);
874 }
875
876 void print(raw_ostream &OS) const;
877 void dump() const;
878
879 /// Walks the interval and assert if any invariants fail to hold.
880 ///
881 /// Note that this is a no-op when asserts are disabled.
882#ifdef NDEBUG
883 void verify(const MachineRegisterInfo *MRI = nullptr) const {}
884#else
885 void verify(const MachineRegisterInfo *MRI = nullptr) const;
886#endif
887
888 private:
889 /// Appends @p Range to SubRanges list.
890 void appendSubRange(SubRange *Range) {
891 Range->Next = SubRanges;
892 SubRanges = Range;
893 }
894
895 /// Free memory held by SubRange.
896 void freeSubRange(SubRange *S);
897 };
898
899 inline raw_ostream &operator<<(raw_ostream &OS,
900 const LiveInterval::SubRange &SR) {
901 SR.print(OS);
902 return OS;
903 }
904
905 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
906 LI.print(OS);
907 return OS;
908 }
909
910 raw_ostream &operator<<(raw_ostream &OS, const LiveRange::Segment &S);
911
912 inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
913 return V < S.start;
914 }
915
916 inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
917 return S.start < V;
918 }
919
920 /// Helper class for performant LiveRange bulk updates.
921 ///
922 /// Calling LiveRange::addSegment() repeatedly can be expensive on large
923 /// live ranges because segments after the insertion point may need to be
924 /// shifted. The LiveRangeUpdater class can defer the shifting when adding
925 /// many segments in order.
926 ///
927 /// The LiveRange will be in an invalid state until flush() is called.
928 class LiveRangeUpdater {
929 LiveRange *LR;
930 SlotIndex LastStart;
931 LiveRange::iterator WriteI;
932 LiveRange::iterator ReadI;
933 SmallVector<LiveRange::Segment, 16> Spills;
934 void mergeSpills();
935
936 public:
937 /// Create a LiveRangeUpdater for adding segments to LR.
938 /// LR will temporarily be in an invalid state until flush() is called.
939 LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
940
941 ~LiveRangeUpdater() { flush(); }
942
943 /// Add a segment to LR and coalesce when possible, just like
944 /// LR.addSegment(). Segments should be added in increasing start order for
945 /// best performance.
946 void add(LiveRange::Segment);
947
948 void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
949 add(LiveRange::Segment(Start, End, VNI));
950 }
951
952 /// Return true if the LR is currently in an invalid state, and flush()
953 /// needs to be called.
954 bool isDirty() const { return LastStart.isValid(); }
955
956 /// Flush the updater state to LR so it is valid and contains all added
957 /// segments.
958 void flush();
959
960 /// Select a different destination live range.
961 void setDest(LiveRange *lr) {
962 if (LR != lr && isDirty())
963 flush();
964 LR = lr;
965 }
966
967 /// Get the current destination live range.
968 LiveRange *getDest() const { return LR; }
969
970 void dump() const;
971 void print(raw_ostream&) const;
972 };
973
974 inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
975 X.print(OS);
976 return OS;
977 }
978
979 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
980 /// LiveInterval into equivalence clases of connected components. A
981 /// LiveInterval that has multiple connected components can be broken into
982 /// multiple LiveIntervals.
983 ///
984 /// Given a LiveInterval that may have multiple connected components, run:
985 ///
986 /// unsigned numComps = ConEQ.Classify(LI);
987 /// if (numComps > 1) {
988 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
989 /// ConEQ.Distribute(LIS);
990 /// }
991
992 class ConnectedVNInfoEqClasses {
993 LiveIntervals &LIS;
994 IntEqClasses EqClass;
995
996 public:
997 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
998
999 /// Classify the values in \p LR into connected components.
1000 /// Returns the number of connected components.
1001 unsigned Classify(const LiveRange &LR);
1002
1003 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
1004 /// the equivalence class assigned the VNI.
1005 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
1006
1007 /// Distribute values in \p LI into a separate LiveIntervals
1008 /// for each connected component. LIV must have an empty LiveInterval for
1009 /// each additional connected component. The first connected component is
1010 /// left in \p LI.
1011 void Distribute(LiveInterval &LI, LiveInterval *LIV[],
1012 MachineRegisterInfo &MRI);
1013 };
1014
1015} // end namespace llvm
1016
1017#endif // LLVM_CODEGEN_LIVEINTERVAL_H

/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h

1//===- llvm/CodeGen/SlotIndexes.h - Slot indexes representation -*- C++ -*-===//
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// This file implements SlotIndex and related classes. The purpose of SlotIndex
10// is to describe a position at which a register can become live, or cease to
11// be live.
12//
13// SlotIndex is mostly a proxy for entries of the SlotIndexList, a class which
14// is held is LiveIntervals and provides the real numbering. This allows
15// LiveIntervals to perform largely transparent renumbering.
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CODEGEN_SLOTINDEXES_H
19#define LLVM_CODEGEN_SLOTINDEXES_H
20
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/IntervalMap.h"
23#include "llvm/ADT/PointerIntPair.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/ilist.h"
26#include "llvm/CodeGen/MachineBasicBlock.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/MachineInstrBundle.h"
31#include "llvm/Pass.h"
32#include "llvm/Support/Allocator.h"
33#include <algorithm>
34#include <cassert>
35#include <iterator>
36#include <utility>
37
38namespace llvm {
39
40class raw_ostream;
41
42 /// This class represents an entry in the slot index list held in the
43 /// SlotIndexes pass. It should not be used directly. See the
44 /// SlotIndex & SlotIndexes classes for the public interface to this
45 /// information.
46 class IndexListEntry : public ilist_node<IndexListEntry> {
47 MachineInstr *mi;
48 unsigned index;
49
50 public:
51 IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
52
53 MachineInstr* getInstr() const { return mi; }
54 void setInstr(MachineInstr *mi) {
55 this->mi = mi;
56 }
57
58 unsigned getIndex() const { return index; }
59 void setIndex(unsigned index) {
60 this->index = index;
61 }
62
63#ifdef EXPENSIVE_CHECKS
64 // When EXPENSIVE_CHECKS is defined, "erased" index list entries will
65 // actually be moved to a "graveyard" list, and have their pointers
66 // poisoned, so that dangling SlotIndex access can be reliably detected.
67 void setPoison() {
68 intptr_t tmp = reinterpret_cast<intptr_t>(mi);
69 assert(((tmp & 0x1) == 0x0) && "Pointer already poisoned?")(static_cast <bool> (((tmp & 0x1) == 0x0) &&
"Pointer already poisoned?") ? void (0) : __assert_fail ("((tmp & 0x1) == 0x0) && \"Pointer already poisoned?\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 69, __extension__ __PRETTY_FUNCTION__))
;
70 tmp |= 0x1;
71 mi = reinterpret_cast<MachineInstr*>(tmp);
72 }
73
74 bool isPoisoned() const { return (reinterpret_cast<intptr_t>(mi) & 0x1) == 0x1; }
75#endif // EXPENSIVE_CHECKS
76 };
77
78 template <>
79 struct ilist_alloc_traits<IndexListEntry>
80 : public ilist_noalloc_traits<IndexListEntry> {};
81
82 /// SlotIndex - An opaque wrapper around machine indexes.
83 class SlotIndex {
84 friend class SlotIndexes;
85
86 enum Slot {
87 /// Basic block boundary. Used for live ranges entering and leaving a
88 /// block without being live in the layout neighbor. Also used as the
89 /// def slot of PHI-defs.
90 Slot_Block,
91
92 /// Early-clobber register use/def slot. A live range defined at
93 /// Slot_EarlyClobber interferes with normal live ranges killed at
94 /// Slot_Register. Also used as the kill slot for live ranges tied to an
95 /// early-clobber def.
96 Slot_EarlyClobber,
97
98 /// Normal register use/def slot. Normal instructions kill and define
99 /// register live ranges at this slot.
100 Slot_Register,
101
102 /// Dead def kill point. Kill slot for a live range that is defined by
103 /// the same instruction (Slot_Register or Slot_EarlyClobber), but isn't
104 /// used anywhere.
105 Slot_Dead,
106
107 Slot_Count
108 };
109
110 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
111
112 SlotIndex(IndexListEntry *entry, unsigned slot)
113 : lie(entry, slot) {}
114
115 IndexListEntry* listEntry() const {
116 assert(isValid() && "Attempt to compare reserved index.")(static_cast <bool> (isValid() && "Attempt to compare reserved index."
) ? void (0) : __assert_fail ("isValid() && \"Attempt to compare reserved index.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 116, __extension__ __PRETTY_FUNCTION__))
;
117#ifdef EXPENSIVE_CHECKS
118 assert(!lie.getPointer()->isPoisoned() &&(static_cast <bool> (!lie.getPointer()->isPoisoned()
&& "Attempt to access deleted list-entry.") ? void (
0) : __assert_fail ("!lie.getPointer()->isPoisoned() && \"Attempt to access deleted list-entry.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 119, __extension__ __PRETTY_FUNCTION__))
119 "Attempt to access deleted list-entry.")(static_cast <bool> (!lie.getPointer()->isPoisoned()
&& "Attempt to access deleted list-entry.") ? void (
0) : __assert_fail ("!lie.getPointer()->isPoisoned() && \"Attempt to access deleted list-entry.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 119, __extension__ __PRETTY_FUNCTION__))
;
120#endif // EXPENSIVE_CHECKS
121 return lie.getPointer();
122 }
123
124 unsigned getIndex() const {
125 return listEntry()->getIndex() | getSlot();
126 }
127
128 /// Returns the slot for this SlotIndex.
129 Slot getSlot() const {
130 return static_cast<Slot>(lie.getInt());
131 }
132
133 public:
134 enum {
135 /// The default distance between instructions as returned by distance().
136 /// This may vary as instructions are inserted and removed.
137 InstrDist = 4 * Slot_Count
138 };
139
140 /// Construct an invalid index.
141 SlotIndex() = default;
142
143 // Construct a new slot index from the given one, and set the slot.
144 SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
145 assert(lie.getPointer() != nullptr &&(static_cast <bool> (lie.getPointer() != nullptr &&
"Attempt to construct index with 0 pointer.") ? void (0) : __assert_fail
("lie.getPointer() != nullptr && \"Attempt to construct index with 0 pointer.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 146, __extension__ __PRETTY_FUNCTION__))
146 "Attempt to construct index with 0 pointer.")(static_cast <bool> (lie.getPointer() != nullptr &&
"Attempt to construct index with 0 pointer.") ? void (0) : __assert_fail
("lie.getPointer() != nullptr && \"Attempt to construct index with 0 pointer.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 146, __extension__ __PRETTY_FUNCTION__))
;
147 }
148
149 /// Returns true if this is a valid index. Invalid indices do
150 /// not point into an index table, and cannot be compared.
151 bool isValid() const {
152 return lie.getPointer();
153 }
154
155 /// Return true for a valid index.
156 explicit operator bool() const { return isValid(); }
157
158 /// Print this index to the given raw_ostream.
159 void print(raw_ostream &os) const;
160
161 /// Dump this index to stderr.
162 void dump() const;
163
164 /// Compare two SlotIndex objects for equality.
165 bool operator==(SlotIndex other) const {
166 return lie == other.lie;
167 }
168 /// Compare two SlotIndex objects for inequality.
169 bool operator!=(SlotIndex other) const {
170 return lie != other.lie;
171 }
172
173 /// Compare two SlotIndex objects. Return true if the first index
174 /// is strictly lower than the second.
175 bool operator<(SlotIndex other) const {
176 return getIndex() < other.getIndex();
177 }
178 /// Compare two SlotIndex objects. Return true if the first index
179 /// is lower than, or equal to, the second.
180 bool operator<=(SlotIndex other) const {
181 return getIndex() <= other.getIndex();
182 }
183
184 /// Compare two SlotIndex objects. Return true if the first index
185 /// is greater than the second.
186 bool operator>(SlotIndex other) const {
187 return getIndex() > other.getIndex();
188 }
189
190 /// Compare two SlotIndex objects. Return true if the first index
191 /// is greater than, or equal to, the second.
192 bool operator>=(SlotIndex other) const {
193 return getIndex() >= other.getIndex();
194 }
195
196 /// isSameInstr - Return true if A and B refer to the same instruction.
197 static bool isSameInstr(SlotIndex A, SlotIndex B) {
198 return A.lie.getPointer() == B.lie.getPointer();
199 }
200
201 /// isEarlierInstr - Return true if A refers to an instruction earlier than
202 /// B. This is equivalent to A < B && !isSameInstr(A, B).
203 static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
204 return A.listEntry()->getIndex() < B.listEntry()->getIndex();
205 }
206
207 /// Return true if A refers to the same instruction as B or an earlier one.
208 /// This is equivalent to !isEarlierInstr(B, A).
209 static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B) {
210 return !isEarlierInstr(B, A);
211 }
212
213 /// Return the distance from this index to the given one.
214 int distance(SlotIndex other) const {
215 return other.getIndex() - getIndex();
216 }
217
218 /// Return the scaled distance from this index to the given one, where all
219 /// slots on the same instruction have zero distance.
220 int getInstrDistance(SlotIndex other) const {
221 return (other.listEntry()->getIndex() - listEntry()->getIndex())
222 / Slot_Count;
223 }
224
225 /// isBlock - Returns true if this is a block boundary slot.
226 bool isBlock() const { return getSlot() == Slot_Block; }
4
Assuming the condition is false
5
Returning zero, which participates in a condition later
227
228 /// isEarlyClobber - Returns true if this is an early-clobber slot.
229 bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
230
231 /// isRegister - Returns true if this is a normal register use/def slot.
232 /// Note that early-clobber slots may also be used for uses and defs.
233 bool isRegister() const { return getSlot() == Slot_Register; }
234
235 /// isDead - Returns true if this is a dead def kill slot.
236 bool isDead() const { return getSlot() == Slot_Dead; }
237
238 /// Returns the base index for associated with this index. The base index
239 /// is the one associated with the Slot_Block slot for the instruction
240 /// pointed to by this index.
241 SlotIndex getBaseIndex() const {
242 return SlotIndex(listEntry(), Slot_Block);
243 }
244
245 /// Returns the boundary index for associated with this index. The boundary
246 /// index is the one associated with the Slot_Block slot for the instruction
247 /// pointed to by this index.
248 SlotIndex getBoundaryIndex() const {
249 return SlotIndex(listEntry(), Slot_Dead);
250 }
251
252 /// Returns the register use/def slot in the current instruction for a
253 /// normal or early-clobber def.
254 SlotIndex getRegSlot(bool EC = false) const {
255 return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
256 }
257
258 /// Returns the dead def kill slot for the current instruction.
259 SlotIndex getDeadSlot() const {
260 return SlotIndex(listEntry(), Slot_Dead);
261 }
262
263 /// Returns the next slot in the index list. This could be either the
264 /// next slot for the instruction pointed to by this index or, if this
265 /// index is a STORE, the first slot for the next instruction.
266 /// WARNING: This method is considerably more expensive than the methods
267 /// that return specific slots (getUseIndex(), etc). If you can - please
268 /// use one of those methods.
269 SlotIndex getNextSlot() const {
270 Slot s = getSlot();
271 if (s == Slot_Dead) {
272 return SlotIndex(&*++listEntry()->getIterator(), Slot_Block);
273 }
274 return SlotIndex(listEntry(), s + 1);
275 }
276
277 /// Returns the next index. This is the index corresponding to the this
278 /// index's slot, but for the next instruction.
279 SlotIndex getNextIndex() const {
280 return SlotIndex(&*++listEntry()->getIterator(), getSlot());
281 }
282
283 /// Returns the previous slot in the index list. This could be either the
284 /// previous slot for the instruction pointed to by this index or, if this
285 /// index is a Slot_Block, the last slot for the previous instruction.
286 /// WARNING: This method is considerably more expensive than the methods
287 /// that return specific slots (getUseIndex(), etc). If you can - please
288 /// use one of those methods.
289 SlotIndex getPrevSlot() const {
290 Slot s = getSlot();
291 if (s == Slot_Block) {
292 return SlotIndex(&*--listEntry()->getIterator(), Slot_Dead);
293 }
294 return SlotIndex(listEntry(), s - 1);
295 }
296
297 /// Returns the previous index. This is the index corresponding to this
298 /// index's slot, but for the previous instruction.
299 SlotIndex getPrevIndex() const {
300 return SlotIndex(&*--listEntry()->getIterator(), getSlot());
301 }
302 };
303
304 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
305 li.print(os);
306 return os;
307 }
308
309 using IdxMBBPair = std::pair<SlotIndex, MachineBasicBlock *>;
310
311 /// SlotIndexes pass.
312 ///
313 /// This pass assigns indexes to each instruction.
314 class SlotIndexes : public MachineFunctionPass {
315 private:
316 // IndexListEntry allocator.
317 BumpPtrAllocator ileAllocator;
318
319 using IndexList = ilist<IndexListEntry>;
320 IndexList indexList;
321
322 MachineFunction *mf;
323
324 using Mi2IndexMap = DenseMap<const MachineInstr *, SlotIndex>;
325 Mi2IndexMap mi2iMap;
326
327 /// MBBRanges - Map MBB number to (start, stop) indexes.
328 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
329
330 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
331 /// and MBB id.
332 SmallVector<IdxMBBPair, 8> idx2MBBMap;
333
334 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
335 IndexListEntry *entry =
336 static_cast<IndexListEntry *>(ileAllocator.Allocate(
337 sizeof(IndexListEntry), alignof(IndexListEntry)));
338
339 new (entry) IndexListEntry(mi, index);
340
341 return entry;
342 }
343
344 /// Renumber locally after inserting curItr.
345 void renumberIndexes(IndexList::iterator curItr);
346
347 public:
348 static char ID;
349
350 SlotIndexes();
351
352 ~SlotIndexes() override;
353
354 void getAnalysisUsage(AnalysisUsage &au) const override;
355 void releaseMemory() override;
356
357 bool runOnMachineFunction(MachineFunction &fn) override;
358
359 /// Dump the indexes.
360 void dump() const;
361
362 /// Repair indexes after adding and removing instructions.
363 void repairIndexesInRange(MachineBasicBlock *MBB,
364 MachineBasicBlock::iterator Begin,
365 MachineBasicBlock::iterator End);
366
367 /// Returns the zero index for this analysis.
368 SlotIndex getZeroIndex() {
369 assert(indexList.front().getIndex() == 0 && "First index is not 0?")(static_cast <bool> (indexList.front().getIndex() == 0 &&
"First index is not 0?") ? void (0) : __assert_fail ("indexList.front().getIndex() == 0 && \"First index is not 0?\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 369, __extension__ __PRETTY_FUNCTION__))
;
370 return SlotIndex(&indexList.front(), 0);
371 }
372
373 /// Returns the base index of the last slot in this analysis.
374 SlotIndex getLastIndex() {
375 return SlotIndex(&indexList.back(), 0);
376 }
377
378 /// Returns true if the given machine instr is mapped to an index,
379 /// otherwise returns false.
380 bool hasIndex(const MachineInstr &instr) const {
381 return mi2iMap.count(&instr);
382 }
383
384 /// Returns the base index for the given instruction.
385 SlotIndex getInstructionIndex(const MachineInstr &MI,
386 bool IgnoreBundle = false) const {
387 // Instructions inside a bundle have the same number as the bundle itself.
388 auto BundleStart = getBundleStart(MI.getIterator());
389 auto BundleEnd = getBundleEnd(MI.getIterator());
390 // Use the first non-debug instruction in the bundle to get SlotIndex.
391 const MachineInstr &BundleNonDebug =
392 IgnoreBundle ? MI
393 : *skipDebugInstructionsForward(BundleStart, BundleEnd);
394 assert(!BundleNonDebug.isDebugInstr() &&(static_cast <bool> (!BundleNonDebug.isDebugInstr() &&
"Could not use a debug instruction to query mi2iMap.") ? void
(0) : __assert_fail ("!BundleNonDebug.isDebugInstr() && \"Could not use a debug instruction to query mi2iMap.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 395, __extension__ __PRETTY_FUNCTION__))
395 "Could not use a debug instruction to query mi2iMap.")(static_cast <bool> (!BundleNonDebug.isDebugInstr() &&
"Could not use a debug instruction to query mi2iMap.") ? void
(0) : __assert_fail ("!BundleNonDebug.isDebugInstr() && \"Could not use a debug instruction to query mi2iMap.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 395, __extension__ __PRETTY_FUNCTION__))
;
396 Mi2IndexMap::const_iterator itr = mi2iMap.find(&BundleNonDebug);
397 assert(itr != mi2iMap.end() && "Instruction not found in maps.")(static_cast <bool> (itr != mi2iMap.end() && "Instruction not found in maps."
) ? void (0) : __assert_fail ("itr != mi2iMap.end() && \"Instruction not found in maps.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 397, __extension__ __PRETTY_FUNCTION__))
;
398 return itr->second;
399 }
400
401 /// Returns the instruction for the given index, or null if the given
402 /// index has no instruction associated with it.
403 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
404 return index.isValid() ? index.listEntry()->getInstr() : nullptr;
405 }
406
407 /// Returns the next non-null index, if one exists.
408 /// Otherwise returns getLastIndex().
409 SlotIndex getNextNonNullIndex(SlotIndex Index) {
410 IndexList::iterator I = Index.listEntry()->getIterator();
411 IndexList::iterator E = indexList.end();
412 while (++I != E)
413 if (I->getInstr())
414 return SlotIndex(&*I, Index.getSlot());
415 // We reached the end of the function.
416 return getLastIndex();
417 }
418
419 /// getIndexBefore - Returns the index of the last indexed instruction
420 /// before MI, or the start index of its basic block.
421 /// MI is not required to have an index.
422 SlotIndex getIndexBefore(const MachineInstr &MI) const {
423 const MachineBasicBlock *MBB = MI.getParent();
424 assert(MBB && "MI must be inserted in a basic block")(static_cast <bool> (MBB && "MI must be inserted in a basic block"
) ? void (0) : __assert_fail ("MBB && \"MI must be inserted in a basic block\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 424, __extension__ __PRETTY_FUNCTION__))
;
425 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
426 while (true) {
427 if (I == B)
428 return getMBBStartIdx(MBB);
429 --I;
430 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(&*I);
431 if (MapItr != mi2iMap.end())
432 return MapItr->second;
433 }
434 }
435
436 /// getIndexAfter - Returns the index of the first indexed instruction
437 /// after MI, or the end index of its basic block.
438 /// MI is not required to have an index.
439 SlotIndex getIndexAfter(const MachineInstr &MI) const {
440 const MachineBasicBlock *MBB = MI.getParent();
441 assert(MBB && "MI must be inserted in a basic block")(static_cast <bool> (MBB && "MI must be inserted in a basic block"
) ? void (0) : __assert_fail ("MBB && \"MI must be inserted in a basic block\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 441, __extension__ __PRETTY_FUNCTION__))
;
442 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
443 while (true) {
444 ++I;
445 if (I == E)
446 return getMBBEndIdx(MBB);
447 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(&*I);
448 if (MapItr != mi2iMap.end())
449 return MapItr->second;
450 }
451 }
452
453 /// Return the (start,end) range of the given basic block number.
454 const std::pair<SlotIndex, SlotIndex> &
455 getMBBRange(unsigned Num) const {
456 return MBBRanges[Num];
457 }
458
459 /// Return the (start,end) range of the given basic block.
460 const std::pair<SlotIndex, SlotIndex> &
461 getMBBRange(const MachineBasicBlock *MBB) const {
462 return getMBBRange(MBB->getNumber());
463 }
464
465 /// Returns the first index in the given basic block number.
466 SlotIndex getMBBStartIdx(unsigned Num) const {
467 return getMBBRange(Num).first;
468 }
469
470 /// Returns the first index in the given basic block.
471 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
472 return getMBBRange(mbb).first;
473 }
474
475 /// Returns the last index in the given basic block number.
476 SlotIndex getMBBEndIdx(unsigned Num) const {
477 return getMBBRange(Num).second;
478 }
479
480 /// Returns the last index in the given basic block.
481 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
482 return getMBBRange(mbb).second;
483 }
484
485 /// Iterator over the idx2MBBMap (sorted pairs of slot index of basic block
486 /// begin and basic block)
487 using MBBIndexIterator = SmallVectorImpl<IdxMBBPair>::const_iterator;
488
489 /// Move iterator to the next IdxMBBPair where the SlotIndex is greater or
490 /// equal to \p To.
491 MBBIndexIterator advanceMBBIndex(MBBIndexIterator I, SlotIndex To) const {
492 return std::partition_point(
493 I, idx2MBBMap.end(),
494 [=](const IdxMBBPair &IM) { return IM.first < To; });
495 }
496
497 /// Get an iterator pointing to the IdxMBBPair with the biggest SlotIndex
498 /// that is greater or equal to \p Idx.
499 MBBIndexIterator findMBBIndex(SlotIndex Idx) const {
500 return advanceMBBIndex(idx2MBBMap.begin(), Idx);
501 }
502
503 /// Returns an iterator for the begin of the idx2MBBMap.
504 MBBIndexIterator MBBIndexBegin() const {
505 return idx2MBBMap.begin();
506 }
507
508 /// Return an iterator for the end of the idx2MBBMap.
509 MBBIndexIterator MBBIndexEnd() const {
510 return idx2MBBMap.end();
511 }
512
513 /// Returns the basic block which the given index falls in.
514 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
515 if (MachineInstr *MI = getInstructionFromIndex(index))
516 return MI->getParent();
517
518 MBBIndexIterator I = findMBBIndex(index);
519 // Take the pair containing the index
520 MBBIndexIterator J =
521 ((I != MBBIndexEnd() && I->first > index) ||
522 (I == MBBIndexEnd() && !idx2MBBMap.empty())) ? std::prev(I) : I;
523
524 assert(J != MBBIndexEnd() && J->first <= index &&(static_cast <bool> (J != MBBIndexEnd() && J->
first <= index && index < getMBBEndIdx(J->second
) && "index does not correspond to an MBB") ? void (0
) : __assert_fail ("J != MBBIndexEnd() && J->first <= index && index < getMBBEndIdx(J->second) && \"index does not correspond to an MBB\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 526, __extension__ __PRETTY_FUNCTION__))
525 index < getMBBEndIdx(J->second) &&(static_cast <bool> (J != MBBIndexEnd() && J->
first <= index && index < getMBBEndIdx(J->second
) && "index does not correspond to an MBB") ? void (0
) : __assert_fail ("J != MBBIndexEnd() && J->first <= index && index < getMBBEndIdx(J->second) && \"index does not correspond to an MBB\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 526, __extension__ __PRETTY_FUNCTION__))
526 "index does not correspond to an MBB")(static_cast <bool> (J != MBBIndexEnd() && J->
first <= index && index < getMBBEndIdx(J->second
) && "index does not correspond to an MBB") ? void (0
) : __assert_fail ("J != MBBIndexEnd() && J->first <= index && index < getMBBEndIdx(J->second) && \"index does not correspond to an MBB\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 526, __extension__ __PRETTY_FUNCTION__))
;
527 return J->second;
528 }
529
530 /// Insert the given machine instruction into the mapping. Returns the
531 /// assigned index.
532 /// If Late is set and there are null indexes between mi's neighboring
533 /// instructions, create the new index after the null indexes instead of
534 /// before them.
535 SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late = false) {
536 assert(!MI.isInsideBundle() &&(static_cast <bool> (!MI.isInsideBundle() && "Instructions inside bundles should use bundle start's slot."
) ? void (0) : __assert_fail ("!MI.isInsideBundle() && \"Instructions inside bundles should use bundle start's slot.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 537, __extension__ __PRETTY_FUNCTION__))
537 "Instructions inside bundles should use bundle start's slot.")(static_cast <bool> (!MI.isInsideBundle() && "Instructions inside bundles should use bundle start's slot."
) ? void (0) : __assert_fail ("!MI.isInsideBundle() && \"Instructions inside bundles should use bundle start's slot.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 537, __extension__ __PRETTY_FUNCTION__))
;
538 assert(mi2iMap.find(&MI) == mi2iMap.end() && "Instr already indexed.")(static_cast <bool> (mi2iMap.find(&MI) == mi2iMap.end
() && "Instr already indexed.") ? void (0) : __assert_fail
("mi2iMap.find(&MI) == mi2iMap.end() && \"Instr already indexed.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 538, __extension__ __PRETTY_FUNCTION__))
;
539 // Numbering debug instructions could cause code generation to be
540 // affected by debug information.
541 assert(!MI.isDebugInstr() && "Cannot number debug instructions.")(static_cast <bool> (!MI.isDebugInstr() && "Cannot number debug instructions."
) ? void (0) : __assert_fail ("!MI.isDebugInstr() && \"Cannot number debug instructions.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 541, __extension__ __PRETTY_FUNCTION__))
;
542
543 assert(MI.getParent() != nullptr && "Instr must be added to function.")(static_cast <bool> (MI.getParent() != nullptr &&
"Instr must be added to function.") ? void (0) : __assert_fail
("MI.getParent() != nullptr && \"Instr must be added to function.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 543, __extension__ __PRETTY_FUNCTION__))
;
544
545 // Get the entries where MI should be inserted.
546 IndexList::iterator prevItr, nextItr;
547 if (Late) {
548 // Insert MI's index immediately before the following instruction.
549 nextItr = getIndexAfter(MI).listEntry()->getIterator();
550 prevItr = std::prev(nextItr);
551 } else {
552 // Insert MI's index immediately after the preceding instruction.
553 prevItr = getIndexBefore(MI).listEntry()->getIterator();
554 nextItr = std::next(prevItr);
555 }
556
557 // Get a number for the new instr, or 0 if there's no room currently.
558 // In the latter case we'll force a renumber later.
559 unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
560 unsigned newNumber = prevItr->getIndex() + dist;
561
562 // Insert a new list entry for MI.
563 IndexList::iterator newItr =
564 indexList.insert(nextItr, createEntry(&MI, newNumber));
565
566 // Renumber locally if we need to.
567 if (dist == 0)
568 renumberIndexes(newItr);
569
570 SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
571 mi2iMap.insert(std::make_pair(&MI, newIndex));
572 return newIndex;
573 }
574
575 /// Removes machine instruction (bundle) \p MI from the mapping.
576 /// This should be called before MachineInstr::eraseFromParent() is used to
577 /// remove a whole bundle or an unbundled instruction.
578 /// If \p AllowBundled is set then this can be used on a bundled
579 /// instruction; however, this exists to support handleMoveIntoBundle,
580 /// and in general removeSingleMachineInstrFromMaps should be used instead.
581 void removeMachineInstrFromMaps(MachineInstr &MI,
582 bool AllowBundled = false);
583
584 /// Removes a single machine instruction \p MI from the mapping.
585 /// This should be called before MachineInstr::eraseFromBundle() is used to
586 /// remove a single instruction (out of a bundle).
587 void removeSingleMachineInstrFromMaps(MachineInstr &MI);
588
589 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
590 /// maps used by register allocator. \returns the index where the new
591 /// instruction was inserted.
592 SlotIndex replaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI) {
593 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(&MI);
594 if (mi2iItr == mi2iMap.end())
595 return SlotIndex();
596 SlotIndex replaceBaseIndex = mi2iItr->second;
597 IndexListEntry *miEntry(replaceBaseIndex.listEntry());
598 assert(miEntry->getInstr() == &MI &&(static_cast <bool> (miEntry->getInstr() == &MI &&
"Mismatched instruction in index tables.") ? void (0) : __assert_fail
("miEntry->getInstr() == &MI && \"Mismatched instruction in index tables.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 599, __extension__ __PRETTY_FUNCTION__))
599 "Mismatched instruction in index tables.")(static_cast <bool> (miEntry->getInstr() == &MI &&
"Mismatched instruction in index tables.") ? void (0) : __assert_fail
("miEntry->getInstr() == &MI && \"Mismatched instruction in index tables.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 599, __extension__ __PRETTY_FUNCTION__))
;
600 miEntry->setInstr(&NewMI);
601 mi2iMap.erase(mi2iItr);
602 mi2iMap.insert(std::make_pair(&NewMI, replaceBaseIndex));
603 return replaceBaseIndex;
604 }
605
606 /// Add the given MachineBasicBlock into the maps.
607 /// If it contains any instructions then they must already be in the maps.
608 /// This is used after a block has been split by moving some suffix of its
609 /// instructions into a newly created block.
610 void insertMBBInMaps(MachineBasicBlock *mbb) {
611 assert(mbb != &mbb->getParent()->front() &&(static_cast <bool> (mbb != &mbb->getParent()->
front() && "Can't insert a new block at the beginning of a function."
) ? void (0) : __assert_fail ("mbb != &mbb->getParent()->front() && \"Can't insert a new block at the beginning of a function.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 612, __extension__ __PRETTY_FUNCTION__))
612 "Can't insert a new block at the beginning of a function.")(static_cast <bool> (mbb != &mbb->getParent()->
front() && "Can't insert a new block at the beginning of a function."
) ? void (0) : __assert_fail ("mbb != &mbb->getParent()->front() && \"Can't insert a new block at the beginning of a function.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 612, __extension__ __PRETTY_FUNCTION__))
;
613 auto prevMBB = std::prev(MachineFunction::iterator(mbb));
614
615 // Create a new entry to be used for the start of mbb and the end of
616 // prevMBB.
617 IndexListEntry *startEntry = createEntry(nullptr, 0);
618 IndexListEntry *endEntry = getMBBEndIdx(&*prevMBB).listEntry();
619 IndexListEntry *insEntry =
620 mbb->empty() ? endEntry
621 : getInstructionIndex(mbb->front()).listEntry();
622 IndexList::iterator newItr =
623 indexList.insert(insEntry->getIterator(), startEntry);
624
625 SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
626 SlotIndex endIdx(endEntry, SlotIndex::Slot_Block);
627
628 MBBRanges[prevMBB->getNumber()].second = startIdx;
629
630 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&(static_cast <bool> (unsigned(mbb->getNumber()) == MBBRanges
.size() && "Blocks must be added in order") ? void (0
) : __assert_fail ("unsigned(mbb->getNumber()) == MBBRanges.size() && \"Blocks must be added in order\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 631, __extension__ __PRETTY_FUNCTION__))
631 "Blocks must be added in order")(static_cast <bool> (unsigned(mbb->getNumber()) == MBBRanges
.size() && "Blocks must be added in order") ? void (0
) : __assert_fail ("unsigned(mbb->getNumber()) == MBBRanges.size() && \"Blocks must be added in order\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 631, __extension__ __PRETTY_FUNCTION__))
;
632 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
633 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
634
635 renumberIndexes(newItr);
636 llvm::sort(idx2MBBMap, less_first());
637 }
638 };
639
640 // Specialize IntervalMapInfo for half-open slot index intervals.
641 template <>
642 struct IntervalMapInfo<SlotIndex> : IntervalMapHalfOpenInfo<SlotIndex> {
643 };
644
645} // end namespace llvm
646
647#endif // LLVM_CODEGEN_SLOTINDEXES_H

/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/Register.h

1//===-- llvm/CodeGen/Register.h ---------------------------------*- C++ -*-===//
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#ifndef LLVM_CODEGEN_REGISTER_H
10#define LLVM_CODEGEN_REGISTER_H
11
12#include "llvm/MC/MCRegister.h"
13#include <cassert>
14
15namespace llvm {
16
17/// Wrapper class representing virtual and physical registers. Should be passed
18/// by value.
19class Register {
20 unsigned Reg;
21
22public:
23 constexpr Register(unsigned Val = 0): Reg(Val) {}
24 constexpr Register(MCRegister Val): Reg(Val) {}
25
26 // Register numbers can represent physical registers, virtual registers, and
27 // sometimes stack slots. The unsigned values are divided into these ranges:
28 //
29 // 0 Not a register, can be used as a sentinel.
30 // [1;2^30) Physical registers assigned by TableGen.
31 // [2^30;2^31) Stack slots. (Rarely used.)
32 // [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
33 //
34 // Further sentinels can be allocated from the small negative integers.
35 // DenseMapInfo<unsigned> uses -1u and -2u.
36 static_assert(std::numeric_limits<decltype(Reg)>::max() >= 0xFFFFFFFF,
37 "Reg isn't large enough to hold full range.");
38
39 /// isStackSlot - Sometimes it is useful the be able to store a non-negative
40 /// frame index in a variable that normally holds a register. isStackSlot()
41 /// returns true if Reg is in the range used for stack slots.
42 ///
43 /// FIXME: remove in favor of member.
44 static bool isStackSlot(unsigned Reg) {
45 return MCRegister::isStackSlot(Reg);
46 }
47
48 /// Return true if this is a stack slot.
49 bool isStack() const { return MCRegister::isStackSlot(Reg); }
50
51 /// Compute the frame index from a register value representing a stack slot.
52 static int stackSlot2Index(Register Reg) {
53 assert(Reg.isStack() && "Not a stack slot")(static_cast <bool> (Reg.isStack() && "Not a stack slot"
) ? void (0) : __assert_fail ("Reg.isStack() && \"Not a stack slot\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/Register.h"
, 53, __extension__ __PRETTY_FUNCTION__))
;
54 return int(Reg - MCRegister::FirstStackSlot);
55 }
56
57 /// Convert a non-negative frame index to a stack slot register value.
58 static Register index2StackSlot(int FI) {
59 assert(FI >= 0 && "Cannot hold a negative frame index.")(static_cast <bool> (FI >= 0 && "Cannot hold a negative frame index."
) ? void (0) : __assert_fail ("FI >= 0 && \"Cannot hold a negative frame index.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/Register.h"
, 59, __extension__ __PRETTY_FUNCTION__))
;
60 return Register(FI + MCRegister::FirstStackSlot);
61 }
62
63 /// Return true if the specified register number is in
64 /// the physical register namespace.
65 static bool isPhysicalRegister(unsigned Reg) {
66 return MCRegister::isPhysicalRegister(Reg);
67 }
68
69 /// Return true if the specified register number is in
70 /// the virtual register namespace.
71 static bool isVirtualRegister(unsigned Reg) {
72 return Reg & MCRegister::VirtualRegFlag && !isStackSlot(Reg);
73 }
74
75 /// Convert a virtual register number to a 0-based index.
76 /// The first virtual register in a function will get the index 0.
77 static unsigned virtReg2Index(Register Reg) {
78 assert(isVirtualRegister(Reg) && "Not a virtual register")(static_cast <bool> (isVirtualRegister(Reg) && "Not a virtual register"
) ? void (0) : __assert_fail ("isVirtualRegister(Reg) && \"Not a virtual register\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/Register.h"
, 78, __extension__ __PRETTY_FUNCTION__))
;
79 return Reg & ~MCRegister::VirtualRegFlag;
80 }
81
82 /// Convert a 0-based index to a virtual register number.
83 /// This is the inverse operation of VirtReg2IndexFunctor below.
84 static Register index2VirtReg(unsigned Index) {
85 assert(Index < (1u << 31) && "Index too large for virtual register range.")(static_cast <bool> (Index < (1u << 31) &&
"Index too large for virtual register range.") ? void (0) : __assert_fail
("Index < (1u << 31) && \"Index too large for virtual register range.\""
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/Register.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return Index | MCRegister::VirtualRegFlag;
87 }
88
89 /// Return true if the specified register number is in the virtual register
90 /// namespace.
91 bool isVirtual() const {
92 return isVirtualRegister(Reg);
93 }
94
95 /// Return true if the specified register number is in the physical register
96 /// namespace.
97 bool isPhysical() const {
98 return isPhysicalRegister(Reg);
99 }
100
101 /// Convert a virtual register number to a 0-based index. The first virtual
102 /// register in a function will get the index 0.
103 unsigned virtRegIndex() const {
104 return virtReg2Index(Reg);
105 }
106
107 constexpr operator unsigned() const {
108 return Reg;
109 }
110
111 unsigned id() const { return Reg; }
112
113 operator MCRegister() const {
114 return MCRegister(Reg);
115 }
116
117 /// Utility to check-convert this value to a MCRegister. The caller is
118 /// expected to have already validated that this Register is, indeed,
119 /// physical.
120 MCRegister asMCReg() const {
121 assert(Reg == MCRegister::NoRegister ||(static_cast <bool> (Reg == MCRegister::NoRegister || MCRegister
::isPhysicalRegister(Reg)) ? void (0) : __assert_fail ("Reg == MCRegister::NoRegister || MCRegister::isPhysicalRegister(Reg)"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/Register.h"
, 122, __extension__ __PRETTY_FUNCTION__))
122 MCRegister::isPhysicalRegister(Reg))(static_cast <bool> (Reg == MCRegister::NoRegister || MCRegister
::isPhysicalRegister(Reg)) ? void (0) : __assert_fail ("Reg == MCRegister::NoRegister || MCRegister::isPhysicalRegister(Reg)"
, "/build/llvm-toolchain-snapshot-13~++20210711100610+f0393deb3367/llvm/include/llvm/CodeGen/Register.h"
, 122, __extension__ __PRETTY_FUNCTION__))
;
123 return MCRegister(Reg);
124 }
125
126 bool isValid() const { return Reg != MCRegister::NoRegister; }
127
128 /// Comparisons between register objects
129 bool operator==(const Register &Other) const { return Reg == Other.Reg; }
20
Assuming 'Reg' is not equal to 'Other.Reg'
21
Returning zero, which participates in a condition later
130 bool operator!=(const Register &Other) const { return Reg != Other.Reg; }
131 bool operator==(const MCRegister &Other) const { return Reg == Other.id(); }
132 bool operator!=(const MCRegister &Other) const { return Reg != Other.id(); }
133
134 /// Comparisons against register constants. E.g.
135 /// * R == AArch64::WZR
136 /// * R == 0
137 /// * R == VirtRegMap::NO_PHYS_REG
138 bool operator==(unsigned Other) const { return Reg == Other; }
139 bool operator!=(unsigned Other) const { return Reg != Other; }
140 bool operator==(int Other) const { return Reg == unsigned(Other); }
141 bool operator!=(int Other) const { return Reg != unsigned(Other); }
142 // MSVC requires that we explicitly declare these two as well.
143 bool operator==(MCPhysReg Other) const { return Reg == unsigned(Other); }
144 bool operator!=(MCPhysReg Other) const { return Reg != unsigned(Other); }
145};
146
147// Provide DenseMapInfo for Register
148template<> struct DenseMapInfo<Register> {
149 static inline unsigned getEmptyKey() {
150 return DenseMapInfo<unsigned>::getEmptyKey();
151 }
152 static inline unsigned getTombstoneKey() {
153 return DenseMapInfo<unsigned>::getTombstoneKey();
154 }
155 static unsigned getHashValue(const Register &Val) {
156 return DenseMapInfo<unsigned>::getHashValue(Val.id());
157 }
158 static bool isEqual(const Register &LHS, const Register &RHS) {
159 return DenseMapInfo<unsigned>::isEqual(LHS.id(), RHS.id());
160 }
161};
162
163}
164
165#endif // LLVM_CODEGEN_REGISTER_H