blob: 870fcc44080d56161b58ead97d7f8d556f25cfed [file] [log] [blame]
David Greene25133302007-06-08 17:18:56 +00001//===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
David Greene25133302007-06-08 17:18:56 +00007//
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"
Evan Chenga461c4d2007-11-05 17:41:38 +000016#include "SimpleRegisterCoalescing.h"
David Greene25133302007-06-08 17:18:56 +000017#include "VirtRegMap.h"
Evan Chenga461c4d2007-11-05 17:41:38 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
David Greene25133302007-06-08 17:18:56 +000019#include "llvm/Value.h"
David Greene25133302007-06-08 17:18:56 +000020#include "llvm/CodeGen/LiveVariables.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
David Greene25133302007-06-08 17:18:56 +000025#include "llvm/CodeGen/Passes.h"
David Greene2c17c4d2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
David Greene25133302007-06-08 17:18:56 +000027#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");
Evan Cheng70071432008-02-13 03:01:43 +000039STATISTIC(numCommutes , "Number of instruction commuting performed");
40STATISTIC(numExtends , "Number of copies extended");
David Greene25133302007-06-08 17:18:56 +000041STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
42STATISTIC(numAborts , "Number of times interval joining aborted");
43
44char SimpleRegisterCoalescing::ID = 0;
45namespace {
46 static cl::opt<bool>
47 EnableJoining("join-liveintervals",
Gabor Greife510b3a2007-07-09 12:00:59 +000048 cl::desc("Coalesce copies (default=true)"),
David Greene25133302007-06-08 17:18:56 +000049 cl::init(true));
50
Evan Cheng8fc9a102007-11-06 08:52:21 +000051 static cl::opt<bool>
52 NewHeuristic("new-coalescer-heuristic",
53 cl::desc("Use new coalescer heuristic"),
54 cl::init(false));
55
David Greene25133302007-06-08 17:18:56 +000056 RegisterPass<SimpleRegisterCoalescing>
Chris Lattnere76fad22007-08-05 18:45:33 +000057 X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000058
59 // Declare that we implement the RegisterCoalescer interface
60 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000061}
62
63const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
64
65void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000066 AU.addPreserved<LiveIntervals>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000067 AU.addPreserved<MachineLoopInfo>();
68 AU.addPreservedID(MachineDominatorsID);
David Greene25133302007-06-08 17:18:56 +000069 AU.addPreservedID(PHIEliminationID);
70 AU.addPreservedID(TwoAddressInstructionPassID);
71 AU.addRequired<LiveVariables>();
72 AU.addRequired<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +000073 AU.addRequired<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +000074 MachineFunctionPass::getAnalysisUsage(AU);
75}
76
Gabor Greife510b3a2007-07-09 12:00:59 +000077/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000078/// being the source and IntB being the dest, thus this defines a value number
79/// in IntB. If the source value number (in IntA) is defined by a copy from B,
80/// see if we can merge these two pieces of B into a single value number,
81/// eliminating a copy. For example:
82///
83/// A3 = B0
84/// ...
85/// B1 = A3 <- this copy
86///
87/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
88/// value number to be replaced with B0 (which simplifies the B liveinterval).
89///
90/// This returns true if an interval was modified.
91///
Bill Wendling2674d712008-01-04 08:59:18 +000092bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
93 LiveInterval &IntB,
94 MachineInstr *CopyMI) {
David Greene25133302007-06-08 17:18:56 +000095 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
96
97 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
98 // the example above.
99 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000100 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000101
102 // Get the location that B is defined at. Two options: either this value has
103 // an unknown definition point or it is defined at CopyIdx. If unknown, we
104 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000105 if (!BValNo->copy) return false;
106 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
David Greene25133302007-06-08 17:18:56 +0000107
Evan Cheng70071432008-02-13 03:01:43 +0000108 // AValNo is the value number in A that defines the copy, A3 in the example.
109 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
110 VNInfo *AValNo = ALR->valno;
David Greene25133302007-06-08 17:18:56 +0000111
Evan Cheng70071432008-02-13 03:01:43 +0000112 // If AValNo is defined as a copy from IntB, we can potentially process this.
David Greene25133302007-06-08 17:18:56 +0000113 // Get the instruction that defines this value number.
Evan Chengc8d044e2008-02-15 18:24:29 +0000114 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
David Greene25133302007-06-08 17:18:56 +0000115 if (!SrcReg) return false; // Not defined by a copy.
116
117 // If the value number is not defined by a copy instruction, ignore it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000118
David Greene25133302007-06-08 17:18:56 +0000119 // If the source register comes from an interval other than IntB, we can't
120 // handle this.
Evan Chengc8d044e2008-02-15 18:24:29 +0000121 if (SrcReg != IntB.reg) return false;
David Greene25133302007-06-08 17:18:56 +0000122
123 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000124 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
David Greene25133302007-06-08 17:18:56 +0000125
126 // Make sure that the end of the live range is inside the same block as
127 // CopyMI.
128 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
129 if (!ValLREndInst ||
130 ValLREndInst->getParent() != CopyMI->getParent()) return false;
131
132 // Okay, we now know that ValLR ends in the same block that the CopyMI
133 // live-range starts. If there are no intervening live ranges between them in
134 // IntB, we can merge them.
135 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000136
137 // If a live interval is a physical register, conservatively check if any
138 // of its sub-registers is overlapping the live interval of the virtual
139 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000140 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
141 *tri_->getSubRegisters(IntB.reg)) {
142 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
Evan Chengdc5294f2007-08-14 23:19:28 +0000143 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
144 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000145 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Chengdc5294f2007-08-14 23:19:28 +0000146 return false;
147 }
148 }
David Greene25133302007-06-08 17:18:56 +0000149
Dan Gohman6f0d0242008-02-10 18:45:23 +0000150 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000151
Evan Chenga8d94f12007-08-07 23:49:57 +0000152 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000153 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000154 // that defines this value #'. Update the the valnum with the new defining
155 // instruction #.
Evan Chengc8d044e2008-02-15 18:24:29 +0000156 BValNo->def = FillerStart;
157 BValNo->copy = NULL;
David Greene25133302007-06-08 17:18:56 +0000158
159 // Okay, we can merge them. We need to insert a new liverange:
160 // [ValLR.end, BLR.begin) of either value number, then we merge the
161 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000162 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
163
164 // If the IntB live range is assigned to a physical register, and if that
165 // physreg has aliases,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000166 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
David Greene25133302007-06-08 17:18:56 +0000167 // Update the liveintervals of sub-registers.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000168 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
David Greene25133302007-06-08 17:18:56 +0000169 LiveInterval &AliasLI = li_->getInterval(*AS);
170 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000171 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000172 }
173 }
174
175 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000176 if (BValNo != ValLR->valno)
177 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000178 DOUT << " result = "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000179 DOUT << "\n";
180
181 // If the source instruction was killing the source register before the
182 // merge, unset the isKill marker given the live range has been extended.
183 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
184 if (UIdx != -1)
Chris Lattnerf7382302007-12-30 21:56:09 +0000185 ValLREndInst->getOperand(UIdx).setIsKill(false);
Evan Cheng70071432008-02-13 03:01:43 +0000186
187 ++numExtends;
188 return true;
189}
190
Evan Cheng559f4222008-02-16 02:32:17 +0000191/// HasOtherReachingDefs - Return true if there are definitions of IntB
192/// other than BValNo val# that can reach uses of AValno val# of IntA.
193bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
194 LiveInterval &IntB,
195 VNInfo *AValNo,
196 VNInfo *BValNo) {
197 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
198 AI != AE; ++AI) {
199 if (AI->valno != AValNo) continue;
200 LiveInterval::Ranges::iterator BI =
201 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
202 if (BI != IntB.ranges.begin())
203 --BI;
204 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
205 if (BI->valno == BValNo)
206 continue;
207 if (BI->start <= AI->start && BI->end > AI->start)
208 return true;
209 if (BI->start > AI->start && BI->start < AI->end)
210 return true;
211 }
212 }
213 return false;
214}
215
Evan Cheng70071432008-02-13 03:01:43 +0000216/// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
217/// being the source and IntB being the dest, thus this defines a value number
218/// in IntB. If the source value number (in IntA) is defined by a commutable
219/// instruction and its other operand is coalesced to the copy dest register,
220/// see if we can transform the copy into a noop by commuting the definition. For
221/// example,
222///
223/// A3 = op A2 B0<kill>
224/// ...
225/// B1 = A3 <- this copy
226/// ...
227/// = op A3 <- more uses
228///
229/// ==>
230///
231/// B2 = op B0 A2<kill>
232/// ...
233/// B1 = B2 <- now an identify copy
234/// ...
235/// = op B2 <- more uses
236///
237/// This returns true if an interval was modified.
238///
239bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
240 LiveInterval &IntB,
241 MachineInstr *CopyMI) {
Evan Cheng70071432008-02-13 03:01:43 +0000242 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
243
Evan Chenga9407f52008-02-18 18:56:31 +0000244 // FIXME: For now, only eliminate the copy by commuting its def when the
245 // source register is a virtual register. We want to guard against cases
246 // where the copy is a back edge copy and commuting the def lengthen the
247 // live interval of the source register to the entire loop.
248 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
Evan Cheng96cfff02008-02-18 08:40:53 +0000249 return false;
250
Evan Chengc8d044e2008-02-15 18:24:29 +0000251 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
Evan Cheng70071432008-02-13 03:01:43 +0000252 // the example above.
253 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
254 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000255
Evan Cheng70071432008-02-13 03:01:43 +0000256 // Get the location that B is defined at. Two options: either this value has
257 // an unknown definition point or it is defined at CopyIdx. If unknown, we
258 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000259 if (!BValNo->copy) return false;
Evan Cheng70071432008-02-13 03:01:43 +0000260 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
261
262 // AValNo is the value number in A that defines the copy, A3 in the example.
263 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
264 VNInfo *AValNo = ALR->valno;
Evan Chenge35a6d12008-02-13 08:41:08 +0000265 // If other defs can reach uses of this def, then it's not safe to perform
266 // the optimization.
267 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
Evan Cheng70071432008-02-13 03:01:43 +0000268 return false;
269 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
270 const TargetInstrDesc &TID = DefMI->getDesc();
Evan Chengc8d044e2008-02-15 18:24:29 +0000271 unsigned NewDstIdx;
272 if (!TID.isCommutable() ||
273 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
Evan Cheng70071432008-02-13 03:01:43 +0000274 return false;
275
Evan Chengc8d044e2008-02-15 18:24:29 +0000276 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
277 unsigned NewReg = NewDstMO.getReg();
278 if (NewReg != IntB.reg || !NewDstMO.isKill())
Evan Cheng70071432008-02-13 03:01:43 +0000279 return false;
280
281 // Make sure there are no other definitions of IntB that would reach the
282 // uses which the new definition can reach.
Evan Cheng559f4222008-02-16 02:32:17 +0000283 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
284 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000285
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000286 // At this point we have decided that it is legal to do this
287 // transformation. Start by commuting the instruction.
Evan Cheng70071432008-02-13 03:01:43 +0000288 MachineBasicBlock *MBB = DefMI->getParent();
289 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
Evan Cheng559f4222008-02-16 02:32:17 +0000290 if (!NewMI)
291 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000292 if (NewMI != DefMI) {
293 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
294 MBB->insert(DefMI, NewMI);
295 MBB->erase(DefMI);
296 }
Evan Cheng6130f662008-03-05 00:59:57 +0000297 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
Evan Cheng70071432008-02-13 03:01:43 +0000298 NewMI->getOperand(OpIdx).setIsKill();
299
Evan Cheng70071432008-02-13 03:01:43 +0000300 bool BHasPHIKill = BValNo->hasPHIKill;
301 SmallVector<VNInfo*, 4> BDeadValNos;
302 SmallVector<unsigned, 4> BKills;
303 std::map<unsigned, unsigned> BExtend;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000304
305 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
306 // A = or A, B
307 // ...
308 // B = A
309 // ...
310 // C = A<kill>
311 // ...
312 // = B
313 //
314 // then do not add kills of A to the newly created B interval.
315 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
316 if (Extended)
317 BExtend[ALR->end] = BLR->end;
318
319 // Update uses of IntA of the specific Val# with IntB.
Evan Cheng70071432008-02-13 03:01:43 +0000320 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
321 UE = mri_->use_end(); UI != UE;) {
322 MachineOperand &UseMO = UI.getOperand();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000323 MachineInstr *UseMI = &*UI;
Evan Cheng70071432008-02-13 03:01:43 +0000324 ++UI;
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000325 if (JoinedCopies.count(UseMI))
Evan Cheng6f83fc82008-03-24 23:31:21 +0000326 // It'll no longer be "joined" after the change.
327 JoinedCopies.erase(UseMI);
Evan Cheng70071432008-02-13 03:01:43 +0000328 unsigned UseIdx = li_->getInstructionIndex(UseMI);
329 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
330 if (ULR->valno != AValNo)
331 continue;
332 UseMO.setReg(NewReg);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000333 if (UseMI == CopyMI)
334 continue;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000335 if (UseMO.isKill()) {
336 if (Extended)
337 UseMO.setIsKill(false);
338 else
339 BKills.push_back(li_->getUseIndex(UseIdx)+1);
340 }
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000341 unsigned SrcReg, DstReg;
342 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
343 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +0000344 if (DstReg == IntB.reg) {
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000345 // This copy will become a noop. If it's defining a new val#,
346 // remove that val# as well. However this live range is being
347 // extended to the end of the existing live range defined by the copy.
348 unsigned DefIdx = li_->getDefIndex(UseIdx);
349 LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
350 BHasPHIKill |= DLR->valno->hasPHIKill;
351 assert(DLR->valno->def == DefIdx);
352 BDeadValNos.push_back(DLR->valno);
353 BExtend[DLR->start] = DLR->end;
354 JoinedCopies.insert(UseMI);
355 // If this is a kill but it's going to be removed, the last use
356 // of the same val# is the new kill.
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000357 if (UseMO.isKill())
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000358 BKills.pop_back();
Evan Cheng70071432008-02-13 03:01:43 +0000359 }
360 }
361
362 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
363 // simply extend BLR if CopyMI doesn't end the range.
364 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
365
366 IntB.removeValNo(BValNo);
367 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
368 IntB.removeValNo(BDeadValNos[i]);
Evan Cheng82a6d232008-03-19 02:26:36 +0000369 VNInfo *ValNo = IntB.getNextValue(AValNo->def, 0, li_->getVNInfoAllocator());
Evan Cheng70071432008-02-13 03:01:43 +0000370 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
371 AI != AE; ++AI) {
372 if (AI->valno != AValNo) continue;
373 unsigned End = AI->end;
374 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
375 if (EI != BExtend.end())
376 End = EI->second;
377 IntB.addRange(LiveRange(AI->start, End, ValNo));
378 }
379 IntB.addKills(ValNo, BKills);
380 ValNo->hasPHIKill = BHasPHIKill;
381
382 DOUT << " result = "; IntB.print(DOUT, tri_);
383 DOUT << "\n";
384
385 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
386 IntA.removeValNo(AValNo);
387 DOUT << " result = "; IntA.print(DOUT, tri_);
388 DOUT << "\n";
389
390 ++numCommutes;
David Greene25133302007-06-08 17:18:56 +0000391 return true;
392}
393
Evan Cheng8fc9a102007-11-06 08:52:21 +0000394/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
395///
396bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
397 unsigned DstReg) {
398 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000399 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000400 if (!L)
401 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000402 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000403 return false;
404
Evan Cheng8fc9a102007-11-06 08:52:21 +0000405 LiveInterval &LI = li_->getInterval(DstReg);
406 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
407 LiveInterval::const_iterator DstLR =
408 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
409 if (DstLR == LI.end())
410 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000411 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
412 if (DstLR->valno->kills.size() == 1 &&
413 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
Evan Cheng8fc9a102007-11-06 08:52:21 +0000414 return true;
415 return false;
416}
417
Evan Chengc8d044e2008-02-15 18:24:29 +0000418/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
419/// update the subregister number if it is not zero. If DstReg is a
420/// physical register and the existing subregister number of the def / use
421/// being updated is not zero, make sure to set it to the correct physical
422/// subregister.
423void
424SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
425 unsigned SubIdx) {
426 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
427 if (DstIsPhys && SubIdx) {
428 // Figure out the real physical register we are updating with.
429 DstReg = tri_->getSubReg(DstReg, SubIdx);
430 SubIdx = 0;
431 }
432
433 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
434 E = mri_->reg_end(); I != E; ) {
435 MachineOperand &O = I.getOperand();
Evan Cheng70366b92008-03-21 19:09:30 +0000436 MachineInstr *UseMI = &*I;
Evan Chengc8d044e2008-02-15 18:24:29 +0000437 ++I;
438 if (DstIsPhys) {
439 unsigned UseSubIdx = O.getSubReg();
440 unsigned UseDstReg = DstReg;
441 if (UseSubIdx)
442 UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
443 O.setReg(UseDstReg);
444 O.setSubReg(0);
445 } else {
446 unsigned OldSubIdx = O.getSubReg();
Evan Chengc886c462008-02-26 08:03:41 +0000447 // Sub-register indexes goes from small to large. e.g.
448 // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
449 // EAX: 0 -> AL, 1 -> AH, 2 -> AX
450 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
451 // sub-register 2 is also AX.
452 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
453 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
454 else if (SubIdx)
Evan Chengc8d044e2008-02-15 18:24:29 +0000455 O.setSubReg(SubIdx);
Evan Cheng70366b92008-03-21 19:09:30 +0000456 // Remove would-be duplicated kill marker.
457 if (O.isKill() && UseMI->killsRegister(DstReg))
458 O.setIsKill(false);
Evan Chengc8d044e2008-02-15 18:24:29 +0000459 O.setReg(DstReg);
460 }
461 }
462}
463
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000464/// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
465/// due to live range lengthening as the result of coalescing.
466void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
467 LiveInterval &LI) {
468 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
469 UE = mri_->use_end(); UI != UE; ++UI) {
470 MachineOperand &UseMO = UI.getOperand();
471 if (UseMO.isKill()) {
472 MachineInstr *UseMI = UseMO.getParent();
473 unsigned SReg, DReg;
474 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
475 continue;
476 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
477 if (JoinedCopies.count(UseMI))
478 continue;
479 LiveInterval::const_iterator UI = LI.FindLiveRangeContaining(UseIdx);
480 assert(UI != LI.end());
481 if (!LI.isKill(UI->valno, UseIdx+1))
482 UseMO.setIsKill(false);
483 }
484 }
485}
486
Evan Cheng3c88d742008-03-18 08:26:47 +0000487/// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
488/// from a physical register live interval as well as from the live intervals
489/// of its sub-registers.
490static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
491 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
492 li.removeRange(Start, End, true);
493 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
494 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
495 if (!li_->hasInterval(*SR))
496 continue;
497 LiveInterval &sli = li_->getInterval(*SR);
498 unsigned RemoveEnd = Start;
499 while (RemoveEnd != End) {
500 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
501 if (LR == sli.end())
502 break;
503 RemoveEnd = (LR->end < End) ? LR->end : End;
504 sli.removeRange(Start, RemoveEnd, true);
505 Start = RemoveEnd;
506 }
507 }
508 }
509}
510
511/// removeIntervalIfEmpty - Check if the live interval of a physical register
512/// is empty, if so remove it and also remove the empty intervals of its
513/// sub-registers.
514static void removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
515 const TargetRegisterInfo *tri_) {
516 if (li.empty()) {
517 li_->removeInterval(li.reg);
518 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
519 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
520 if (!li_->hasInterval(*SR))
521 continue;
522 LiveInterval &sli = li_->getInterval(*SR);
523 if (sli.empty())
524 li_->removeInterval(*SR);
525 }
526 }
527}
528
529/// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
530///
Evan Chengecb2a8b2008-03-05 22:09:42 +0000531void SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
532 MachineInstr *CopyMI) {
533 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
534 LiveInterval::iterator MLR =
535 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
Evan Cheng3c88d742008-03-18 08:26:47 +0000536 if (MLR == li.end())
537 return; // Already removed by ShortenDeadCopySrcLiveRange.
Evan Chengecb2a8b2008-03-05 22:09:42 +0000538 unsigned RemoveStart = MLR->start;
539 unsigned RemoveEnd = MLR->end;
Evan Cheng3c88d742008-03-18 08:26:47 +0000540 // Remove the liverange that's defined by this.
541 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
542 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
543 removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000544 }
Evan Cheng3c88d742008-03-18 08:26:47 +0000545}
546
547/// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
548/// extended by a dead copy. Mark the last use (if any) of the val# as kill
549/// as ends the live range there. If there isn't another use, then this
550/// live range is dead.
551void
552SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
553 MachineInstr *CopyMI) {
554 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
555 if (CopyIdx == 0) {
556 // FIXME: special case: function live in. It can be a general case if the
557 // first instruction index starts at > 0 value.
558 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
559 // Live-in to the function but dead. Remove it from entry live-in set.
560 mf_->begin()->removeLiveIn(li.reg);
561 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
562 removeRange(li, LR->start, LR->end, li_, tri_);
563 removeIntervalIfEmpty(li, li_, tri_);
564 return;
565 }
566
567 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
568 if (LR == li.end())
569 // Livein but defined by a phi.
570 return;
571
572 unsigned RemoveStart = LR->start;
573 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
574 if (LR->end > RemoveEnd)
575 // More uses past this copy? Nothing to do.
576 return;
577
578 unsigned LastUseIdx;
579 MachineOperand *LastUse =
580 lastRegisterUse(LR->start, CopyIdx-1, li.reg, LastUseIdx);
581 if (LastUse) {
582 // There are uses before the copy, just shorten the live range to the end
583 // of last use.
584 LastUse->setIsKill();
585 MachineInstr *LastUseMI = LastUse->getParent();
586 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
587 unsigned SrcReg, DstReg;
588 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
589 DstReg == li.reg) {
590 // Last use is itself an identity code.
591 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
592 LastUseMI->getOperand(DeadIdx).setIsDead();
593 }
594 return;
595 }
596
597 // Is it livein?
598 MachineBasicBlock *CopyMBB = CopyMI->getParent();
599 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
600 if (LR->start <= MBBStart && LR->end > MBBStart) {
601 if (LR->start == 0) {
602 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
603 // Live-in to the function but dead. Remove it from entry live-in set.
604 mf_->begin()->removeLiveIn(li.reg);
605 }
606 removeRange(li, LR->start, LR->end, li_, tri_);
607 // FIXME: Shorten intervals in BBs that reaches this BB.
608 } else {
609 // Not livein into BB.
610 MachineInstr *DefMI =
611 li_->getInstructionFromIndex(li_->getDefIndex(RemoveStart));
612 if (DefMI && DefMI != CopyMI) {
613 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
614 if (DeadIdx != -1) {
615 DefMI->getOperand(DeadIdx).setIsDead();
616 // A dead def should have a single cycle interval.
617 ++RemoveStart;
618 }
619 }
620 removeRange(li, RemoveStart, LR->end, li_, tri_);
621 }
622
623 removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000624}
625
David Greene25133302007-06-08 17:18:56 +0000626/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
627/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +0000628/// if the copy was successfully coalesced away. If it is not currently
629/// possible to coalesce this interval, but it may be possible if other
630/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng70071432008-02-13 03:01:43 +0000631bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000632 MachineInstr *CopyMI = TheCopy.MI;
633
634 Again = false;
635 if (JoinedCopies.count(CopyMI))
636 return false; // Already done.
637
David Greene25133302007-06-08 17:18:56 +0000638 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
639
Evan Chengc8d044e2008-02-15 18:24:29 +0000640 unsigned SrcReg;
641 unsigned DstReg;
642 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
643 unsigned SubIdx = 0;
644 if (isExtSubReg) {
645 DstReg = CopyMI->getOperand(0).getReg();
646 SrcReg = CopyMI->getOperand(1).getReg();
647 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
648 assert(0 && "Unrecognized copy instruction!");
649 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000650 }
651
David Greene25133302007-06-08 17:18:56 +0000652 // If they are already joined we continue.
Evan Chengc8d044e2008-02-15 18:24:29 +0000653 if (SrcReg == DstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000654 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000655 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000656 }
657
Evan Chengc8d044e2008-02-15 18:24:29 +0000658 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
659 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
David Greene25133302007-06-08 17:18:56 +0000660
661 // If they are both physical registers, we cannot join them.
662 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000663 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000664 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000665 }
666
667 // We only join virtual registers with allocatable physical registers.
Evan Chengc8d044e2008-02-15 18:24:29 +0000668 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
David Greene25133302007-06-08 17:18:56 +0000669 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000670 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000671 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000672 if (DstIsPhys && !allocatableRegs_[DstReg]) {
David Greene25133302007-06-08 17:18:56 +0000673 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000674 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000675 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000676
Evan Cheng32dfbea2007-10-12 08:50:34 +0000677 unsigned RealDstReg = 0;
678 if (isExtSubReg) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000679 SubIdx = CopyMI->getOperand(2).getImm();
680 if (SrcIsPhys) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000681 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
682 // coalesced with AX.
Evan Chengc8d044e2008-02-15 18:24:29 +0000683 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
684 SubIdx = 0;
685 } else if (DstIsPhys) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000686 // If this is a extract_subreg where dst is a physical register, e.g.
687 // cl = EXTRACT_SUBREG reg1024, 1
688 // then create and update the actual physical register allocated to RHS.
Evan Chengc8d044e2008-02-15 18:24:29 +0000689 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
690 for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000691 unsigned SR = *SRs; ++SRs) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000692 if (DstReg == tri_->getSubReg(SR, SubIdx) &&
Evan Cheng32dfbea2007-10-12 08:50:34 +0000693 RC->contains(SR)) {
694 RealDstReg = SR;
695 break;
696 }
697 }
698 assert(RealDstReg && "Invalid extra_subreg instruction!");
699
700 // For this type of EXTRACT_SUBREG, conservatively
701 // check if the live interval of the source register interfere with the
702 // actual super physical register we are trying to coalesce with.
Evan Chengc8d044e2008-02-15 18:24:29 +0000703 LiveInterval &RHS = li_->getInterval(SrcReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000704 if (li_->hasInterval(RealDstReg) &&
705 RHS.overlaps(li_->getInterval(RealDstReg))) {
706 DOUT << "Interfere with register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000707 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000708 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000709 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000710 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
Evan Cheng32dfbea2007-10-12 08:50:34 +0000711 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
712 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000713 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000714 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000715 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000716 SubIdx = 0;
Evan Cheng0547bab2007-11-01 06:22:48 +0000717 } else {
Evan Chengc8d044e2008-02-15 18:24:29 +0000718 unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
719 unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
720 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
Evan Cheng0547bab2007-11-01 06:22:48 +0000721 unsigned Threshold = allocatableRCRegs_[RC].count();
Evan Cheng52c7ff72007-10-12 09:15:53 +0000722 // Be conservative. If both sides are virtual registers, do not coalesce
Evan Cheng0547bab2007-11-01 06:22:48 +0000723 // if this will cause a high use density interval to target a smaller set
724 // of registers.
725 if (DstSize > Threshold || SrcSize > Threshold) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000726 LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
727 LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
Evan Cheng0547bab2007-11-01 06:22:48 +0000728 if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
729 Again = true; // May be possible to coalesce later.
730 return false;
731 }
732 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000733 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000734 } else if (differingRegisterClasses(SrcReg, DstReg)) {
735 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
736 // with another? If it's the resulting destination register, then
737 // the subidx must be propagated to uses (but only those defined
738 // by the EXTRACT_SUBREG). If it's being coalesced into another
739 // register, it should be safe because register is assumed to have
740 // the register class of the super-register.
741
Evan Cheng32dfbea2007-10-12 08:50:34 +0000742 // If they are not of the same register class, we cannot join them.
David Greene25133302007-06-08 17:18:56 +0000743 DOUT << "\tSrc/Dest are different register classes.\n";
Evan Cheng32dfbea2007-10-12 08:50:34 +0000744 // Allow the coalescer to try again in case either side gets coalesced to
745 // a physical register that's compatible with the other side. e.g.
746 // r1024 = MOV32to32_ r1025
747 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
Evan Cheng0547bab2007-11-01 06:22:48 +0000748 Again = true; // May be possible to coalesce later.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000749 return false;
David Greene25133302007-06-08 17:18:56 +0000750 }
751
Evan Chengc8d044e2008-02-15 18:24:29 +0000752 LiveInterval &SrcInt = li_->getInterval(SrcReg);
753 LiveInterval &DstInt = li_->getInterval(DstReg);
754 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
David Greene25133302007-06-08 17:18:56 +0000755 "Register mapping is horribly broken!");
756
Dan Gohman6f0d0242008-02-10 18:45:23 +0000757 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
758 DOUT << " and "; DstInt.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000759 DOUT << ": ";
760
Evan Cheng3c88d742008-03-18 08:26:47 +0000761 // Check if it is necessary to propagate "isDead" property.
Evan Cheng6130f662008-03-05 00:59:57 +0000762 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
David Greene25133302007-06-08 17:18:56 +0000763 bool isDead = mopd->isDead();
David Greene25133302007-06-08 17:18:56 +0000764
765 // We need to be careful about coalescing a source physical register with a
766 // virtual register. Once the coalescing is done, it cannot be broken and
767 // these are not spillable! If the destination interval uses are far away,
768 // think twice about coalescing them!
Evan Cheng3c88d742008-03-18 08:26:47 +0000769 if (!isDead && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
David Greene25133302007-06-08 17:18:56 +0000770 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
Evan Chengc8d044e2008-02-15 18:24:29 +0000771 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
772 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
773 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
Evan Cheng68949422007-12-20 02:23:25 +0000774 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
Evan Cheng8fc9a102007-11-06 08:52:21 +0000775 if (TheCopy.isBackEdge)
776 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +0000777
Evan Cheng32dfbea2007-10-12 08:50:34 +0000778 // If the virtual register live interval is long but it has low use desity,
David Greene25133302007-06-08 17:18:56 +0000779 // do not join them, instead mark the physical register as its allocation
780 // preference.
781 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
782 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
783 if (Length > Threshold &&
784 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
785 JoinVInt.preference = JoinPReg;
786 ++numAborts;
787 DOUT << "\tMay tie down a physical register, abort!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000788 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +0000789 return false;
790 }
791 }
792
793 // Okay, attempt to join these two intervals. On failure, this returns false.
794 // Otherwise, if one of the intervals being joined is a physreg, this method
795 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
796 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000797 bool Swapped = false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000798 if (!JoinIntervals(DstInt, SrcInt, Swapped)) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000799 // Coalescing failed.
David Greene25133302007-06-08 17:18:56 +0000800
801 // If we can eliminate the copy without merging the live ranges, do so now.
Evan Cheng70071432008-02-13 03:01:43 +0000802 if (!isExtSubReg &&
803 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
804 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000805 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +0000806 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +0000807 }
Evan Cheng70071432008-02-13 03:01:43 +0000808
David Greene25133302007-06-08 17:18:56 +0000809 // Otherwise, we are unable to join the intervals.
810 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000811 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +0000812 return false;
813 }
814
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000815 LiveInterval *ResSrcInt = &SrcInt;
816 LiveInterval *ResDstInt = &DstInt;
817 if (Swapped) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000818 std::swap(SrcReg, DstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000819 std::swap(ResSrcInt, ResDstInt);
820 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000821 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
David Greene25133302007-06-08 17:18:56 +0000822 "LiveInterval::join didn't work right!");
823
824 // If we're about to merge live ranges into a physical register live range,
825 // we have to update any aliased register's live ranges to indicate that they
826 // have clobbered values for this range.
Evan Chengc8d044e2008-02-15 18:24:29 +0000827 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000828 // If this is a extract_subreg where dst is a physical register, e.g.
829 // cl = EXTRACT_SUBREG reg1024, 1
830 // then create and update the actual physical register allocated to RHS.
831 if (RealDstReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000832 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
Evan Chengf5c73592007-10-15 18:33:50 +0000833 SmallSet<const VNInfo*, 4> CopiedValNos;
834 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
835 E = ResSrcInt->ranges.end(); I != E; ++I) {
836 LiveInterval::const_iterator DstLR =
837 ResDstInt->FindLiveRangeContaining(I->start);
838 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
839 const VNInfo *DstValNo = DstLR->valno;
840 if (CopiedValNos.insert(DstValNo)) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000841 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
Evan Chengf5c73592007-10-15 18:33:50 +0000842 li_->getVNInfoAllocator());
Evan Chengc3fc7d92007-11-29 09:49:23 +0000843 ValNo->hasPHIKill = DstValNo->hasPHIKill;
Evan Chengf5c73592007-10-15 18:33:50 +0000844 RealDstInt.addKills(ValNo, DstValNo->kills);
845 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
846 }
Evan Cheng34729252007-10-14 10:08:34 +0000847 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000848 DstReg = RealDstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +0000849 }
850
David Greene25133302007-06-08 17:18:56 +0000851 // Update the liveintervals of sub-registers.
Evan Chengc8d044e2008-02-15 18:24:29 +0000852 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +0000853 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000854 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +0000855 } else {
856 // Merge use info if the destination is a virtual register.
Evan Chengc8d044e2008-02-15 18:24:29 +0000857 LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
858 LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
David Greene25133302007-06-08 17:18:56 +0000859 dVI.NumUses += sVI.NumUses;
860 }
861
Evan Chengc8d044e2008-02-15 18:24:29 +0000862 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
863 // larger super-register.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000864 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
865 if (!Swapped) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000866 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
Evan Chengc8d044e2008-02-15 18:24:29 +0000867 std::swap(SrcReg, DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000868 std::swap(ResSrcInt, ResDstInt);
869 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000870 }
871
Evan Cheng8fc9a102007-11-06 08:52:21 +0000872 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000873 // Add all copies that define val# in the source interval into the queue.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000874 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
875 e = ResSrcInt->vni_end(); i != e; ++i) {
876 const VNInfo *vni = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +0000877 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
878 continue;
879 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
880 unsigned NewSrcReg, NewDstReg;
881 if (CopyMI &&
882 JoinedCopies.count(CopyMI) == 0 &&
883 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
884 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
885 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
886 isBackEdgeCopy(CopyMI, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +0000887 }
888 }
889 }
890
Dan Gohman6f0d0242008-02-10 18:45:23 +0000891 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000892 DOUT << "\n";
893
Evan Chengc8d044e2008-02-15 18:24:29 +0000894 // Remember to delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000895 JoinedCopies.insert(CopyMI);
Evan Chengc8d044e2008-02-15 18:24:29 +0000896
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000897 // Some live range has been lengthened due to colaescing, eliminate the
898 // unnecessary kills.
899 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
900 if (TargetRegisterInfo::isVirtualRegister(DstReg))
901 RemoveUnnecessaryKills(DstReg, *ResDstInt);
902
Evan Chengc8d044e2008-02-15 18:24:29 +0000903 // SrcReg is guarateed to be the register whose live interval that is
904 // being merged.
905 li_->removeInterval(SrcReg);
906 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
907
David Greene25133302007-06-08 17:18:56 +0000908 ++numJoins;
909 return true;
910}
911
912/// ComputeUltimateVN - Assuming we are going to join two live intervals,
913/// compute what the resultant value numbers for each value in the input two
914/// ranges will be. This is complicated by copies between the two which can
915/// and will commonly cause multiple value numbers to be merged into one.
916///
917/// VN is the value number that we're trying to resolve. InstDefiningValue
918/// keeps track of the new InstDefiningValue assignment for the result
919/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
920/// whether a value in this or other is a copy from the opposite set.
921/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
922/// already been assigned.
923///
924/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
925/// contains the value number the copy is from.
926///
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000927static unsigned ComputeUltimateVN(VNInfo *VNI,
928 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +0000929 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
930 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +0000931 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000932 SmallVector<int, 16> &OtherValNoAssignments) {
933 unsigned VN = VNI->id;
934
David Greene25133302007-06-08 17:18:56 +0000935 // If the VN has already been computed, just return it.
936 if (ThisValNoAssignments[VN] >= 0)
937 return ThisValNoAssignments[VN];
938// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000939
David Greene25133302007-06-08 17:18:56 +0000940 // If this val is not a copy from the other val, then it must be a new value
941 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +0000942 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +0000943 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000944 NewVNInfo.push_back(VNI);
945 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +0000946 }
Evan Chengc14b1442007-08-31 08:04:17 +0000947 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +0000948
949 // Otherwise, this *is* a copy from the RHS. If the other side has already
950 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000951 if (OtherValNoAssignments[OtherValNo->id] >= 0)
952 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +0000953
954 // Mark this value number as currently being computed, then ask what the
955 // ultimate value # of the other value is.
956 ThisValNoAssignments[VN] = -2;
957 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000958 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
959 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000960 return ThisValNoAssignments[VN] = UltimateVN;
961}
962
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000963static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +0000964 return std::find(V.begin(), V.end(), Val) != V.end();
965}
966
967/// SimpleJoin - Attempt to joint the specified interval into this one. The
968/// caller of this method must guarantee that the RHS only contains a single
969/// value number and that the RHS is not defined by a copy from this
970/// interval. This returns false if the intervals are not joinable, or it
971/// joins them and returns true.
Bill Wendling2674d712008-01-04 08:59:18 +0000972bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
David Greene25133302007-06-08 17:18:56 +0000973 assert(RHS.containsOneValue());
974
975 // Some number (potentially more than one) value numbers in the current
976 // interval may be defined as copies from the RHS. Scan the overlapping
977 // portions of the LHS and RHS, keeping track of this and looking for
978 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +0000979 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +0000980
981 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
982 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
983
984 if (LHSIt->start < RHSIt->start) {
985 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
986 if (LHSIt != LHS.begin()) --LHSIt;
987 } else if (RHSIt->start < LHSIt->start) {
988 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
989 if (RHSIt != RHS.begin()) --RHSIt;
990 }
991
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000992 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +0000993
994 while (1) {
995 // Determine if these live intervals overlap.
996 bool Overlaps = false;
997 if (LHSIt->start <= RHSIt->start)
998 Overlaps = LHSIt->end > RHSIt->start;
999 else
1000 Overlaps = RHSIt->end > LHSIt->start;
1001
1002 // If the live intervals overlap, there are two interesting cases: if the
1003 // LHS interval is defined by a copy from the RHS, it's ok and we record
1004 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +00001005 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +00001006 if (Overlaps) {
1007 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001008 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001009 // Copy from the RHS?
Evan Chengc8d044e2008-02-15 18:24:29 +00001010 unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
1011 if (SrcReg != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00001012 return false; // Nope, bail out.
1013
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001014 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001015 }
1016
1017 // We know this entire LHS live range is okay, so skip it now.
1018 if (++LHSIt == LHSEnd) break;
1019 continue;
1020 }
1021
1022 if (LHSIt->end < RHSIt->end) {
1023 if (++LHSIt == LHSEnd) break;
1024 } else {
1025 // One interesting case to check here. It's possible that we have
1026 // something like "X3 = Y" which defines a new value number in the LHS,
1027 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001028 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +00001029 // the live ranges don't actually overlap.
1030 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001031 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001032 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +00001033 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +00001034 if (++LHSIt == LHSEnd) break;
1035 } else {
1036 // Otherwise, if this is a copy from the RHS, mark it as being merged
1037 // in.
Evan Chengc8d044e2008-02-15 18:24:29 +00001038 if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001039 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001040
1041 // We know this entire LHS live range is okay, so skip it now.
1042 if (++LHSIt == LHSEnd) break;
1043 }
1044 }
1045 }
1046
1047 if (++RHSIt == RHSEnd) break;
1048 }
1049 }
1050
Gabor Greife510b3a2007-07-09 12:00:59 +00001051 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +00001052 // the value numbers in EliminatedLHSVals will all be merged together. Since
1053 // the most common case is that EliminatedLHSVals has a single number, we
1054 // optimize for it: if there is more than one value, we merge them all into
1055 // the lowest numbered one, then handle the interval as if we were merging
1056 // with one value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001057 VNInfo *LHSValNo;
David Greene25133302007-06-08 17:18:56 +00001058 if (EliminatedLHSVals.size() > 1) {
1059 // Loop through all the equal value numbers merging them into the smallest
1060 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001061 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +00001062 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001063 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +00001064 // Merge the current notion of the smallest into the smaller one.
1065 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1066 Smallest = EliminatedLHSVals[i];
1067 } else {
1068 // Merge into the smallest.
1069 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1070 }
1071 }
1072 LHSValNo = Smallest;
1073 } else {
1074 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1075 LHSValNo = EliminatedLHSVals[0];
1076 }
1077
1078 // Okay, now that there is a single LHS value number that we're merging the
1079 // RHS into, update the value number info for the LHS to indicate that the
1080 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +00001081 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001082 LHSValNo->def = VNI->def;
1083 LHSValNo->copy = VNI->copy;
David Greene25133302007-06-08 17:18:56 +00001084
1085 // Okay, the final step is to loop over the RHS live intervals, adding them to
1086 // the LHS.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001087 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001088 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +00001089 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +00001090 LHS.weight += RHS.weight;
1091 if (RHS.preference && !LHS.preference)
1092 LHS.preference = RHS.preference;
1093
1094 return true;
1095}
1096
1097/// JoinIntervals - Attempt to join these two intervals. On failure, this
1098/// returns false. Otherwise, if one of the intervals being joined is a
1099/// physreg, this method always canonicalizes LHS to be it. The output
1100/// "RHS" will not have been modified, so we can use this information
1101/// below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001102bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1103 LiveInterval &RHS, bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +00001104 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +00001105 // coalesced.
David Greene25133302007-06-08 17:18:56 +00001106 SmallVector<int, 16> LHSValNoAssignments;
1107 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +00001108 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1109 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001110 SmallVector<VNInfo*, 16> NewVNInfo;
David Greene25133302007-06-08 17:18:56 +00001111
1112 // If a live interval is a physical register, conservatively check if any
1113 // of its sub-registers is overlapping the live interval of the virtual
1114 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001115 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1116 *tri_->getSubRegisters(LHS.reg)) {
1117 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001118 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1119 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001120 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001121 return false;
1122 }
Dan Gohman6f0d0242008-02-10 18:45:23 +00001123 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1124 *tri_->getSubRegisters(RHS.reg)) {
1125 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001126 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1127 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001128 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001129 return false;
1130 }
1131 }
1132
1133 // Compute ultimate value numbers for the LHS and RHS values.
1134 if (RHS.containsOneValue()) {
1135 // Copies from a liveinterval with a single value are simple to handle and
1136 // very common, handle the special case here. This is important, because
1137 // often RHS is small and LHS is large (e.g. a physreg).
1138
1139 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +00001140 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +00001141 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001142 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001143 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001144 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1145 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001146 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +00001147 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +00001148 // can't swap the LHS/RHS intervals though.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001149 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001150 return SimpleJoin(LHS, RHS);
1151 } else {
Evan Chengc14b1442007-08-31 08:04:17 +00001152 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001153 }
1154 } else {
1155 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +00001156 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001157 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001158 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +00001159 }
1160
1161 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1162 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001163 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +00001164
1165 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1166 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001167 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1168 i != e; ++i) {
1169 VNInfo *VNI = *i;
1170 unsigned VN = VNI->id;
Evan Chengc8d044e2008-02-15 18:24:29 +00001171 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1172 if (LHSSrcReg != RHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001173 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +00001174 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001175 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001176 LHSValNoAssignments[VN] = VN;
1177 } else if (RHSValID == -1) {
1178 // Otherwise, it is a copy from the RHS, and we don't already have a
1179 // value# for it. Keep the current value number, but remember it.
1180 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001181 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001182 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001183 } else {
1184 // Otherwise, use the specified value #.
1185 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001186 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1187 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001188 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001189 }
David Greene25133302007-06-08 17:18:56 +00001190 }
1191 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001192 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001193 LHSValNoAssignments[VN] = VN;
1194 }
1195 }
1196
1197 assert(RHSValID != -1 && "Didn't find value #?");
1198 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001199 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +00001200 // This path doesn't go through ComputeUltimateVN so just set
1201 // it to anything.
1202 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001203 }
David Greene25133302007-06-08 17:18:56 +00001204 } else {
1205 // Loop over the value numbers of the LHS, seeing if any are defined from
1206 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001207 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1208 i != e; ++i) {
1209 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001210 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001211 continue;
1212
1213 // DstReg is known to be a register in the LHS interval. If the src is
1214 // from the RHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001215 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00001216 continue;
1217
1218 // Figure out the value # from the RHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001219 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001220 }
1221
1222 // Loop over the value numbers of the RHS, seeing if any are defined from
1223 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001224 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1225 i != e; ++i) {
1226 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001227 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001228 continue;
1229
1230 // DstReg is known to be a register in the RHS interval. If the src is
1231 // from the LHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001232 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
David Greene25133302007-06-08 17:18:56 +00001233 continue;
1234
1235 // Figure out the value # from the LHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001236 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001237 }
1238
1239 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1240 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001241 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +00001242
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001243 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1244 i != e; ++i) {
1245 VNInfo *VNI = *i;
1246 unsigned VN = VNI->id;
1247 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001248 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001249 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001250 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001251 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001252 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001253 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1254 i != e; ++i) {
1255 VNInfo *VNI = *i;
1256 unsigned VN = VNI->id;
1257 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001258 continue;
1259 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +00001260 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001261 NewVNInfo.push_back(VNI);
1262 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001263 continue;
1264 }
1265
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001266 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001267 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001268 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001269 }
1270 }
1271
1272 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +00001273 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +00001274 LiveInterval::const_iterator I = LHS.begin();
1275 LiveInterval::const_iterator IE = LHS.end();
1276 LiveInterval::const_iterator J = RHS.begin();
1277 LiveInterval::const_iterator JE = RHS.end();
1278
1279 // Skip ahead until the first place of potential sharing.
1280 if (I->start < J->start) {
1281 I = std::upper_bound(I, IE, J->start);
1282 if (I != LHS.begin()) --I;
1283 } else if (J->start < I->start) {
1284 J = std::upper_bound(J, JE, I->start);
1285 if (J != RHS.begin()) --J;
1286 }
1287
1288 while (1) {
1289 // Determine if these two live ranges overlap.
1290 bool Overlaps;
1291 if (I->start < J->start) {
1292 Overlaps = I->end > J->start;
1293 } else {
1294 Overlaps = J->end > I->start;
1295 }
1296
1297 // If so, check value # info to determine if they are really different.
1298 if (Overlaps) {
1299 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +00001300 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001301 if (LHSValNoAssignments[I->valno->id] !=
1302 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +00001303 return false;
1304 }
1305
1306 if (I->end < J->end) {
1307 ++I;
1308 if (I == IE) break;
1309 } else {
1310 ++J;
1311 if (J == JE) break;
1312 }
1313 }
1314
Evan Cheng34729252007-10-14 10:08:34 +00001315 // Update kill info. Some live ranges are extended due to copy coalescing.
1316 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1317 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1318 VNInfo *VNI = I->first;
1319 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1320 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001321 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001322 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1323 }
1324
1325 // Update kill info. Some live ranges are extended due to copy coalescing.
1326 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1327 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1328 VNInfo *VNI = I->first;
1329 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1330 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001331 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001332 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1333 }
1334
Gabor Greife510b3a2007-07-09 12:00:59 +00001335 // If we get here, we know that we can coalesce the live ranges. Ask the
1336 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001337 if ((RHS.ranges.size() > LHS.ranges.size() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00001338 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1339 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001340 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001341 Swapped = true;
1342 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001343 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001344 Swapped = false;
1345 }
David Greene25133302007-06-08 17:18:56 +00001346 return true;
1347}
1348
1349namespace {
1350 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1351 // depth of the basic block (the unsigned), and then on the MBB number.
1352 struct DepthMBBCompare {
1353 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1354 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1355 if (LHS.first > RHS.first) return true; // Deeper loops first
1356 return LHS.first == RHS.first &&
1357 LHS.second->getNumber() < RHS.second->getNumber();
1358 }
1359 };
1360}
1361
Evan Cheng8fc9a102007-11-06 08:52:21 +00001362/// getRepIntervalSize - Returns the size of the interval that represents the
1363/// specified register.
1364template<class SF>
1365unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1366 return Rc->getRepIntervalSize(Reg);
1367}
1368
1369/// CopyRecSort::operator - Join priority queue sorting function.
1370///
1371bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1372 // Inner loops first.
1373 if (left.LoopDepth > right.LoopDepth)
1374 return false;
Evan Chengc8d044e2008-02-15 18:24:29 +00001375 else if (left.LoopDepth == right.LoopDepth)
Evan Cheng8fc9a102007-11-06 08:52:21 +00001376 if (left.isBackEdge && !right.isBackEdge)
1377 return false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001378 return true;
1379}
1380
Gabor Greife510b3a2007-07-09 12:00:59 +00001381void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00001382 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00001383 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00001384
Evan Cheng8b0b8742007-10-16 08:04:24 +00001385 std::vector<CopyRec> VirtCopies;
1386 std::vector<CopyRec> PhysCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001387 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00001388 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1389 MII != E;) {
1390 MachineInstr *Inst = MII++;
1391
Evan Cheng32dfbea2007-10-12 08:50:34 +00001392 // If this isn't a copy nor a extract_subreg, we can't join intervals.
David Greene25133302007-06-08 17:18:56 +00001393 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001394 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1395 DstReg = Inst->getOperand(0).getReg();
1396 SrcReg = Inst->getOperand(1).getReg();
1397 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1398 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00001399
Evan Chengc8d044e2008-02-15 18:24:29 +00001400 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1401 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00001402 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001403 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001404 } else {
1405 if (SrcIsPhys || DstIsPhys)
Evan Chengc8d044e2008-02-15 18:24:29 +00001406 PhysCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001407 else
Evan Chengc8d044e2008-02-15 18:24:29 +00001408 VirtCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001409 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00001410 }
1411
Evan Cheng8fc9a102007-11-06 08:52:21 +00001412 if (NewHeuristic)
1413 return;
1414
Evan Cheng8b0b8742007-10-16 08:04:24 +00001415 // Try coalescing physical register + virtual register first.
1416 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1417 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001418 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001419 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001420 if (Again)
1421 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00001422 }
1423 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1424 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001425 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001426 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001427 if (Again)
1428 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00001429 }
1430}
1431
1432void SimpleRegisterCoalescing::joinIntervals() {
1433 DOUT << "********** JOINING INTERVALS ***********\n";
1434
Evan Cheng8fc9a102007-11-06 08:52:21 +00001435 if (NewHeuristic)
1436 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1437
David Greene25133302007-06-08 17:18:56 +00001438 std::vector<CopyRec> TryAgainList;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001439 if (loopInfo->begin() == loopInfo->end()) {
David Greene25133302007-06-08 17:18:56 +00001440 // If there are no loops in the function, join intervals in function order.
1441 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1442 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001443 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001444 } else {
1445 // Otherwise, join intervals in inner loops before other intervals.
1446 // Unfortunately we can't just iterate over loop hierarchy here because
1447 // there may be more MBB's than BB's. Collect MBB's for sorting.
1448
1449 // Join intervals in the function prolog first. We want to join physical
1450 // registers with virtual registers before the intervals got too long.
1451 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001452 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1453 MachineBasicBlock *MBB = I;
1454 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1455 }
David Greene25133302007-06-08 17:18:56 +00001456
1457 // Sort by loop depth.
1458 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1459
1460 // Finally, join intervals in loop nest order.
1461 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001462 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001463 }
1464
1465 // Joining intervals can allow other intervals to be joined. Iteratively join
1466 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001467 if (NewHeuristic) {
1468 SmallVector<CopyRec, 16> TryAgain;
1469 bool ProgressMade = true;
1470 while (ProgressMade) {
1471 ProgressMade = false;
1472 while (!JoinQueue->empty()) {
1473 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00001474 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001475 bool Success = JoinCopy(R, Again);
1476 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00001477 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001478 else if (Again)
1479 TryAgain.push_back(R);
1480 }
1481
1482 if (ProgressMade) {
1483 while (!TryAgain.empty()) {
1484 JoinQueue->push(TryAgain.back());
1485 TryAgain.pop_back();
1486 }
1487 }
1488 }
1489 } else {
1490 bool ProgressMade = true;
1491 while (ProgressMade) {
1492 ProgressMade = false;
1493
1494 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1495 CopyRec &TheCopy = TryAgainList[i];
1496 if (TheCopy.MI) {
1497 bool Again = false;
1498 bool Success = JoinCopy(TheCopy, Again);
1499 if (Success || !Again) {
1500 TheCopy.MI = 0; // Mark this one as done.
1501 ProgressMade = true;
1502 }
Evan Cheng0547bab2007-11-01 06:22:48 +00001503 }
David Greene25133302007-06-08 17:18:56 +00001504 }
1505 }
1506 }
1507
Evan Cheng8fc9a102007-11-06 08:52:21 +00001508 if (NewHeuristic)
Evan Chengc8d044e2008-02-15 18:24:29 +00001509 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00001510}
1511
1512/// Return true if the two specified registers belong to different register
1513/// classes. The registers may be either phys or virt regs.
1514bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
Evan Cheng32dfbea2007-10-12 08:50:34 +00001515 unsigned RegB) const {
David Greene25133302007-06-08 17:18:56 +00001516
1517 // Get the register classes for the first reg.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001518 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1519 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
David Greene25133302007-06-08 17:18:56 +00001520 "Shouldn't consider two physregs!");
Evan Chengc8d044e2008-02-15 18:24:29 +00001521 return !mri_->getRegClass(RegB)->contains(RegA);
David Greene25133302007-06-08 17:18:56 +00001522 }
1523
1524 // Compare against the regclass for the second reg.
Evan Chengc8d044e2008-02-15 18:24:29 +00001525 const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001526 if (TargetRegisterInfo::isVirtualRegister(RegB))
Evan Chengc8d044e2008-02-15 18:24:29 +00001527 return RegClass != mri_->getRegClass(RegB);
David Greene25133302007-06-08 17:18:56 +00001528 else
1529 return !RegClass->contains(RegB);
1530}
1531
1532/// lastRegisterUse - Returns the last use of the specific register between
Evan Chengc8d044e2008-02-15 18:24:29 +00001533/// cycles Start and End or NULL if there are no uses.
1534MachineOperand *
Chris Lattner84bc5422007-12-31 04:13:23 +00001535SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
Evan Chengc8d044e2008-02-15 18:24:29 +00001536 unsigned Reg, unsigned &UseIdx) const{
1537 UseIdx = 0;
1538 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1539 MachineOperand *LastUse = NULL;
1540 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1541 E = mri_->use_end(); I != E; ++I) {
1542 MachineOperand &Use = I.getOperand();
1543 MachineInstr *UseMI = Use.getParent();
Evan Chenga2fb6342008-03-25 02:02:19 +00001544 unsigned SrcReg, DstReg;
1545 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1546 // Ignore identity copies.
1547 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +00001548 unsigned Idx = li_->getInstructionIndex(UseMI);
1549 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1550 LastUse = &Use;
1551 UseIdx = Idx;
1552 }
1553 }
1554 return LastUse;
1555 }
1556
David Greene25133302007-06-08 17:18:56 +00001557 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1558 int s = Start;
1559 while (e >= s) {
1560 // Skip deleted instructions
1561 MachineInstr *MI = li_->getInstructionFromIndex(e);
1562 while ((e - InstrSlots::NUM) >= s && !MI) {
1563 e -= InstrSlots::NUM;
1564 MI = li_->getInstructionFromIndex(e);
1565 }
1566 if (e < s || MI == NULL)
1567 return NULL;
1568
Evan Chenga2fb6342008-03-25 02:02:19 +00001569 // Ignore identity copies.
1570 unsigned SrcReg, DstReg;
1571 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1572 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1573 MachineOperand &Use = MI->getOperand(i);
1574 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1575 tri_->regsOverlap(Use.getReg(), Reg)) {
1576 UseIdx = e;
1577 return &Use;
1578 }
David Greene25133302007-06-08 17:18:56 +00001579 }
David Greene25133302007-06-08 17:18:56 +00001580
1581 e -= InstrSlots::NUM;
1582 }
1583
1584 return NULL;
1585}
1586
1587
David Greene25133302007-06-08 17:18:56 +00001588void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +00001589 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001590 cerr << tri_->getName(reg);
David Greene25133302007-06-08 17:18:56 +00001591 else
1592 cerr << "%reg" << reg;
1593}
1594
1595void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001596 JoinedCopies.clear();
David Greene25133302007-06-08 17:18:56 +00001597}
1598
1599static bool isZeroLengthInterval(LiveInterval *li) {
1600 for (LiveInterval::Ranges::const_iterator
1601 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1602 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1603 return false;
1604 return true;
1605}
1606
1607bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1608 mf_ = &fn;
Evan Cheng70071432008-02-13 03:01:43 +00001609 mri_ = &fn.getRegInfo();
David Greene25133302007-06-08 17:18:56 +00001610 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001611 tri_ = tm_->getRegisterInfo();
David Greene25133302007-06-08 17:18:56 +00001612 tii_ = tm_->getInstrInfo();
1613 li_ = &getAnalysis<LiveIntervals>();
1614 lv_ = &getAnalysis<LiveVariables>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00001615 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00001616
1617 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1618 << "********** Function: "
1619 << ((Value*)mf_->getFunction())->getName() << '\n';
1620
Dan Gohman6f0d0242008-02-10 18:45:23 +00001621 allocatableRegs_ = tri_->getAllocatableSet(fn);
1622 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1623 E = tri_->regclass_end(); I != E; ++I)
Bill Wendling2674d712008-01-04 08:59:18 +00001624 allocatableRCRegs_.insert(std::make_pair(*I,
Dan Gohman6f0d0242008-02-10 18:45:23 +00001625 tri_->getAllocatableSet(fn, *I)));
David Greene25133302007-06-08 17:18:56 +00001626
Gabor Greife510b3a2007-07-09 12:00:59 +00001627 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00001628 if (EnableJoining) {
1629 joinIntervals();
1630 DOUT << "********** INTERVALS POST JOINING **********\n";
Bill Wendling2674d712008-01-04 08:59:18 +00001631 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
Dan Gohman6f0d0242008-02-10 18:45:23 +00001632 I->second.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00001633 DOUT << "\n";
1634 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001635
Evan Cheng8fc9a102007-11-06 08:52:21 +00001636 // Delete all coalesced copies.
1637 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1638 E = JoinedCopies.end(); I != E; ++I) {
Evan Cheng3c88d742008-03-18 08:26:47 +00001639 MachineInstr *CopyMI = *I;
1640 unsigned SrcReg, DstReg;
1641 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg);
1642 if (CopyMI->registerDefIsDead(DstReg)) {
1643 LiveInterval &li = li_->getInterval(DstReg);
1644 ShortenDeadCopySrcLiveRange(li, CopyMI);
1645 ShortenDeadCopyLiveRange(li, CopyMI);
1646 }
Evan Cheng8fc9a102007-11-06 08:52:21 +00001647 li_->RemoveMachineInstrFromMaps(*I);
1648 (*I)->eraseFromParent();
Evan Cheng70071432008-02-13 03:01:43 +00001649 ++numPeep;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001650 }
David Greene25133302007-06-08 17:18:56 +00001651 }
1652
Evan Chengc8d044e2008-02-15 18:24:29 +00001653 // Perform a final pass over the instructions and compute spill weights
1654 // and remove identity moves.
David Greene25133302007-06-08 17:18:56 +00001655 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1656 mbbi != mbbe; ++mbbi) {
1657 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001658 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00001659
1660 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1661 mii != mie; ) {
1662 // if the move will be an identity move delete it
Evan Chengc8d044e2008-02-15 18:24:29 +00001663 unsigned srcReg, dstReg;
1664 if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
Evan Cheng3c88d742008-03-18 08:26:47 +00001665 if (li_->hasInterval(srcReg)) {
1666 LiveInterval &RegInt = li_->getInterval(srcReg);
1667 // If def of this move instruction is dead, remove its live range
1668 // from the dstination register's live interval.
1669 if (mii->registerDefIsDead(dstReg)) {
1670 ShortenDeadCopySrcLiveRange(RegInt, mii);
1671 ShortenDeadCopyLiveRange(RegInt, mii);
1672 }
1673 }
David Greene25133302007-06-08 17:18:56 +00001674 li_->RemoveMachineInstrFromMaps(mii);
1675 mii = mbbi->erase(mii);
1676 ++numPeep;
1677 } else {
1678 SmallSet<unsigned, 4> UniqueUses;
1679 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1680 const MachineOperand &mop = mii->getOperand(i);
1681 if (mop.isRegister() && mop.getReg() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00001682 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001683 unsigned reg = mop.getReg();
David Greene25133302007-06-08 17:18:56 +00001684 // Multiple uses of reg by the same instruction. It should not
1685 // contribute to spill weight again.
1686 if (UniqueUses.count(reg) != 0)
1687 continue;
1688 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001689 RegInt.weight +=
1690 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00001691 UniqueUses.insert(reg);
1692 }
1693 }
1694 ++mii;
1695 }
1696 }
1697 }
1698
1699 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1700 LiveInterval &LI = I->second;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001701 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
David Greene25133302007-06-08 17:18:56 +00001702 // If the live interval length is essentially zero, i.e. in every live
1703 // range the use follows def immediately, it doesn't make sense to spill
1704 // it and hope it will be easier to allocate for this li.
1705 if (isZeroLengthInterval(&LI))
1706 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001707 else {
1708 bool isLoad = false;
Evan Cheng63a18c42008-02-09 08:36:28 +00001709 if (li_->isReMaterializable(LI, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00001710 // If all of the definitions of the interval are re-materializable,
1711 // it is a preferred candidate for spilling. If non of the defs are
1712 // loads, then it's potentially very cheap to re-materialize.
1713 // FIXME: this gets much more complicated once we support non-trivial
1714 // re-materialization.
1715 if (isLoad)
1716 LI.weight *= 0.9F;
1717 else
1718 LI.weight *= 0.5F;
1719 }
1720 }
David Greene25133302007-06-08 17:18:56 +00001721
1722 // Slightly prefer live interval that has been assigned a preferred reg.
1723 if (LI.preference)
1724 LI.weight *= 1.01F;
1725
1726 // Divide the weight of the interval by its size. This encourages
1727 // spilling of intervals that are large and have few uses, and
1728 // discourages spilling of small intervals with many uses.
1729 LI.weight /= LI.getSize();
1730 }
1731 }
1732
1733 DEBUG(dump());
1734 return true;
1735}
1736
1737/// print - Implement the dump method.
1738void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1739 li_->print(O, m);
1740}
David Greene2c17c4d2007-09-06 16:18:45 +00001741
1742RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1743 return new SimpleRegisterCoalescing();
1744}
1745
1746// Make sure that anything that uses RegisterCoalescer pulls in this file...
1747DEFINING_FILE_FOR(SimpleRegisterCoalescing)