blob: 052573a35c428132f9a12dde327f636a70a59574 [file] [log] [blame]
David Greene25133302007-06-08 17:18:56 +00001//===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple register coalescing pass that attempts to
11// aggressively coalesce every register copy that it can.
12//
13//===----------------------------------------------------------------------===//
14
Evan Cheng3b1f55e2007-07-31 22:37:44 +000015#define DEBUG_TYPE "regcoalescing"
David Greene25133302007-06-08 17:18:56 +000016#include "llvm/CodeGen/SimpleRegisterCoalescing.h"
17#include "llvm/CodeGen/LiveIntervalAnalysis.h"
18#include "VirtRegMap.h"
19#include "llvm/Value.h"
20#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/CodeGen/LiveVariables.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/CodeGen/SSARegMap.h"
26#include "llvm/Target/MRegisterInfo.h"
27#include "llvm/Target/TargetInstrInfo.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/STLExtras.h"
34#include <algorithm>
35#include <cmath>
36using namespace llvm;
37
38STATISTIC(numJoins , "Number of interval joins performed");
39STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
40STATISTIC(numAborts , "Number of times interval joining aborted");
41
42char SimpleRegisterCoalescing::ID = 0;
43namespace {
44 static cl::opt<bool>
45 EnableJoining("join-liveintervals",
Gabor Greife510b3a2007-07-09 12:00:59 +000046 cl::desc("Coalesce copies (default=true)"),
David Greene25133302007-06-08 17:18:56 +000047 cl::init(true));
48
49 RegisterPass<SimpleRegisterCoalescing>
Chris Lattnere76fad22007-08-05 18:45:33 +000050 X("simple-register-coalescing", "Simple Register Coalescing");
David Greene25133302007-06-08 17:18:56 +000051}
52
53const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
54
55void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
56 //AU.addPreserved<LiveVariables>();
57 AU.addPreserved<LiveIntervals>();
58 AU.addPreservedID(PHIEliminationID);
59 AU.addPreservedID(TwoAddressInstructionPassID);
60 AU.addRequired<LiveVariables>();
61 AU.addRequired<LiveIntervals>();
62 AU.addRequired<LoopInfo>();
63 MachineFunctionPass::getAnalysisUsage(AU);
64}
65
Gabor Greife510b3a2007-07-09 12:00:59 +000066/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000067/// being the source and IntB being the dest, thus this defines a value number
68/// in IntB. If the source value number (in IntA) is defined by a copy from B,
69/// see if we can merge these two pieces of B into a single value number,
70/// eliminating a copy. For example:
71///
72/// A3 = B0
73/// ...
74/// B1 = A3 <- this copy
75///
76/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
77/// value number to be replaced with B0 (which simplifies the B liveinterval).
78///
79/// This returns true if an interval was modified.
80///
81bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
82 MachineInstr *CopyMI) {
83 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
84
85 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
86 // the example above.
87 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +000088 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +000089
90 // Get the location that B is defined at. Two options: either this value has
91 // an unknown definition point or it is defined at CopyIdx. If unknown, we
92 // can't process it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +000093 if (!BValNo->reg) return false;
94 assert(BValNo->def == CopyIdx &&
David Greene25133302007-06-08 17:18:56 +000095 "Copy doesn't define the value?");
96
97 // AValNo is the value number in A that defines the copy, A0 in the example.
98 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +000099 VNInfo *AValNo = AValLR->valno;
David Greene25133302007-06-08 17:18:56 +0000100
101 // If AValNo is defined as a copy from IntB, we can potentially process this.
102
103 // Get the instruction that defines this value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000104 unsigned SrcReg = AValNo->reg;
David Greene25133302007-06-08 17:18:56 +0000105 if (!SrcReg) return false; // Not defined by a copy.
106
107 // If the value number is not defined by a copy instruction, ignore it.
108
109 // If the source register comes from an interval other than IntB, we can't
110 // handle this.
111 if (rep(SrcReg) != IntB.reg) return false;
112
113 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000114 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
David Greene25133302007-06-08 17:18:56 +0000115
116 // Make sure that the end of the live range is inside the same block as
117 // CopyMI.
118 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
119 if (!ValLREndInst ||
120 ValLREndInst->getParent() != CopyMI->getParent()) return false;
121
122 // Okay, we now know that ValLR ends in the same block that the CopyMI
123 // live-range starts. If there are no intervening live ranges between them in
124 // IntB, we can merge them.
125 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000126
127 // If a live interval is a physical register, conservatively check if any
128 // of its sub-registers is overlapping the live interval of the virtual
129 // register. If so, do not coalesce.
130 if (MRegisterInfo::isPhysicalRegister(IntB.reg) &&
131 *mri_->getSubRegisters(IntB.reg)) {
132 for (const unsigned* SR = mri_->getSubRegisters(IntB.reg); *SR; ++SR)
133 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
134 DOUT << "Interfere with sub-register ";
135 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
136 return false;
137 }
138 }
David Greene25133302007-06-08 17:18:56 +0000139
140 DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
141
Evan Chenga8d94f12007-08-07 23:49:57 +0000142 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000143 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000144 // that defines this value #'. Update the the valnum with the new defining
145 // instruction #.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000146 BValNo->def = FillerStart;
147 BValNo->reg = 0;
David Greene25133302007-06-08 17:18:56 +0000148
149 // Okay, we can merge them. We need to insert a new liverange:
150 // [ValLR.end, BLR.begin) of either value number, then we merge the
151 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000152 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
153
154 // If the IntB live range is assigned to a physical register, and if that
155 // physreg has aliases,
156 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
157 // Update the liveintervals of sub-registers.
158 for (const unsigned *AS = mri_->getSubRegisters(IntB.reg); *AS; ++AS) {
159 LiveInterval &AliasLI = li_->getInterval(*AS);
160 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chenga8d94f12007-08-07 23:49:57 +0000161 AliasLI.getNextValue(FillerStart, 0)));
David Greene25133302007-06-08 17:18:56 +0000162 }
163 }
164
165 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000166 if (BValNo != ValLR->valno)
167 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
David Greene25133302007-06-08 17:18:56 +0000168 DOUT << " result = "; IntB.print(DOUT, mri_);
169 DOUT << "\n";
170
171 // If the source instruction was killing the source register before the
172 // merge, unset the isKill marker given the live range has been extended.
173 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
174 if (UIdx != -1)
175 ValLREndInst->getOperand(UIdx).unsetIsKill();
176
177 // Finally, delete the copy instruction.
178 li_->RemoveMachineInstrFromMaps(CopyMI);
179 CopyMI->eraseFromParent();
180 ++numPeep;
181 return true;
182}
183
184/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
185/// which are the src/dst of the copy instruction CopyMI. This returns true
Gabor Greife510b3a2007-07-09 12:00:59 +0000186/// if the copy was successfully coalesced away, or if it is never possible
187/// to coalesce this copy, due to register constraints. It returns
188/// false if it is not currently possible to coalesce this interval, but
189/// it may be possible if other things get coalesced.
David Greene25133302007-06-08 17:18:56 +0000190bool SimpleRegisterCoalescing::JoinCopy(MachineInstr *CopyMI,
191 unsigned SrcReg, unsigned DstReg, bool PhysOnly) {
192 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
193
194 // Get representative registers.
195 unsigned repSrcReg = rep(SrcReg);
196 unsigned repDstReg = rep(DstReg);
197
198 // If they are already joined we continue.
199 if (repSrcReg == repDstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000200 DOUT << "\tCopy already coalesced.\n";
201 return true; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000202 }
203
204 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
205 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
206 if (PhysOnly && !SrcIsPhys && !DstIsPhys)
207 // Only joining physical registers with virtual registers in this round.
208 return true;
209
210 // If they are both physical registers, we cannot join them.
211 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000212 DOUT << "\tCan not coalesce physregs.\n";
213 return true; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000214 }
215
216 // We only join virtual registers with allocatable physical registers.
217 if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
218 DOUT << "\tSrc reg is unallocatable physreg.\n";
Gabor Greife510b3a2007-07-09 12:00:59 +0000219 return true; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000220 }
221 if (DstIsPhys && !allocatableRegs_[repDstReg]) {
222 DOUT << "\tDst reg is unallocatable physreg.\n";
Gabor Greife510b3a2007-07-09 12:00:59 +0000223 return true; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000224 }
225
226 // If they are not of the same register class, we cannot join them.
227 if (differingRegisterClasses(repSrcReg, repDstReg)) {
228 DOUT << "\tSrc/Dest are different register classes.\n";
Gabor Greife510b3a2007-07-09 12:00:59 +0000229 return true; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000230 }
231
232 LiveInterval &SrcInt = li_->getInterval(repSrcReg);
233 LiveInterval &DstInt = li_->getInterval(repDstReg);
234 assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
235 "Register mapping is horribly broken!");
236
237 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
238 DOUT << " and "; DstInt.print(DOUT, mri_);
239 DOUT << ": ";
240
241 // Check if it is necessary to propagate "isDead" property before intervals
242 // are joined.
243 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
244 bool isDead = mopd->isDead();
245 bool isShorten = false;
246 unsigned SrcStart = 0, RemoveStart = 0;
247 unsigned SrcEnd = 0, RemoveEnd = 0;
248 if (isDead) {
249 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
250 LiveInterval::iterator SrcLR =
251 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
252 RemoveStart = SrcStart = SrcLR->start;
253 RemoveEnd = SrcEnd = SrcLR->end;
254 // The instruction which defines the src is only truly dead if there are
255 // no intermediate uses and there isn't a use beyond the copy.
256 // FIXME: find the last use, mark is kill and shorten the live range.
257 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
258 isDead = false;
259 } else {
260 MachineOperand *MOU;
261 MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
262 if (LastUse) {
263 // Shorten the liveinterval to the end of last use.
264 MOU->setIsKill();
265 isDead = false;
266 isShorten = true;
267 RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
268 RemoveEnd = SrcEnd;
269 } else {
270 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
271 if (SrcMI) {
272 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
273 if (mops)
274 // A dead def should have a single cycle interval.
275 ++RemoveStart;
276 }
277 }
278 }
279 }
280
281 // We need to be careful about coalescing a source physical register with a
282 // virtual register. Once the coalescing is done, it cannot be broken and
283 // these are not spillable! If the destination interval uses are far away,
284 // think twice about coalescing them!
285 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys)) {
286 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
287 unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
288 unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
289 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(JoinVReg);
290 unsigned Threshold = allocatableRCRegs_[RC].count();
291
292 // If the virtual register live interval is long has it has low use desity,
293 // do not join them, instead mark the physical register as its allocation
294 // preference.
295 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
296 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
297 if (Length > Threshold &&
298 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
299 JoinVInt.preference = JoinPReg;
300 ++numAborts;
301 DOUT << "\tMay tie down a physical register, abort!\n";
302 return false;
303 }
304 }
305
306 // Okay, attempt to join these two intervals. On failure, this returns false.
307 // Otherwise, if one of the intervals being joined is a physreg, this method
308 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
309 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000310 bool Swapped = false;
311 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
David Greene25133302007-06-08 17:18:56 +0000312 if (isDead) {
313 // Result of the copy is dead. Propagate this property.
314 if (SrcStart == 0) {
315 assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
316 "Live-in must be a physical register!");
317 // Live-in to the function but dead. Remove it from entry live-in set.
318 // JoinIntervals may end up swapping the two intervals.
319 mf_->begin()->removeLiveIn(repSrcReg);
320 } else {
321 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
322 if (SrcMI) {
323 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
324 if (mops)
325 mops->setIsDead();
326 }
327 }
328 }
329
330 if (isShorten || isDead) {
Evan Chengccb36a42007-08-12 01:26:19 +0000331 // Shorten the destination live interval.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000332 if (Swapped)
333 SrcInt.removeRange(RemoveStart, RemoveEnd);
David Greene25133302007-06-08 17:18:56 +0000334 }
335 } else {
Gabor Greife510b3a2007-07-09 12:00:59 +0000336 // Coalescing failed.
David Greene25133302007-06-08 17:18:56 +0000337
338 // If we can eliminate the copy without merging the live ranges, do so now.
339 if (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI))
340 return true;
341
342 // Otherwise, we are unable to join the intervals.
343 DOUT << "Interference!\n";
344 return false;
345 }
346
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000347 LiveInterval *ResSrcInt = &SrcInt;
348 LiveInterval *ResDstInt = &DstInt;
349 if (Swapped) {
David Greene25133302007-06-08 17:18:56 +0000350 std::swap(repSrcReg, repDstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000351 std::swap(ResSrcInt, ResDstInt);
352 }
David Greene25133302007-06-08 17:18:56 +0000353 assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
354 "LiveInterval::join didn't work right!");
355
356 // If we're about to merge live ranges into a physical register live range,
357 // we have to update any aliased register's live ranges to indicate that they
358 // have clobbered values for this range.
359 if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
360 // Unset unnecessary kills.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000361 if (!ResDstInt->containsOneValue()) {
362 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
363 E = ResSrcInt->end(); I != E; ++I)
David Greene25133302007-06-08 17:18:56 +0000364 unsetRegisterKills(I->start, I->end, repDstReg);
365 }
366
367 // Update the liveintervals of sub-registers.
368 for (const unsigned *AS = mri_->getSubRegisters(repDstReg); *AS; ++AS)
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000369 li_->getInterval(*AS).MergeInClobberRanges(*ResSrcInt);
David Greene25133302007-06-08 17:18:56 +0000370 } else {
371 // Merge use info if the destination is a virtual register.
372 LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
373 LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
374 dVI.NumUses += sVI.NumUses;
375 }
376
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000377 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, mri_);
David Greene25133302007-06-08 17:18:56 +0000378 DOUT << "\n";
379
380 // Remember these liveintervals have been joined.
381 JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
382 if (MRegisterInfo::isVirtualRegister(repDstReg))
383 JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
384
Evan Cheng273288c2007-07-18 23:34:48 +0000385 // repSrcReg is guarateed to be the register whose live interval that is
386 // being merged.
David Greene25133302007-06-08 17:18:56 +0000387 li_->removeInterval(repSrcReg);
388 r2rMap_[repSrcReg] = repDstReg;
389
390 // Finally, delete the copy instruction.
391 li_->RemoveMachineInstrFromMaps(CopyMI);
392 CopyMI->eraseFromParent();
393 ++numPeep;
394 ++numJoins;
395 return true;
396}
397
398/// ComputeUltimateVN - Assuming we are going to join two live intervals,
399/// compute what the resultant value numbers for each value in the input two
400/// ranges will be. This is complicated by copies between the two which can
401/// and will commonly cause multiple value numbers to be merged into one.
402///
403/// VN is the value number that we're trying to resolve. InstDefiningValue
404/// keeps track of the new InstDefiningValue assignment for the result
405/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
406/// whether a value in this or other is a copy from the opposite set.
407/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
408/// already been assigned.
409///
410/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
411/// contains the value number the copy is from.
412///
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000413static unsigned ComputeUltimateVN(VNInfo *VNI,
414 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +0000415 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
416 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +0000417 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000418 SmallVector<int, 16> &OtherValNoAssignments) {
419 unsigned VN = VNI->id;
420
David Greene25133302007-06-08 17:18:56 +0000421 // If the VN has already been computed, just return it.
422 if (ThisValNoAssignments[VN] >= 0)
423 return ThisValNoAssignments[VN];
424// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000425
David Greene25133302007-06-08 17:18:56 +0000426 // If this val is not a copy from the other val, then it must be a new value
427 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +0000428 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +0000429 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000430 NewVNInfo.push_back(VNI);
431 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +0000432 }
Evan Chengc14b1442007-08-31 08:04:17 +0000433 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +0000434
435 // Otherwise, this *is* a copy from the RHS. If the other side has already
436 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000437 if (OtherValNoAssignments[OtherValNo->id] >= 0)
438 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +0000439
440 // Mark this value number as currently being computed, then ask what the
441 // ultimate value # of the other value is.
442 ThisValNoAssignments[VN] = -2;
443 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000444 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
445 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000446 return ThisValNoAssignments[VN] = UltimateVN;
447}
448
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000449static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +0000450 return std::find(V.begin(), V.end(), Val) != V.end();
451}
452
453/// SimpleJoin - Attempt to joint the specified interval into this one. The
454/// caller of this method must guarantee that the RHS only contains a single
455/// value number and that the RHS is not defined by a copy from this
456/// interval. This returns false if the intervals are not joinable, or it
457/// joins them and returns true.
458bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
459 assert(RHS.containsOneValue());
460
461 // Some number (potentially more than one) value numbers in the current
462 // interval may be defined as copies from the RHS. Scan the overlapping
463 // portions of the LHS and RHS, keeping track of this and looking for
464 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +0000465 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +0000466
467 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
468 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
469
470 if (LHSIt->start < RHSIt->start) {
471 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
472 if (LHSIt != LHS.begin()) --LHSIt;
473 } else if (RHSIt->start < LHSIt->start) {
474 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
475 if (RHSIt != RHS.begin()) --RHSIt;
476 }
477
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000478 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +0000479
480 while (1) {
481 // Determine if these live intervals overlap.
482 bool Overlaps = false;
483 if (LHSIt->start <= RHSIt->start)
484 Overlaps = LHSIt->end > RHSIt->start;
485 else
486 Overlaps = RHSIt->end > LHSIt->start;
487
488 // If the live intervals overlap, there are two interesting cases: if the
489 // LHS interval is defined by a copy from the RHS, it's ok and we record
490 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +0000491 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +0000492 if (Overlaps) {
493 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000494 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +0000495 // Copy from the RHS?
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000496 unsigned SrcReg = LHSIt->valno->reg;
David Greene25133302007-06-08 17:18:56 +0000497 if (rep(SrcReg) != RHS.reg)
498 return false; // Nope, bail out.
499
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000500 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +0000501 }
502
503 // We know this entire LHS live range is okay, so skip it now.
504 if (++LHSIt == LHSEnd) break;
505 continue;
506 }
507
508 if (LHSIt->end < RHSIt->end) {
509 if (++LHSIt == LHSEnd) break;
510 } else {
511 // One interesting case to check here. It's possible that we have
512 // something like "X3 = Y" which defines a new value number in the LHS,
513 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +0000514 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +0000515 // the live ranges don't actually overlap.
516 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000517 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +0000518 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +0000519 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +0000520 if (++LHSIt == LHSEnd) break;
521 } else {
522 // Otherwise, if this is a copy from the RHS, mark it as being merged
523 // in.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000524 if (rep(LHSIt->valno->reg) == RHS.reg) {
525 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +0000526
527 // We know this entire LHS live range is okay, so skip it now.
528 if (++LHSIt == LHSEnd) break;
529 }
530 }
531 }
532
533 if (++RHSIt == RHSEnd) break;
534 }
535 }
536
Gabor Greife510b3a2007-07-09 12:00:59 +0000537 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +0000538 // the value numbers in EliminatedLHSVals will all be merged together. Since
539 // the most common case is that EliminatedLHSVals has a single number, we
540 // optimize for it: if there is more than one value, we merge them all into
541 // the lowest numbered one, then handle the interval as if we were merging
542 // with one value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000543 VNInfo *LHSValNo;
David Greene25133302007-06-08 17:18:56 +0000544 if (EliminatedLHSVals.size() > 1) {
545 // Loop through all the equal value numbers merging them into the smallest
546 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000547 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +0000548 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000549 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +0000550 // Merge the current notion of the smallest into the smaller one.
551 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
552 Smallest = EliminatedLHSVals[i];
553 } else {
554 // Merge into the smallest.
555 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
556 }
557 }
558 LHSValNo = Smallest;
559 } else {
560 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
561 LHSValNo = EliminatedLHSVals[0];
562 }
563
564 // Okay, now that there is a single LHS value number that we're merging the
565 // RHS into, update the value number info for the LHS to indicate that the
566 // value number is defined where the RHS value number was.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000567 const VNInfo *VNI = RHS.getFirstValNumInfo();
568 LHSValNo->def = VNI->def;
569 LHSValNo->reg = VNI->reg;
David Greene25133302007-06-08 17:18:56 +0000570
571 // Okay, the final step is to loop over the RHS live intervals, adding them to
572 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000573 LHS.addKills(*LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +0000574 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +0000575 LHS.weight += RHS.weight;
576 if (RHS.preference && !LHS.preference)
577 LHS.preference = RHS.preference;
578
579 return true;
580}
581
582/// JoinIntervals - Attempt to join these two intervals. On failure, this
583/// returns false. Otherwise, if one of the intervals being joined is a
584/// physreg, this method always canonicalizes LHS to be it. The output
585/// "RHS" will not have been modified, so we can use this information
586/// below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000587bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
588 LiveInterval &RHS, bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +0000589 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +0000590 // coalesced.
David Greene25133302007-06-08 17:18:56 +0000591 SmallVector<int, 16> LHSValNoAssignments;
592 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +0000593 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
594 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000595 SmallVector<VNInfo*, 16> NewVNInfo;
David Greene25133302007-06-08 17:18:56 +0000596
597 // If a live interval is a physical register, conservatively check if any
598 // of its sub-registers is overlapping the live interval of the virtual
599 // register. If so, do not coalesce.
600 if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
601 *mri_->getSubRegisters(LHS.reg)) {
602 for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
603 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
604 DOUT << "Interfere with sub-register ";
605 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
606 return false;
607 }
608 } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
609 *mri_->getSubRegisters(RHS.reg)) {
610 for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
611 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
612 DOUT << "Interfere with sub-register ";
613 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
614 return false;
615 }
616 }
617
618 // Compute ultimate value numbers for the LHS and RHS values.
619 if (RHS.containsOneValue()) {
620 // Copies from a liveinterval with a single value are simple to handle and
621 // very common, handle the special case here. This is important, because
622 // often RHS is small and LHS is large (e.g. a physreg).
623
624 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +0000625 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +0000626 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000627 VNInfo *RHSValNoInfo = NULL;
Evan Chengc14b1442007-08-31 08:04:17 +0000628 VNInfo *RHSValNoInfo0 = RHS.getFirstValNumInfo();
629 unsigned RHSSrcReg = RHSValNoInfo0->reg;
David Greene25133302007-06-08 17:18:56 +0000630 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
631 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +0000632 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +0000633 // can't swap the LHS/RHS intervals though.
634 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
635 return SimpleJoin(LHS, RHS);
636 } else {
Evan Chengc14b1442007-08-31 08:04:17 +0000637 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +0000638 }
639 } else {
640 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +0000641 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000642 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000643 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +0000644 }
645
646 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
647 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000648 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +0000649
650 // Okay, *all* of the values in LHS that are defined as a copy from RHS
651 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000652 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
653 i != e; ++i) {
654 VNInfo *VNI = *i;
655 unsigned VN = VNI->id;
656 if (unsigned LHSSrcReg = VNI->reg) {
David Greene25133302007-06-08 17:18:56 +0000657 if (rep(LHSSrcReg) != RHS.reg) {
658 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +0000659 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000660 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +0000661 LHSValNoAssignments[VN] = VN;
662 } else if (RHSValID == -1) {
663 // Otherwise, it is a copy from the RHS, and we don't already have a
664 // value# for it. Keep the current value number, but remember it.
665 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000666 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +0000667 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +0000668 } else {
669 // Otherwise, use the specified value #.
670 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000671 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
672 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +0000673 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000674 }
David Greene25133302007-06-08 17:18:56 +0000675 }
676 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000677 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +0000678 LHSValNoAssignments[VN] = VN;
679 }
680 }
681
682 assert(RHSValID != -1 && "Didn't find value #?");
683 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000684 if (RHSVal0DefinedFromLHS != -1) {
Evan Chengc14b1442007-08-31 08:04:17 +0000685 RHSValsDefinedFromLHS[RHSValNoInfo0] =
686 LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000687 }
David Greene25133302007-06-08 17:18:56 +0000688 } else {
689 // Loop over the value numbers of the LHS, seeing if any are defined from
690 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000691 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
692 i != e; ++i) {
693 VNInfo *VNI = *i;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000694 unsigned ValSrcReg = VNI->reg;
David Greene25133302007-06-08 17:18:56 +0000695 if (ValSrcReg == 0) // Src not defined by a copy?
696 continue;
697
698 // DstReg is known to be a register in the LHS interval. If the src is
699 // from the RHS interval, we can use its value #.
700 if (rep(ValSrcReg) != RHS.reg)
701 continue;
702
703 // Figure out the value # from the RHS.
Evan Chengc14b1442007-08-31 08:04:17 +0000704 LHSValsDefinedFromRHS[VNI] = RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +0000705 }
706
707 // Loop over the value numbers of the RHS, seeing if any are defined from
708 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000709 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
710 i != e; ++i) {
711 VNInfo *VNI = *i;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000712 unsigned ValSrcReg = VNI->reg;
David Greene25133302007-06-08 17:18:56 +0000713 if (ValSrcReg == 0) // Src not defined by a copy?
714 continue;
715
716 // DstReg is known to be a register in the RHS interval. If the src is
717 // from the LHS interval, we can use its value #.
718 if (rep(ValSrcReg) != LHS.reg)
719 continue;
720
721 // Figure out the value # from the LHS.
Evan Chengc14b1442007-08-31 08:04:17 +0000722 RHSValsDefinedFromLHS[VNI]= LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +0000723 }
724
725 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
726 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000727 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +0000728
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000729 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
730 i != e; ++i) {
731 VNInfo *VNI = *i;
732 unsigned VN = VNI->id;
733 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +0000734 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000735 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +0000736 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000737 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000738 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000739 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
740 i != e; ++i) {
741 VNInfo *VNI = *i;
742 unsigned VN = VNI->id;
743 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +0000744 continue;
745 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +0000746 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000747 NewVNInfo.push_back(VNI);
748 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +0000749 continue;
750 }
751
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000752 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +0000753 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000754 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000755 }
756 }
757
758 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +0000759 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +0000760 LiveInterval::const_iterator I = LHS.begin();
761 LiveInterval::const_iterator IE = LHS.end();
762 LiveInterval::const_iterator J = RHS.begin();
763 LiveInterval::const_iterator JE = RHS.end();
764
765 // Skip ahead until the first place of potential sharing.
766 if (I->start < J->start) {
767 I = std::upper_bound(I, IE, J->start);
768 if (I != LHS.begin()) --I;
769 } else if (J->start < I->start) {
770 J = std::upper_bound(J, JE, I->start);
771 if (J != RHS.begin()) --J;
772 }
773
774 while (1) {
775 // Determine if these two live ranges overlap.
776 bool Overlaps;
777 if (I->start < J->start) {
778 Overlaps = I->end > J->start;
779 } else {
780 Overlaps = J->end > I->start;
781 }
782
783 // If so, check value # info to determine if they are really different.
784 if (Overlaps) {
785 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +0000786 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000787 if (LHSValNoAssignments[I->valno->id] !=
788 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +0000789 return false;
790 }
791
792 if (I->end < J->end) {
793 ++I;
794 if (I == IE) break;
795 } else {
796 ++J;
797 if (J == JE) break;
798 }
799 }
800
Evan Cheng4f8ff162007-08-11 00:59:19 +0000801 // Update kill info. Some live ranges are extended due to copy coalescing.
Evan Chengfadfb5b2007-08-31 21:23:06 +0000802 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
Evan Chengc14b1442007-08-31 08:04:17 +0000803 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
804 VNInfo *VNI = I->first;
805 unsigned RHSValID = RHSValNoAssignments[VNI->id];
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000806 LiveInterval::removeKill(*NewVNInfo[RHSValID], VNI->def);
807 LHS.addKills(*NewVNInfo[RHSValID], VNI->kills);
Evan Cheng4f8ff162007-08-11 00:59:19 +0000808 }
Evan Chengc14b1442007-08-31 08:04:17 +0000809
Evan Chengfadfb5b2007-08-31 21:23:06 +0000810 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
Evan Chengc14b1442007-08-31 08:04:17 +0000811 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
812 VNInfo *VNI = I->first;
813 unsigned LHSValID = LHSValNoAssignments[VNI->id];
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000814 LiveInterval::removeKill(*NewVNInfo[LHSValID], VNI->def);
815 RHS.addKills(*NewVNInfo[LHSValID], VNI->kills);
Evan Cheng4f8ff162007-08-11 00:59:19 +0000816 }
817
Gabor Greife510b3a2007-07-09 12:00:59 +0000818 // If we get here, we know that we can coalesce the live ranges. Ask the
819 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000820 if ((RHS.ranges.size() > LHS.ranges.size() &&
821 MRegisterInfo::isVirtualRegister(LHS.reg)) ||
822 MRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000823 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000824 Swapped = true;
825 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000826 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000827 Swapped = false;
828 }
David Greene25133302007-06-08 17:18:56 +0000829 return true;
830}
831
832namespace {
833 // DepthMBBCompare - Comparison predicate that sort first based on the loop
834 // depth of the basic block (the unsigned), and then on the MBB number.
835 struct DepthMBBCompare {
836 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
837 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
838 if (LHS.first > RHS.first) return true; // Deeper loops first
839 return LHS.first == RHS.first &&
840 LHS.second->getNumber() < RHS.second->getNumber();
841 }
842 };
843}
844
Gabor Greife510b3a2007-07-09 12:00:59 +0000845void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
David Greene25133302007-06-08 17:18:56 +0000846 std::vector<CopyRec> *TryAgain, bool PhysOnly) {
847 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
848
849 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
850 MII != E;) {
851 MachineInstr *Inst = MII++;
852
853 // If this isn't a copy, we can't join intervals.
854 unsigned SrcReg, DstReg;
855 if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
856
857 if (TryAgain && !JoinCopy(Inst, SrcReg, DstReg, PhysOnly))
858 TryAgain->push_back(getCopyRec(Inst, SrcReg, DstReg));
859 }
860}
861
862void SimpleRegisterCoalescing::joinIntervals() {
863 DOUT << "********** JOINING INTERVALS ***********\n";
864
865 JoinedLIs.resize(li_->getNumIntervals());
866 JoinedLIs.reset();
867
868 std::vector<CopyRec> TryAgainList;
869 const LoopInfo &LI = getAnalysis<LoopInfo>();
870 if (LI.begin() == LI.end()) {
871 // If there are no loops in the function, join intervals in function order.
872 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
873 I != E; ++I)
Gabor Greife510b3a2007-07-09 12:00:59 +0000874 CopyCoalesceInMBB(I, &TryAgainList);
David Greene25133302007-06-08 17:18:56 +0000875 } else {
876 // Otherwise, join intervals in inner loops before other intervals.
877 // Unfortunately we can't just iterate over loop hierarchy here because
878 // there may be more MBB's than BB's. Collect MBB's for sorting.
879
880 // Join intervals in the function prolog first. We want to join physical
881 // registers with virtual registers before the intervals got too long.
882 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
883 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); I != E;++I)
884 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
885
886 // Sort by loop depth.
887 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
888
889 // Finally, join intervals in loop nest order.
890 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Gabor Greife510b3a2007-07-09 12:00:59 +0000891 CopyCoalesceInMBB(MBBs[i].second, NULL, true);
David Greene25133302007-06-08 17:18:56 +0000892 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Gabor Greife510b3a2007-07-09 12:00:59 +0000893 CopyCoalesceInMBB(MBBs[i].second, &TryAgainList, false);
David Greene25133302007-06-08 17:18:56 +0000894 }
895
896 // Joining intervals can allow other intervals to be joined. Iteratively join
897 // until we make no progress.
898 bool ProgressMade = true;
899 while (ProgressMade) {
900 ProgressMade = false;
901
902 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
903 CopyRec &TheCopy = TryAgainList[i];
904 if (TheCopy.MI &&
905 JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
906 TheCopy.MI = 0; // Mark this one as done.
907 ProgressMade = true;
908 }
909 }
910 }
911
912 // Some live range has been lengthened due to colaescing, eliminate the
913 // unnecessary kills.
914 int RegNum = JoinedLIs.find_first();
915 while (RegNum != -1) {
916 unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
917 unsigned repReg = rep(Reg);
918 LiveInterval &LI = li_->getInterval(repReg);
919 LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
920 for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
921 MachineInstr *Kill = svi.Kills[i];
922 // Suppose vr1 = op vr2, x
923 // and vr1 and vr2 are coalesced. vr2 should still be marked kill
924 // unless it is a two-address operand.
925 if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
926 continue;
927 if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
928 unsetRegisterKill(Kill, repReg);
929 }
930 RegNum = JoinedLIs.find_next(RegNum);
931 }
932
933 DOUT << "*** Register mapping ***\n";
934 for (int i = 0, e = r2rMap_.size(); i != e; ++i)
935 if (r2rMap_[i]) {
936 DOUT << " reg " << i << " -> ";
937 DEBUG(printRegName(r2rMap_[i]));
938 DOUT << "\n";
939 }
940}
941
942/// Return true if the two specified registers belong to different register
943/// classes. The registers may be either phys or virt regs.
944bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
945 unsigned RegB) const {
946
947 // Get the register classes for the first reg.
948 if (MRegisterInfo::isPhysicalRegister(RegA)) {
949 assert(MRegisterInfo::isVirtualRegister(RegB) &&
950 "Shouldn't consider two physregs!");
951 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
952 }
953
954 // Compare against the regclass for the second reg.
955 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
956 if (MRegisterInfo::isVirtualRegister(RegB))
957 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
958 else
959 return !RegClass->contains(RegB);
960}
961
962/// lastRegisterUse - Returns the last use of the specific register between
963/// cycles Start and End. It also returns the use operand by reference. It
964/// returns NULL if there are no uses.
965MachineInstr *
966SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
967 MachineOperand *&MOU) {
968 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
969 int s = Start;
970 while (e >= s) {
971 // Skip deleted instructions
972 MachineInstr *MI = li_->getInstructionFromIndex(e);
973 while ((e - InstrSlots::NUM) >= s && !MI) {
974 e -= InstrSlots::NUM;
975 MI = li_->getInstructionFromIndex(e);
976 }
977 if (e < s || MI == NULL)
978 return NULL;
979
980 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
981 MachineOperand &MO = MI->getOperand(i);
982 if (MO.isReg() && MO.isUse() && MO.getReg() &&
983 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
984 MOU = &MO;
985 return MI;
986 }
987 }
988
989 e -= InstrSlots::NUM;
990 }
991
992 return NULL;
993}
994
995
996/// findDefOperand - Returns the MachineOperand that is a def of the specific
997/// register. It returns NULL if the def is not found.
998MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
999 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1000 MachineOperand &MO = MI->getOperand(i);
1001 if (MO.isReg() && MO.isDef() &&
1002 mri_->regsOverlap(rep(MO.getReg()), Reg))
1003 return &MO;
1004 }
1005 return NULL;
1006}
1007
1008/// unsetRegisterKill - Unset IsKill property of all uses of specific register
1009/// of the specific instruction.
1010void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1011 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1012 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanc674a922007-07-20 23:17:34 +00001013 if (MO.isReg() && MO.isKill() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001014 mri_->regsOverlap(rep(MO.getReg()), Reg))
1015 MO.unsetIsKill();
1016 }
1017}
1018
1019/// unsetRegisterKills - Unset IsKill property of all uses of specific register
1020/// between cycles Start and End.
1021void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1022 unsigned Reg) {
1023 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1024 int s = Start;
1025 while (e >= s) {
1026 // Skip deleted instructions
1027 MachineInstr *MI = li_->getInstructionFromIndex(e);
1028 while ((e - InstrSlots::NUM) >= s && !MI) {
1029 e -= InstrSlots::NUM;
1030 MI = li_->getInstructionFromIndex(e);
1031 }
1032 if (e < s || MI == NULL)
1033 return;
1034
1035 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1036 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanc674a922007-07-20 23:17:34 +00001037 if (MO.isReg() && MO.isKill() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001038 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1039 MO.unsetIsKill();
1040 }
1041 }
1042
1043 e -= InstrSlots::NUM;
1044 }
1045}
1046
1047/// hasRegisterDef - True if the instruction defines the specific register.
1048///
1049bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1050 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1051 MachineOperand &MO = MI->getOperand(i);
1052 if (MO.isReg() && MO.isDef() &&
1053 mri_->regsOverlap(rep(MO.getReg()), Reg))
1054 return true;
1055 }
1056 return false;
1057}
1058
1059void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1060 if (MRegisterInfo::isPhysicalRegister(reg))
1061 cerr << mri_->getName(reg);
1062 else
1063 cerr << "%reg" << reg;
1064}
1065
1066void SimpleRegisterCoalescing::releaseMemory() {
1067 r2rMap_.clear();
1068 JoinedLIs.clear();
1069}
1070
1071static bool isZeroLengthInterval(LiveInterval *li) {
1072 for (LiveInterval::Ranges::const_iterator
1073 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1074 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1075 return false;
1076 return true;
1077}
1078
1079bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1080 mf_ = &fn;
1081 tm_ = &fn.getTarget();
1082 mri_ = tm_->getRegisterInfo();
1083 tii_ = tm_->getInstrInfo();
1084 li_ = &getAnalysis<LiveIntervals>();
1085 lv_ = &getAnalysis<LiveVariables>();
1086
1087 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1088 << "********** Function: "
1089 << ((Value*)mf_->getFunction())->getName() << '\n';
1090
1091 allocatableRegs_ = mri_->getAllocatableSet(fn);
1092 for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1093 E = mri_->regclass_end(); I != E; ++I)
1094 allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1095
1096 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
1097
Gabor Greife510b3a2007-07-09 12:00:59 +00001098 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00001099 if (EnableJoining) {
1100 joinIntervals();
1101 DOUT << "********** INTERVALS POST JOINING **********\n";
1102 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1103 I->second.print(DOUT, mri_);
1104 DOUT << "\n";
1105 }
1106 }
1107
1108 // perform a final pass over the instructions and compute spill
1109 // weights, coalesce virtual registers and remove identity moves.
1110 const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
1111
1112 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1113 mbbi != mbbe; ++mbbi) {
1114 MachineBasicBlock* mbb = mbbi;
1115 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
1116
1117 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1118 mii != mie; ) {
1119 // if the move will be an identity move delete it
1120 unsigned srcReg, dstReg, RegRep;
1121 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1122 (RegRep = rep(srcReg)) == rep(dstReg)) {
1123 // remove from def list
1124 LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1125 MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1126 // If def of this move instruction is dead, remove its live range from
1127 // the dstination register's live interval.
1128 if (MO->isDead()) {
1129 unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1130 LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1131 RegInt.removeRange(MLR->start, MoveIdx+1);
1132 if (RegInt.empty())
1133 li_->removeInterval(RegRep);
1134 }
1135 li_->RemoveMachineInstrFromMaps(mii);
1136 mii = mbbi->erase(mii);
1137 ++numPeep;
1138 } else {
1139 SmallSet<unsigned, 4> UniqueUses;
1140 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1141 const MachineOperand &mop = mii->getOperand(i);
1142 if (mop.isRegister() && mop.getReg() &&
1143 MRegisterInfo::isVirtualRegister(mop.getReg())) {
1144 // replace register with representative register
1145 unsigned reg = rep(mop.getReg());
1146 mii->getOperand(i).setReg(reg);
1147
1148 // Multiple uses of reg by the same instruction. It should not
1149 // contribute to spill weight again.
1150 if (UniqueUses.count(reg) != 0)
1151 continue;
1152 LiveInterval &RegInt = li_->getInterval(reg);
1153 float w = (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
David Greene25133302007-06-08 17:18:56 +00001154 RegInt.weight += w;
1155 UniqueUses.insert(reg);
1156 }
1157 }
1158 ++mii;
1159 }
1160 }
1161 }
1162
1163 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1164 LiveInterval &LI = I->second;
1165 if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1166 // If the live interval length is essentially zero, i.e. in every live
1167 // range the use follows def immediately, it doesn't make sense to spill
1168 // it and hope it will be easier to allocate for this li.
1169 if (isZeroLengthInterval(&LI))
1170 LI.weight = HUGE_VALF;
1171
1172 // Slightly prefer live interval that has been assigned a preferred reg.
1173 if (LI.preference)
1174 LI.weight *= 1.01F;
1175
1176 // Divide the weight of the interval by its size. This encourages
1177 // spilling of intervals that are large and have few uses, and
1178 // discourages spilling of small intervals with many uses.
1179 LI.weight /= LI.getSize();
1180 }
1181 }
1182
1183 DEBUG(dump());
1184 return true;
1185}
1186
1187/// print - Implement the dump method.
1188void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1189 li_->print(O, m);
1190}