blob: cfc77eef046157c9ba0311d896c646f3344d05a6 [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/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
David Greene25133302007-06-08 17:18:56 +000024#include "llvm/CodeGen/Passes.h"
David Greene2c17c4d2007-09-06 16:18:45 +000025#include "llvm/CodeGen/RegisterCoalescer.h"
David Greene25133302007-06-08 17:18:56 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000028#include "llvm/Target/TargetOptions.h"
David Greene25133302007-06-08 17:18:56 +000029#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 Chenge00f5de2008-06-19 01:39:21 +000039STATISTIC(numSubJoins , "Number of subclass joins performed");
Evan Cheng70071432008-02-13 03:01:43 +000040STATISTIC(numCommutes , "Number of instruction commuting performed");
41STATISTIC(numExtends , "Number of copies extended");
Evan Chengcd047082008-08-30 09:09:33 +000042STATISTIC(NumReMats , "Number of instructions re-materialized");
David Greene25133302007-06-08 17:18:56 +000043STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
44STATISTIC(numAborts , "Number of times interval joining aborted");
45
46char SimpleRegisterCoalescing::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000047static cl::opt<bool>
48EnableJoining("join-liveintervals",
49 cl::desc("Coalesce copies (default=true)"),
50 cl::init(true));
David Greene25133302007-06-08 17:18:56 +000051
Dan Gohman844731a2008-05-13 00:00:25 +000052static cl::opt<bool>
53NewHeuristic("new-coalescer-heuristic",
Evan Chenge00f5de2008-06-19 01:39:21 +000054 cl::desc("Use new coalescer heuristic"),
55 cl::init(false), cl::Hidden);
56
57static cl::opt<bool>
58CrossClassJoin("join-subclass-copies",
59 cl::desc("Coalesce copies to sub- register class"),
60 cl::init(false), cl::Hidden);
Evan Cheng8fc9a102007-11-06 08:52:21 +000061
Dan Gohman844731a2008-05-13 00:00:25 +000062static RegisterPass<SimpleRegisterCoalescing>
63X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000064
Dan Gohman844731a2008-05-13 00:00:25 +000065// Declare that we implement the RegisterCoalescer interface
66static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000067
Dan Gohman6ddba2b2008-05-13 02:05:11 +000068const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
David Greene25133302007-06-08 17:18:56 +000069
70void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
Evan Chengbbeeb2a2008-09-22 20:58:04 +000071 AU.addRequired<LiveIntervals>();
David Greene25133302007-06-08 17:18:56 +000072 AU.addPreserved<LiveIntervals>();
Evan Chengbbeeb2a2008-09-22 20:58:04 +000073 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000074 AU.addPreserved<MachineLoopInfo>();
75 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000076 if (StrongPHIElim)
77 AU.addPreservedID(StrongPHIEliminationID);
78 else
79 AU.addPreservedID(PHIEliminationID);
David Greene25133302007-06-08 17:18:56 +000080 AU.addPreservedID(TwoAddressInstructionPassID);
David Greene25133302007-06-08 17:18:56 +000081 MachineFunctionPass::getAnalysisUsage(AU);
82}
83
Gabor Greife510b3a2007-07-09 12:00:59 +000084/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000085/// being the source and IntB being the dest, thus this defines a value number
86/// in IntB. If the source value number (in IntA) is defined by a copy from B,
87/// see if we can merge these two pieces of B into a single value number,
88/// eliminating a copy. For example:
89///
90/// A3 = B0
91/// ...
92/// B1 = A3 <- this copy
93///
94/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
95/// value number to be replaced with B0 (which simplifies the B liveinterval).
96///
97/// This returns true if an interval was modified.
98///
Bill Wendling2674d712008-01-04 08:59:18 +000099bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
100 LiveInterval &IntB,
101 MachineInstr *CopyMI) {
David Greene25133302007-06-08 17:18:56 +0000102 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
103
104 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
105 // the example above.
106 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000107 if (BLR == IntB.end()) // Should never happen!
108 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000109 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000110
111 // Get the location that B is defined at. Two options: either this value has
112 // an unknown definition point or it is defined at CopyIdx. If unknown, we
113 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000114 if (!BValNo->copy) return false;
115 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
David Greene25133302007-06-08 17:18:56 +0000116
Evan Cheng70071432008-02-13 03:01:43 +0000117 // AValNo is the value number in A that defines the copy, A3 in the example.
118 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000119 if (ALR == IntA.end()) // Should never happen!
120 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000121 VNInfo *AValNo = ALR->valno;
Evan Cheng5379f412008-12-19 20:58:01 +0000122 // If it's re-defined by an early clobber somewhere in the live range, then
123 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
124 // See PR3149:
125 // 172 %ECX<def> = MOV32rr %reg1039<kill>
126 // 180 INLINEASM <es:subl $5,$1
127 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
128 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
129 // 188 %EAX<def> = MOV32rr %EAX<kill>
130 // 196 %ECX<def> = MOV32rr %ECX<kill>
131 // 204 %ECX<def> = MOV32rr %ECX<kill>
132 // 212 %EAX<def> = MOV32rr %EAX<kill>
133 // 220 %EAX<def> = MOV32rr %EAX
134 // 228 %reg1039<def> = MOV32rr %ECX<kill>
135 // The early clobber operand ties ECX input to the ECX def.
136 //
137 // The live interval of ECX is represented as this:
138 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
139 // The coalescer has no idea there was a def in the middle of [174,230].
140 if (AValNo->redefByEC)
141 return false;
David Greene25133302007-06-08 17:18:56 +0000142
Evan Cheng70071432008-02-13 03:01:43 +0000143 // If AValNo is defined as a copy from IntB, we can potentially process this.
David Greene25133302007-06-08 17:18:56 +0000144 // Get the instruction that defines this value number.
Evan Chengc8d044e2008-02-15 18:24:29 +0000145 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
David Greene25133302007-06-08 17:18:56 +0000146 if (!SrcReg) return false; // Not defined by a copy.
147
148 // If the value number is not defined by a copy instruction, ignore it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000149
David Greene25133302007-06-08 17:18:56 +0000150 // If the source register comes from an interval other than IntB, we can't
151 // handle this.
Evan Chengc8d044e2008-02-15 18:24:29 +0000152 if (SrcReg != IntB.reg) return false;
David Greene25133302007-06-08 17:18:56 +0000153
154 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000155 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000156 if (ValLR == IntB.end()) // Should never happen!
157 return false;
David Greene25133302007-06-08 17:18:56 +0000158
159 // Make sure that the end of the live range is inside the same block as
160 // CopyMI.
161 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
162 if (!ValLREndInst ||
163 ValLREndInst->getParent() != CopyMI->getParent()) return false;
164
165 // Okay, we now know that ValLR ends in the same block that the CopyMI
166 // live-range starts. If there are no intervening live ranges between them in
167 // IntB, we can merge them.
168 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000169
170 // If a live interval is a physical register, conservatively check if any
171 // of its sub-registers is overlapping the live interval of the virtual
172 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000173 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
174 *tri_->getSubRegisters(IntB.reg)) {
175 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
Evan Chengdc5294f2007-08-14 23:19:28 +0000176 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
177 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000178 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Chengdc5294f2007-08-14 23:19:28 +0000179 return false;
180 }
181 }
David Greene25133302007-06-08 17:18:56 +0000182
Dan Gohman6f0d0242008-02-10 18:45:23 +0000183 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000184
Evan Chenga8d94f12007-08-07 23:49:57 +0000185 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000186 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000187 // that defines this value #'. Update the the valnum with the new defining
188 // instruction #.
Evan Chengc8d044e2008-02-15 18:24:29 +0000189 BValNo->def = FillerStart;
190 BValNo->copy = NULL;
David Greene25133302007-06-08 17:18:56 +0000191
192 // Okay, we can merge them. We need to insert a new liverange:
193 // [ValLR.end, BLR.begin) of either value number, then we merge the
194 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000195 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
196
197 // If the IntB live range is assigned to a physical register, and if that
198 // physreg has aliases,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000199 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
David Greene25133302007-06-08 17:18:56 +0000200 // Update the liveintervals of sub-registers.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000201 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
David Greene25133302007-06-08 17:18:56 +0000202 LiveInterval &AliasLI = li_->getInterval(*AS);
203 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000204 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000205 }
206 }
207
208 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng25f34a32008-09-15 06:28:41 +0000209 if (BValNo != ValLR->valno) {
210 IntB.addKills(ValLR->valno, BValNo->kills);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000211 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
Evan Cheng25f34a32008-09-15 06:28:41 +0000212 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000213 DOUT << " result = "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000214 DOUT << "\n";
215
216 // If the source instruction was killing the source register before the
217 // merge, unset the isKill marker given the live range has been extended.
218 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
Evan Cheng25f34a32008-09-15 06:28:41 +0000219 if (UIdx != -1) {
Chris Lattnerf7382302007-12-30 21:56:09 +0000220 ValLREndInst->getOperand(UIdx).setIsKill(false);
Evan Cheng25f34a32008-09-15 06:28:41 +0000221 IntB.removeKill(ValLR->valno, FillerStart);
222 }
Evan Cheng70071432008-02-13 03:01:43 +0000223
224 ++numExtends;
225 return true;
226}
227
Evan Cheng559f4222008-02-16 02:32:17 +0000228/// HasOtherReachingDefs - Return true if there are definitions of IntB
229/// other than BValNo val# that can reach uses of AValno val# of IntA.
230bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
231 LiveInterval &IntB,
232 VNInfo *AValNo,
233 VNInfo *BValNo) {
234 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
235 AI != AE; ++AI) {
236 if (AI->valno != AValNo) continue;
237 LiveInterval::Ranges::iterator BI =
238 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
239 if (BI != IntB.ranges.begin())
240 --BI;
241 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
242 if (BI->valno == BValNo)
243 continue;
244 if (BI->start <= AI->start && BI->end > AI->start)
245 return true;
246 if (BI->start > AI->start && BI->start < AI->end)
247 return true;
248 }
249 }
250 return false;
251}
252
Evan Cheng70071432008-02-13 03:01:43 +0000253/// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
254/// being the source and IntB being the dest, thus this defines a value number
255/// in IntB. If the source value number (in IntA) is defined by a commutable
256/// instruction and its other operand is coalesced to the copy dest register,
257/// see if we can transform the copy into a noop by commuting the definition. For
258/// example,
259///
260/// A3 = op A2 B0<kill>
261/// ...
262/// B1 = A3 <- this copy
263/// ...
264/// = op A3 <- more uses
265///
266/// ==>
267///
268/// B2 = op B0 A2<kill>
269/// ...
270/// B1 = B2 <- now an identify copy
271/// ...
272/// = op B2 <- more uses
273///
274/// This returns true if an interval was modified.
275///
276bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
277 LiveInterval &IntB,
278 MachineInstr *CopyMI) {
Evan Cheng70071432008-02-13 03:01:43 +0000279 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
280
Evan Chenga9407f52008-02-18 18:56:31 +0000281 // FIXME: For now, only eliminate the copy by commuting its def when the
282 // source register is a virtual register. We want to guard against cases
283 // where the copy is a back edge copy and commuting the def lengthen the
284 // live interval of the source register to the entire loop.
285 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
Evan Cheng96cfff02008-02-18 08:40:53 +0000286 return false;
287
Evan Chengc8d044e2008-02-15 18:24:29 +0000288 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
Evan Cheng70071432008-02-13 03:01:43 +0000289 // the example above.
290 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000291 if (BLR == IntB.end()) // Should never happen!
292 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000293 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000294
Evan Cheng70071432008-02-13 03:01:43 +0000295 // Get the location that B is defined at. Two options: either this value has
296 // an unknown definition point or it is defined at CopyIdx. If unknown, we
297 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000298 if (!BValNo->copy) return false;
Evan Cheng70071432008-02-13 03:01:43 +0000299 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
300
301 // AValNo is the value number in A that defines the copy, A3 in the example.
302 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000303 if (ALR == IntA.end()) // Should never happen!
304 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000305 VNInfo *AValNo = ALR->valno;
Evan Chenge35a6d12008-02-13 08:41:08 +0000306 // If other defs can reach uses of this def, then it's not safe to perform
307 // the optimization.
308 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
Evan Cheng70071432008-02-13 03:01:43 +0000309 return false;
310 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
311 const TargetInstrDesc &TID = DefMI->getDesc();
Evan Chengc8d044e2008-02-15 18:24:29 +0000312 unsigned NewDstIdx;
313 if (!TID.isCommutable() ||
314 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
Evan Cheng70071432008-02-13 03:01:43 +0000315 return false;
316
Evan Chengc8d044e2008-02-15 18:24:29 +0000317 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
318 unsigned NewReg = NewDstMO.getReg();
319 if (NewReg != IntB.reg || !NewDstMO.isKill())
Evan Cheng70071432008-02-13 03:01:43 +0000320 return false;
321
322 // Make sure there are no other definitions of IntB that would reach the
323 // uses which the new definition can reach.
Evan Cheng559f4222008-02-16 02:32:17 +0000324 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
325 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000326
Evan Chenged70cbb32008-03-26 19:03:01 +0000327 // If some of the uses of IntA.reg is already coalesced away, return false.
328 // It's not possible to determine whether it's safe to perform the coalescing.
329 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
330 UE = mri_->use_end(); UI != UE; ++UI) {
331 MachineInstr *UseMI = &*UI;
332 unsigned UseIdx = li_->getInstructionIndex(UseMI);
333 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000334 if (ULR == IntA.end())
335 continue;
Evan Chenged70cbb32008-03-26 19:03:01 +0000336 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
337 return false;
338 }
339
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000340 // At this point we have decided that it is legal to do this
341 // transformation. Start by commuting the instruction.
Evan Cheng70071432008-02-13 03:01:43 +0000342 MachineBasicBlock *MBB = DefMI->getParent();
343 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
Evan Cheng559f4222008-02-16 02:32:17 +0000344 if (!NewMI)
345 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000346 if (NewMI != DefMI) {
347 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
348 MBB->insert(DefMI, NewMI);
349 MBB->erase(DefMI);
350 }
Evan Cheng6130f662008-03-05 00:59:57 +0000351 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
Evan Cheng70071432008-02-13 03:01:43 +0000352 NewMI->getOperand(OpIdx).setIsKill();
353
Evan Cheng70071432008-02-13 03:01:43 +0000354 bool BHasPHIKill = BValNo->hasPHIKill;
355 SmallVector<VNInfo*, 4> BDeadValNos;
356 SmallVector<unsigned, 4> BKills;
357 std::map<unsigned, unsigned> BExtend;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000358
359 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
360 // A = or A, B
361 // ...
362 // B = A
363 // ...
364 // C = A<kill>
365 // ...
366 // = B
367 //
368 // then do not add kills of A to the newly created B interval.
369 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
370 if (Extended)
371 BExtend[ALR->end] = BLR->end;
372
373 // Update uses of IntA of the specific Val# with IntB.
Evan Cheng70071432008-02-13 03:01:43 +0000374 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
375 UE = mri_->use_end(); UI != UE;) {
376 MachineOperand &UseMO = UI.getOperand();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000377 MachineInstr *UseMI = &*UI;
Evan Cheng70071432008-02-13 03:01:43 +0000378 ++UI;
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000379 if (JoinedCopies.count(UseMI))
Evan Chenged70cbb32008-03-26 19:03:01 +0000380 continue;
Evan Cheng70071432008-02-13 03:01:43 +0000381 unsigned UseIdx = li_->getInstructionIndex(UseMI);
382 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000383 if (ULR == IntA.end() || ULR->valno != AValNo)
Evan Cheng70071432008-02-13 03:01:43 +0000384 continue;
385 UseMO.setReg(NewReg);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000386 if (UseMI == CopyMI)
387 continue;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000388 if (UseMO.isKill()) {
389 if (Extended)
390 UseMO.setIsKill(false);
391 else
392 BKills.push_back(li_->getUseIndex(UseIdx)+1);
393 }
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000394 unsigned SrcReg, DstReg;
395 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
396 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +0000397 if (DstReg == IntB.reg) {
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000398 // This copy will become a noop. If it's defining a new val#,
399 // remove that val# as well. However this live range is being
400 // extended to the end of the existing live range defined by the copy.
401 unsigned DefIdx = li_->getDefIndex(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000402 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000403 BHasPHIKill |= DLR->valno->hasPHIKill;
404 assert(DLR->valno->def == DefIdx);
405 BDeadValNos.push_back(DLR->valno);
406 BExtend[DLR->start] = DLR->end;
407 JoinedCopies.insert(UseMI);
408 // If this is a kill but it's going to be removed, the last use
409 // of the same val# is the new kill.
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000410 if (UseMO.isKill())
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000411 BKills.pop_back();
Evan Cheng70071432008-02-13 03:01:43 +0000412 }
413 }
414
415 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
416 // simply extend BLR if CopyMI doesn't end the range.
417 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
418
Evan Cheng739583b2008-06-17 20:11:16 +0000419 // Remove val#'s defined by copies that will be coalesced away.
Evan Cheng70071432008-02-13 03:01:43 +0000420 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
421 IntB.removeValNo(BDeadValNos[i]);
Evan Cheng739583b2008-06-17 20:11:16 +0000422
423 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
424 // is updated. Kills are also updated.
425 VNInfo *ValNo = BValNo;
426 ValNo->def = AValNo->def;
427 ValNo->copy = NULL;
428 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
429 unsigned Kill = ValNo->kills[j];
430 if (Kill != BLR->end)
431 BKills.push_back(Kill);
432 }
433 ValNo->kills.clear();
Evan Cheng70071432008-02-13 03:01:43 +0000434 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
435 AI != AE; ++AI) {
436 if (AI->valno != AValNo) continue;
437 unsigned End = AI->end;
438 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
439 if (EI != BExtend.end())
440 End = EI->second;
441 IntB.addRange(LiveRange(AI->start, End, ValNo));
442 }
443 IntB.addKills(ValNo, BKills);
444 ValNo->hasPHIKill = BHasPHIKill;
445
446 DOUT << " result = "; IntB.print(DOUT, tri_);
447 DOUT << "\n";
448
449 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
450 IntA.removeValNo(AValNo);
451 DOUT << " result = "; IntA.print(DOUT, tri_);
452 DOUT << "\n";
453
454 ++numCommutes;
David Greene25133302007-06-08 17:18:56 +0000455 return true;
456}
457
Evan Chengcd047082008-08-30 09:09:33 +0000458/// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
459/// computation, replace the copy by rematerialize the definition.
460bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
461 unsigned DstReg,
462 MachineInstr *CopyMI) {
463 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
464 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
465 if (SrcLR == SrcInt.end()) // Should never happen!
466 return false;
467 VNInfo *ValNo = SrcLR->valno;
468 // If other defs can reach uses of this def, then it's not safe to perform
469 // the optimization.
470 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
471 return false;
472 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
473 const TargetInstrDesc &TID = DefMI->getDesc();
474 if (!TID.isAsCheapAsAMove())
475 return false;
476 bool SawStore = false;
477 if (!DefMI->isSafeToMove(tii_, SawStore))
478 return false;
479
480 unsigned DefIdx = li_->getDefIndex(CopyIdx);
481 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
482 DLR->valno->copy = NULL;
Evan Cheng195cd3a2008-10-13 18:35:52 +0000483 // Don't forget to update sub-register intervals.
484 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
485 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
486 if (!li_->hasInterval(*SR))
487 continue;
488 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
489 if (DLR && DLR->valno->copy == CopyMI)
490 DLR->valno->copy = NULL;
491 }
492 }
Evan Chengcd047082008-08-30 09:09:33 +0000493
Evan Chengcd047082008-08-30 09:09:33 +0000494 MachineBasicBlock *MBB = CopyMI->getParent();
Dan Gohman3afda6e2008-10-21 03:24:31 +0000495 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
496 CopyMI->removeFromParent();
Evan Chengcd047082008-08-30 09:09:33 +0000497 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
498 MachineInstr *NewMI = prior(MII);
Chris Lattner99cbdff2008-10-11 23:59:03 +0000499 // CopyMI may have implicit operands, transfer them over to the newly
Evan Chengcd047082008-08-30 09:09:33 +0000500 // rematerialized instruction. And update implicit def interval valnos.
501 for (unsigned i = CopyMI->getDesc().getNumOperands(),
502 e = CopyMI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = CopyMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000504 if (MO.isReg() && MO.isImplicit())
Evan Chengcd047082008-08-30 09:09:33 +0000505 NewMI->addOperand(MO);
Owen Anderson369e9872008-09-10 20:41:13 +0000506 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
Evan Chengcd047082008-08-30 09:09:33 +0000507 unsigned Reg = MO.getReg();
508 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
509 if (DLR && DLR->valno->copy == CopyMI)
510 DLR->valno->copy = NULL;
511 }
512 }
513
514 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
Dan Gohman3afda6e2008-10-21 03:24:31 +0000515 MBB->getParent()->DeleteMachineInstr(CopyMI);
Evan Chengcd047082008-08-30 09:09:33 +0000516 ReMatCopies.insert(CopyMI);
Evan Cheng20580a12008-09-19 17:38:47 +0000517 ReMatDefs.insert(DefMI);
Evan Chengcd047082008-08-30 09:09:33 +0000518 ++NumReMats;
519 return true;
520}
521
Evan Cheng8fc9a102007-11-06 08:52:21 +0000522/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
523///
524bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
Evan Cheng7e073ba2008-04-09 20:57:25 +0000525 unsigned DstReg) const {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000526 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000527 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000528 if (!L)
529 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000530 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000531 return false;
532
Evan Cheng8fc9a102007-11-06 08:52:21 +0000533 LiveInterval &LI = li_->getInterval(DstReg);
534 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
535 LiveInterval::const_iterator DstLR =
536 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
537 if (DstLR == LI.end())
538 return false;
Owen Andersonb3db9c92008-06-23 22:12:23 +0000539 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
Evan Cheng70071432008-02-13 03:01:43 +0000540 if (DstLR->valno->kills.size() == 1 &&
541 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
Evan Cheng8fc9a102007-11-06 08:52:21 +0000542 return true;
543 return false;
544}
545
Evan Chengc8d044e2008-02-15 18:24:29 +0000546/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
547/// update the subregister number if it is not zero. If DstReg is a
548/// physical register and the existing subregister number of the def / use
549/// being updated is not zero, make sure to set it to the correct physical
550/// subregister.
551void
552SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
553 unsigned SubIdx) {
554 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
555 if (DstIsPhys && SubIdx) {
556 // Figure out the real physical register we are updating with.
557 DstReg = tri_->getSubReg(DstReg, SubIdx);
558 SubIdx = 0;
559 }
560
561 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
562 E = mri_->reg_end(); I != E; ) {
563 MachineOperand &O = I.getOperand();
Evan Cheng70366b92008-03-21 19:09:30 +0000564 MachineInstr *UseMI = &*I;
Evan Chengc8d044e2008-02-15 18:24:29 +0000565 ++I;
Evan Cheng621d1572008-04-17 00:06:42 +0000566 unsigned OldSubIdx = O.getSubReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000567 if (DstIsPhys) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000568 unsigned UseDstReg = DstReg;
Evan Cheng621d1572008-04-17 00:06:42 +0000569 if (OldSubIdx)
570 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
Evan Chengcd047082008-08-30 09:09:33 +0000571
572 unsigned CopySrcReg, CopyDstReg;
573 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
574 CopySrcReg != CopyDstReg &&
575 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
576 // If the use is a copy and it won't be coalesced away, and its source
577 // is defined by a trivial computation, try to rematerialize it instead.
578 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
579 continue;
580 }
581
Evan Chengc8d044e2008-02-15 18:24:29 +0000582 O.setReg(UseDstReg);
583 O.setSubReg(0);
Evan Chengee9e1b02008-09-12 18:13:14 +0000584 continue;
585 }
586
587 // Sub-register indexes goes from small to large. e.g.
588 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
589 // EAX: 1 -> AL, 2 -> AX
590 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
591 // sub-register 2 is also AX.
592 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
593 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
594 else if (SubIdx)
595 O.setSubReg(SubIdx);
596 // Remove would-be duplicated kill marker.
597 if (O.isKill() && UseMI->killsRegister(DstReg))
598 O.setIsKill(false);
599 O.setReg(DstReg);
600
601 // After updating the operand, check if the machine instruction has
602 // become a copy. If so, update its val# information.
603 const TargetInstrDesc &TID = UseMI->getDesc();
604 unsigned CopySrcReg, CopyDstReg;
605 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
606 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
Evan Cheng870e4be2008-09-17 18:36:25 +0000607 CopySrcReg != CopyDstReg &&
608 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
609 allocatableRegs_[CopyDstReg])) {
Evan Chengee9e1b02008-09-12 18:13:14 +0000610 LiveInterval &LI = li_->getInterval(CopyDstReg);
611 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
612 const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
Evan Cheng25f34a32008-09-15 06:28:41 +0000613 if (DLR->valno->def == DefIdx)
614 DLR->valno->copy = UseMI;
Evan Chengc8d044e2008-02-15 18:24:29 +0000615 }
616 }
617}
618
Evan Cheng7e073ba2008-04-09 20:57:25 +0000619/// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
620/// registers due to insert_subreg coalescing. e.g.
621/// r1024 = op
622/// r1025 = implicit_def
623/// r1025 = insert_subreg r1025, r1024
624/// = op r1025
625/// =>
626/// r1025 = op
627/// r1025 = implicit_def
628/// r1025 = insert_subreg r1025, r1025
629/// = op r1025
630void
631SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
632 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
633 E = mri_->reg_end(); I != E; ) {
634 MachineOperand &O = I.getOperand();
635 MachineInstr *DefMI = &*I;
636 ++I;
637 if (!O.isDef())
638 continue;
639 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
640 continue;
641 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
642 continue;
643 li_->RemoveMachineInstrFromMaps(DefMI);
644 DefMI->eraseFromParent();
645 }
646}
647
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000648/// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
649/// due to live range lengthening as the result of coalescing.
650void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
651 LiveInterval &LI) {
652 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
653 UE = mri_->use_end(); UI != UE; ++UI) {
654 MachineOperand &UseMO = UI.getOperand();
655 if (UseMO.isKill()) {
656 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000657 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
658 if (JoinedCopies.count(UseMI))
659 continue;
Evan Chengff7a3e52008-04-16 18:48:43 +0000660 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
Evan Cheng068b4ff2008-08-05 07:10:38 +0000661 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000662 UseMO.setIsKill(false);
663 }
664 }
665}
666
Evan Cheng3c88d742008-03-18 08:26:47 +0000667/// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
668/// from a physical register live interval as well as from the live intervals
669/// of its sub-registers.
670static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
671 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
672 li.removeRange(Start, End, true);
673 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
674 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
675 if (!li_->hasInterval(*SR))
676 continue;
677 LiveInterval &sli = li_->getInterval(*SR);
678 unsigned RemoveEnd = Start;
679 while (RemoveEnd != End) {
680 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
681 if (LR == sli.end())
682 break;
683 RemoveEnd = (LR->end < End) ? LR->end : End;
684 sli.removeRange(Start, RemoveEnd, true);
685 Start = RemoveEnd;
686 }
687 }
688 }
689}
690
691/// removeIntervalIfEmpty - Check if the live interval of a physical register
692/// is empty, if so remove it and also remove the empty intervals of its
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000693/// sub-registers. Return true if live interval is removed.
694static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
Evan Cheng3c88d742008-03-18 08:26:47 +0000695 const TargetRegisterInfo *tri_) {
696 if (li.empty()) {
Evan Cheng3c88d742008-03-18 08:26:47 +0000697 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
698 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
699 if (!li_->hasInterval(*SR))
700 continue;
701 LiveInterval &sli = li_->getInterval(*SR);
702 if (sli.empty())
703 li_->removeInterval(*SR);
704 }
Evan Chengd94950c2008-04-16 01:22:28 +0000705 li_->removeInterval(li.reg);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000706 return true;
Evan Cheng3c88d742008-03-18 08:26:47 +0000707 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000708 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000709}
710
711/// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000712/// Return true if live interval is removed.
713bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
Evan Chengecb2a8b2008-03-05 22:09:42 +0000714 MachineInstr *CopyMI) {
715 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
716 LiveInterval::iterator MLR =
717 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
Evan Cheng3c88d742008-03-18 08:26:47 +0000718 if (MLR == li.end())
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000719 return false; // Already removed by ShortenDeadCopySrcLiveRange.
Evan Chengecb2a8b2008-03-05 22:09:42 +0000720 unsigned RemoveStart = MLR->start;
721 unsigned RemoveEnd = MLR->end;
Evan Cheng3c88d742008-03-18 08:26:47 +0000722 // Remove the liverange that's defined by this.
723 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
724 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000725 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000726 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000727 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000728}
729
Evan Chengb3990d52008-10-27 23:21:01 +0000730/// RemoveDeadDef - If a def of a live interval is now determined dead, remove
731/// the val# it defines. If the live interval becomes empty, remove it as well.
732bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
733 MachineInstr *DefMI) {
734 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
735 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
736 if (DefIdx != MLR->valno->def)
737 return false;
738 li.removeValNo(MLR->valno);
739 return removeIntervalIfEmpty(li, li_, tri_);
740}
741
Evan Cheng0c284322008-03-26 20:15:49 +0000742/// PropagateDeadness - Propagate the dead marker to the instruction which
743/// defines the val#.
744static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
745 unsigned &LRStart, LiveIntervals *li_,
746 const TargetRegisterInfo* tri_) {
747 MachineInstr *DefMI =
748 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
749 if (DefMI && DefMI != CopyMI) {
750 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
751 if (DeadIdx != -1) {
752 DefMI->getOperand(DeadIdx).setIsDead();
753 // A dead def should have a single cycle interval.
754 ++LRStart;
755 }
756 }
757}
758
Evan Cheng883d2602008-04-18 19:22:23 +0000759/// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
760/// fallthoughs to SuccMBB.
761static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
762 MachineBasicBlock *SuccMBB,
763 const TargetInstrInfo *tii_) {
764 if (MBB == SuccMBB)
765 return true;
766 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000767 SmallVector<MachineOperand, 4> Cond;
Evan Cheng883d2602008-04-18 19:22:23 +0000768 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
769 MBB->isSuccessor(SuccMBB);
770}
771
Bill Wendlingf2317782008-04-17 05:20:39 +0000772/// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
773/// extended by a dead copy. Mark the last use (if any) of the val# as kill as
774/// ends the live range there. If there isn't another use, then this live range
775/// is dead. Return true if live interval is removed.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000776bool
Evan Cheng3c88d742008-03-18 08:26:47 +0000777SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
778 MachineInstr *CopyMI) {
779 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
780 if (CopyIdx == 0) {
781 // FIXME: special case: function live in. It can be a general case if the
782 // first instruction index starts at > 0 value.
783 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
784 // Live-in to the function but dead. Remove it from entry live-in set.
Evan Chenga971dbd2008-04-24 09:06:33 +0000785 if (mf_->begin()->isLiveIn(li.reg))
786 mf_->begin()->removeLiveIn(li.reg);
Evan Chengff7a3e52008-04-16 18:48:43 +0000787 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000788 removeRange(li, LR->start, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000789 return removeIntervalIfEmpty(li, li_, tri_);
Evan Cheng3c88d742008-03-18 08:26:47 +0000790 }
791
792 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
793 if (LR == li.end())
794 // Livein but defined by a phi.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000795 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000796
797 unsigned RemoveStart = LR->start;
798 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
799 if (LR->end > RemoveEnd)
800 // More uses past this copy? Nothing to do.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000801 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000802
Evan Cheng883d2602008-04-18 19:22:23 +0000803 MachineBasicBlock *CopyMBB = CopyMI->getParent();
804 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
Evan Cheng3c88d742008-03-18 08:26:47 +0000805 unsigned LastUseIdx;
Evan Chengd2012d02008-04-10 23:48:35 +0000806 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
807 LastUseIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000808 if (LastUse) {
Evan Cheng883d2602008-04-18 19:22:23 +0000809 MachineInstr *LastUseMI = LastUse->getParent();
810 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
811 // r1024 = op
812 // ...
813 // BB1:
814 // = r1024
815 //
816 // BB2:
817 // r1025<dead> = r1024<kill>
818 if (MBBStart < LR->end)
819 removeRange(li, MBBStart, LR->end, li_, tri_);
820 return false;
821 }
822
Evan Cheng3c88d742008-03-18 08:26:47 +0000823 // There are uses before the copy, just shorten the live range to the end
824 // of last use.
825 LastUse->setIsKill();
Evan Cheng3c88d742008-03-18 08:26:47 +0000826 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
827 unsigned SrcReg, DstReg;
828 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
829 DstReg == li.reg) {
830 // Last use is itself an identity code.
831 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
832 LastUseMI->getOperand(DeadIdx).setIsDead();
833 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000834 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000835 }
836
837 // Is it livein?
Evan Cheng3c88d742008-03-18 08:26:47 +0000838 if (LR->start <= MBBStart && LR->end > MBBStart) {
839 if (LR->start == 0) {
840 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
841 // Live-in to the function but dead. Remove it from entry live-in set.
842 mf_->begin()->removeLiveIn(li.reg);
843 }
Evan Cheng3c88d742008-03-18 08:26:47 +0000844 // FIXME: Shorten intervals in BBs that reaches this BB.
Evan Cheng3c88d742008-03-18 08:26:47 +0000845 }
846
Evan Cheng0c284322008-03-26 20:15:49 +0000847 if (LR->valno->def == RemoveStart)
848 // If the def MI defines the val#, propagate the dead marker.
849 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
850
851 removeRange(li, RemoveStart, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000852 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000853}
854
Evan Cheng7e073ba2008-04-09 20:57:25 +0000855/// CanCoalesceWithImpDef - Returns true if the specified copy instruction
856/// from an implicit def to another register can be coalesced away.
857bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
858 LiveInterval &li,
859 LiveInterval &ImpLi) const{
860 if (!CopyMI->killsRegister(ImpLi.reg))
861 return false;
862 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
863 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
864 if (LR == li.end())
865 return false;
866 if (LR->valno->hasPHIKill)
867 return false;
868 if (LR->valno->def != CopyIdx)
869 return false;
870 // Make sure all of val# uses are copies.
871 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
872 UE = mri_->use_end(); UI != UE;) {
873 MachineInstr *UseMI = &*UI;
874 ++UI;
875 if (JoinedCopies.count(UseMI))
876 continue;
877 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
878 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000879 if (ULR == li.end() || ULR->valno != LR->valno)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000880 continue;
881 // If the use is not a use, then it's not safe to coalesce the move.
882 unsigned SrcReg, DstReg;
883 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
884 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
885 UseMI->getOperand(1).getReg() == li.reg)
886 continue;
887 return false;
888 }
889 }
890 return true;
891}
892
893
894/// RemoveCopiesFromValNo - The specified value# is defined by an implicit
895/// def and it is being removed. Turn all copies from this value# into
896/// identity copies so they will be removed.
897void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
898 VNInfo *VNI) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000899 SmallVector<MachineInstr*, 4> ImpDefs;
Evan Chengd2012d02008-04-10 23:48:35 +0000900 MachineOperand *LastUse = NULL;
901 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
902 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
903 RE = mri_->reg_end(); RI != RE;) {
904 MachineOperand *MO = &RI.getOperand();
905 MachineInstr *MI = &*RI;
906 ++RI;
907 if (MO->isDef()) {
908 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000909 ImpDefs.push_back(MI);
Evan Chengd2012d02008-04-10 23:48:35 +0000910 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000911 continue;
Evan Chengd2012d02008-04-10 23:48:35 +0000912 }
913 if (JoinedCopies.count(MI))
914 continue;
915 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
Evan Cheng7e073ba2008-04-09 20:57:25 +0000916 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000917 if (ULR == li.end() || ULR->valno != VNI)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000918 continue;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000919 // If the use is a copy, turn it into an identity copy.
920 unsigned SrcReg, DstReg;
Evan Chengd2012d02008-04-10 23:48:35 +0000921 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
922 // Each use MI may have multiple uses of this register. Change them all.
923 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
924 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000925 if (MO.isReg() && MO.getReg() == li.reg)
Evan Chengd2012d02008-04-10 23:48:35 +0000926 MO.setReg(DstReg);
927 }
928 JoinedCopies.insert(MI);
929 } else if (UseIdx > LastUseIdx) {
930 LastUseIdx = UseIdx;
931 LastUse = MO;
Evan Cheng172b70c2008-04-10 18:38:47 +0000932 }
Evan Chengd2012d02008-04-10 23:48:35 +0000933 }
934 if (LastUse)
935 LastUse->setIsKill();
936 else {
Evan Chengd77d4f92008-05-28 17:40:10 +0000937 // Remove dead implicit_def's.
938 while (!ImpDefs.empty()) {
939 MachineInstr *ImpDef = ImpDefs.back();
940 ImpDefs.pop_back();
941 li_->RemoveMachineInstrFromMaps(ImpDef);
942 ImpDef->eraseFromParent();
943 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000944 }
945}
946
Evan Cheng8db86682008-09-11 20:07:10 +0000947/// getMatchingSuperReg - Return a super-register of the specified register
948/// Reg so its sub-register of index SubIdx is Reg.
Evan Cheng7e073ba2008-04-09 20:57:25 +0000949static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
950 const TargetRegisterClass *RC,
951 const TargetRegisterInfo* TRI) {
952 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
953 unsigned SR = *SRs; ++SRs)
954 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
955 return SR;
956 return 0;
957}
958
Evan Chenge00f5de2008-06-19 01:39:21 +0000959/// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
960/// a subset of the register class of SrcReg, return true if it's profitable
961/// to coalesce the two registers.
962bool
963SimpleRegisterCoalescing::isProfitableToCoalesceToSubRC(unsigned SrcReg,
964 unsigned DstReg,
965 MachineBasicBlock *MBB){
966 if (!CrossClassJoin)
967 return false;
968
969 // First let's make sure all uses are in the same MBB.
970 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
971 RE = mri_->reg_end(); RI != RE; ++RI) {
972 MachineInstr &MI = *RI;
973 if (MI.getParent() != MBB)
974 return false;
975 }
976 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(DstReg),
977 RE = mri_->reg_end(); RI != RE; ++RI) {
978 MachineInstr &MI = *RI;
979 if (MI.getParent() != MBB)
980 return false;
981 }
982
983 // Then make sure the intervals are *short*.
984 LiveInterval &SrcInt = li_->getInterval(SrcReg);
985 LiveInterval &DstInt = li_->getInterval(DstReg);
Owen Andersona1566f22008-07-22 22:46:49 +0000986 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
987 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
Evan Chenge00f5de2008-06-19 01:39:21 +0000988 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
989 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
990 return (SrcSize + DstSize) <= Threshold;
991}
992
Evan Cheng8db86682008-09-11 20:07:10 +0000993/// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
994/// register with a physical register, check if any of the virtual register
995/// operand is a sub-register use or def. If so, make sure it won't result
996/// in an illegal extract_subreg or insert_subreg instruction. e.g.
997/// vr1024 = extract_subreg vr1025, 1
998/// ...
999/// vr1024 = mov8rr AH
1000/// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1001/// AH does not have a super-reg whose sub-register 1 is AH.
1002bool
1003SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1004 unsigned VirtReg,
1005 unsigned PhysReg) {
1006 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1007 E = mri_->reg_end(); I != E; ++I) {
1008 MachineOperand &O = I.getOperand();
1009 MachineInstr *MI = &*I;
1010 if (MI == CopyMI || JoinedCopies.count(MI))
1011 continue;
1012 unsigned SubIdx = O.getSubReg();
1013 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1014 return true;
1015 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1016 SubIdx = MI->getOperand(2).getImm();
1017 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1018 return true;
1019 if (O.isDef()) {
1020 unsigned SrcReg = MI->getOperand(1).getReg();
1021 const TargetRegisterClass *RC =
1022 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1023 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1024 : mri_->getRegClass(SrcReg);
1025 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1026 return true;
1027 }
1028 }
1029 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1030 SubIdx = MI->getOperand(3).getImm();
1031 if (VirtReg == MI->getOperand(0).getReg()) {
1032 if (!tri_->getSubReg(PhysReg, SubIdx))
1033 return true;
1034 } else {
1035 unsigned DstReg = MI->getOperand(0).getReg();
1036 const TargetRegisterClass *RC =
1037 TargetRegisterInfo::isPhysicalRegister(DstReg)
1038 ? tri_->getPhysicalRegisterRegClass(DstReg)
1039 : mri_->getRegClass(DstReg);
1040 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1041 return true;
1042 }
1043 }
1044 }
1045 return false;
1046}
1047
Evan Chenge00f5de2008-06-19 01:39:21 +00001048
David Greene25133302007-06-08 17:18:56 +00001049/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1050/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +00001051/// if the copy was successfully coalesced away. If it is not currently
1052/// possible to coalesce this interval, but it may be possible if other
1053/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng70071432008-02-13 03:01:43 +00001054bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001055 MachineInstr *CopyMI = TheCopy.MI;
1056
1057 Again = false;
Evan Chengcd047082008-08-30 09:09:33 +00001058 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
Evan Cheng8fc9a102007-11-06 08:52:21 +00001059 return false; // Already done.
1060
David Greene25133302007-06-08 17:18:56 +00001061 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1062
Evan Chengc8d044e2008-02-15 18:24:29 +00001063 unsigned SrcReg;
1064 unsigned DstReg;
1065 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001066 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
Evan Chengc8d044e2008-02-15 18:24:29 +00001067 unsigned SubIdx = 0;
1068 if (isExtSubReg) {
1069 DstReg = CopyMI->getOperand(0).getReg();
1070 SrcReg = CopyMI->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001071 } else if (isInsSubReg) {
1072 if (CopyMI->getOperand(2).getSubReg()) {
1073 DOUT << "\tSource of insert_subreg is already coalesced "
1074 << "to another register.\n";
1075 return false; // Not coalescable.
1076 }
1077 DstReg = CopyMI->getOperand(0).getReg();
1078 SrcReg = CopyMI->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +00001079 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
1080 assert(0 && "Unrecognized copy instruction!");
1081 return false;
Evan Cheng70071432008-02-13 03:01:43 +00001082 }
1083
David Greene25133302007-06-08 17:18:56 +00001084 // If they are already joined we continue.
Evan Chengc8d044e2008-02-15 18:24:29 +00001085 if (SrcReg == DstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001086 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001087 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001088 }
1089
Evan Chengc8d044e2008-02-15 18:24:29 +00001090 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1091 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
David Greene25133302007-06-08 17:18:56 +00001092
1093 // If they are both physical registers, we cannot join them.
1094 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001095 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001096 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001097 }
1098
1099 // We only join virtual registers with allocatable physical registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001100 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
David Greene25133302007-06-08 17:18:56 +00001101 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001102 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001103 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001104 if (DstIsPhys && !allocatableRegs_[DstReg]) {
David Greene25133302007-06-08 17:18:56 +00001105 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001106 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001107 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001108
Evan Chenge00f5de2008-06-19 01:39:21 +00001109 // Should be non-null only when coalescing to a sub-register class.
1110 const TargetRegisterClass *SubRC = NULL;
1111 MachineBasicBlock *CopyMBB = CopyMI->getParent();
Evan Cheng32dfbea2007-10-12 08:50:34 +00001112 unsigned RealDstReg = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001113 unsigned RealSrcReg = 0;
1114 if (isExtSubReg || isInsSubReg) {
1115 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1116 if (SrcIsPhys && isExtSubReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001117 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1118 // coalesced with AX.
Evan Cheng621d1572008-04-17 00:06:42 +00001119 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001120 if (DstSubIdx) {
1121 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1122 // coalesced to a larger register so the subreg indices cancel out.
1123 if (DstSubIdx != SubIdx) {
1124 DOUT << "\t Sub-register indices mismatch.\n";
1125 return false; // Not coalescable.
1126 }
1127 } else
Evan Cheng621d1572008-04-17 00:06:42 +00001128 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +00001129 SubIdx = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001130 } else if (DstIsPhys && isInsSubReg) {
1131 // EAX = INSERT_SUBREG EAX, r1024, 0
Evan Cheng621d1572008-04-17 00:06:42 +00001132 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001133 if (SrcSubIdx) {
1134 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1135 // coalesced to a larger register so the subreg indices cancel out.
1136 if (SrcSubIdx != SubIdx) {
1137 DOUT << "\t Sub-register indices mismatch.\n";
1138 return false; // Not coalescable.
1139 }
1140 } else
1141 DstReg = tri_->getSubReg(DstReg, SubIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001142 SubIdx = 0;
1143 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001144 // If this is a extract_subreg where dst is a physical register, e.g.
1145 // cl = EXTRACT_SUBREG reg1024, 1
1146 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001147 // Ditto for
1148 // reg1024 = INSERT_SUBREG r1024, cl, 1
Evan Cheng639f4932008-04-17 07:58:04 +00001149 if (CopyMI->getOperand(1).getSubReg()) {
1150 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
1151 << " of a super-class.\n";
1152 return false; // Not coalescable.
1153 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001154 const TargetRegisterClass *RC =
1155 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
1156 if (isExtSubReg) {
1157 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
Evan Cheng8ec33892008-09-10 00:30:50 +00001158 assert(RealDstReg && "Invalid extract_subreg instruction!");
Evan Cheng7e073ba2008-04-09 20:57:25 +00001159 } else {
1160 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
Evan Cheng8ec33892008-09-10 00:30:50 +00001161 assert(RealSrcReg && "Invalid extract_subreg instruction!");
Evan Cheng32dfbea2007-10-12 08:50:34 +00001162 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001163
1164 // For this type of EXTRACT_SUBREG, conservatively
1165 // check if the live interval of the source register interfere with the
1166 // actual super physical register we are trying to coalesce with.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001167 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
1168 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
1169 if (li_->hasInterval(PhysReg) &&
1170 RHS.overlaps(li_->getInterval(PhysReg))) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001171 DOUT << "Interfere with register ";
Evan Cheng7e073ba2008-04-09 20:57:25 +00001172 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +00001173 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +00001174 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001175 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
Evan Cheng32dfbea2007-10-12 08:50:34 +00001176 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1177 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001178 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +00001179 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +00001180 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001181 SubIdx = 0;
Evan Cheng0547bab2007-11-01 06:22:48 +00001182 } else {
Evan Cheng639f4932008-04-17 07:58:04 +00001183 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1184 : CopyMI->getOperand(2).getSubReg();
1185 if (OldSubIdx) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001186 if (OldSubIdx == SubIdx &&
1187 !differingRegisterClasses(SrcReg, DstReg, SubRC))
Evan Cheng639f4932008-04-17 07:58:04 +00001188 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1189 // coalesced to a larger register so the subreg indices cancel out.
Evan Cheng8509fcf2008-04-29 01:41:44 +00001190 // Also check if the other larger register is of the same register
1191 // class as the would be resulting register.
Evan Cheng639f4932008-04-17 07:58:04 +00001192 SubIdx = 0;
1193 else {
1194 DOUT << "\t Sub-register indices mismatch.\n";
1195 return false; // Not coalescable.
1196 }
1197 }
1198 if (SubIdx) {
1199 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1200 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
Owen Andersona1566f22008-07-22 22:46:49 +00001201 unsigned LargeRegSize =
1202 li_->getApproximateInstructionCount(li_->getInterval(LargeReg));
1203 unsigned SmallRegSize =
1204 li_->getApproximateInstructionCount(li_->getInterval(SmallReg));
Evan Cheng639f4932008-04-17 07:58:04 +00001205 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
1206 unsigned Threshold = allocatableRCRegs_[RC].count();
1207 // Be conservative. If both sides are virtual registers, do not coalesce
1208 // if this will cause a high use density interval to target a smaller
1209 // set of registers.
1210 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
Owen Andersondbb81372008-05-30 22:37:27 +00001211 if ((float)std::distance(mri_->use_begin(SmallReg),
1212 mri_->use_end()) / SmallRegSize <
1213 (float)std::distance(mri_->use_begin(LargeReg),
1214 mri_->use_end()) / LargeRegSize) {
Evan Cheng639f4932008-04-17 07:58:04 +00001215 Again = true; // May be possible to coalesce later.
1216 return false;
1217 }
Evan Cheng0547bab2007-11-01 06:22:48 +00001218 }
1219 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001220 }
Evan Chenge00f5de2008-06-19 01:39:21 +00001221 } else if (differingRegisterClasses(SrcReg, DstReg, SubRC)) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001222 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
1223 // with another? If it's the resulting destination register, then
1224 // the subidx must be propagated to uses (but only those defined
1225 // by the EXTRACT_SUBREG). If it's being coalesced into another
1226 // register, it should be safe because register is assumed to have
1227 // the register class of the super-register.
1228
Evan Chenge00f5de2008-06-19 01:39:21 +00001229 if (!SubRC || !isProfitableToCoalesceToSubRC(SrcReg, DstReg, CopyMBB)) {
1230 // If they are not of the same register class, we cannot join them.
1231 DOUT << "\tSrc/Dest are different register classes.\n";
1232 // Allow the coalescer to try again in case either side gets coalesced to
1233 // a physical register that's compatible with the other side. e.g.
1234 // r1024 = MOV32to32_ r1025
1235 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1236 Again = true; // May be possible to coalesce later.
1237 return false;
1238 }
David Greene25133302007-06-08 17:18:56 +00001239 }
Evan Cheng8db86682008-09-11 20:07:10 +00001240
1241 // Will it create illegal extract_subreg / insert_subreg?
1242 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1243 return false;
1244 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1245 return false;
David Greene25133302007-06-08 17:18:56 +00001246
Evan Chengc8d044e2008-02-15 18:24:29 +00001247 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1248 LiveInterval &DstInt = li_->getInterval(DstReg);
1249 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
David Greene25133302007-06-08 17:18:56 +00001250 "Register mapping is horribly broken!");
1251
Dan Gohman6f0d0242008-02-10 18:45:23 +00001252 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1253 DOUT << " and "; DstInt.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00001254 DOUT << ": ";
1255
Evan Cheng3c88d742008-03-18 08:26:47 +00001256 // Check if it is necessary to propagate "isDead" property.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001257 if (!isExtSubReg && !isInsSubReg) {
1258 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1259 bool isDead = mopd->isDead();
David Greene25133302007-06-08 17:18:56 +00001260
Evan Cheng7e073ba2008-04-09 20:57:25 +00001261 // We need to be careful about coalescing a source physical register with a
1262 // virtual register. Once the coalescing is done, it cannot be broken and
1263 // these are not spillable! If the destination interval uses are far away,
1264 // think twice about coalescing them!
1265 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1266 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1267 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1268 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1269 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1270 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1271 if (TheCopy.isBackEdge)
1272 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +00001273
Evan Cheng7e073ba2008-04-09 20:57:25 +00001274 // If the virtual register live interval is long but it has low use desity,
1275 // do not join them, instead mark the physical register as its allocation
1276 // preference.
Owen Andersona1566f22008-07-22 22:46:49 +00001277 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001278 if (Length > Threshold &&
Owen Andersondbb81372008-05-30 22:37:27 +00001279 (((float)std::distance(mri_->use_begin(JoinVReg),
1280 mri_->use_end()) / Length) < (1.0 / Threshold))) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001281 JoinVInt.preference = JoinPReg;
1282 ++numAborts;
1283 DOUT << "\tMay tie down a physical register, abort!\n";
1284 Again = true; // May be possible to coalesce later.
1285 return false;
1286 }
David Greene25133302007-06-08 17:18:56 +00001287 }
1288 }
1289
1290 // Okay, attempt to join these two intervals. On failure, this returns false.
1291 // Otherwise, if one of the intervals being joined is a physreg, this method
1292 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1293 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001294 bool Swapped = false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00001295 // If SrcInt is implicitly defined, it's safe to coalesce.
1296 bool isEmpty = SrcInt.empty();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001297 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
Evan Chengdb9b1c32008-04-03 16:41:54 +00001298 // Only coalesce an empty interval (defined by implicit_def) with
Evan Cheng7e073ba2008-04-09 20:57:25 +00001299 // another interval which has a valno defined by the CopyMI and the CopyMI
1300 // is a kill of the implicit def.
Evan Chengdb9b1c32008-04-03 16:41:54 +00001301 DOUT << "Not profitable!\n";
1302 return false;
1303 }
1304
1305 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001306 // Coalescing failed.
Evan Chengcd047082008-08-30 09:09:33 +00001307
1308 // If definition of source is defined by trivial computation, try
1309 // rematerializing it.
1310 if (!isExtSubReg && !isInsSubReg &&
1311 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1312 return true;
David Greene25133302007-06-08 17:18:56 +00001313
1314 // If we can eliminate the copy without merging the live ranges, do so now.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001315 if (!isExtSubReg && !isInsSubReg &&
Evan Cheng70071432008-02-13 03:01:43 +00001316 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1317 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001318 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +00001319 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001320 }
Evan Cheng70071432008-02-13 03:01:43 +00001321
David Greene25133302007-06-08 17:18:56 +00001322 // Otherwise, we are unable to join the intervals.
1323 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001324 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +00001325 return false;
1326 }
1327
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001328 LiveInterval *ResSrcInt = &SrcInt;
1329 LiveInterval *ResDstInt = &DstInt;
1330 if (Swapped) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001331 std::swap(SrcReg, DstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001332 std::swap(ResSrcInt, ResDstInt);
1333 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001334 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
David Greene25133302007-06-08 17:18:56 +00001335 "LiveInterval::join didn't work right!");
1336
1337 // If we're about to merge live ranges into a physical register live range,
1338 // we have to update any aliased register's live ranges to indicate that they
1339 // have clobbered values for this range.
Evan Chengc8d044e2008-02-15 18:24:29 +00001340 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001341 // If this is a extract_subreg where dst is a physical register, e.g.
1342 // cl = EXTRACT_SUBREG reg1024, 1
1343 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001344 if (RealDstReg || RealSrcReg) {
1345 LiveInterval &RealInt =
1346 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
Evan Chengf5c73592007-10-15 18:33:50 +00001347 SmallSet<const VNInfo*, 4> CopiedValNos;
1348 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1349 E = ResSrcInt->ranges.end(); I != E; ++I) {
Evan Chengff7a3e52008-04-16 18:48:43 +00001350 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1351 assert(DstLR && "Invalid joined interval!");
Evan Chengf5c73592007-10-15 18:33:50 +00001352 const VNInfo *DstValNo = DstLR->valno;
1353 if (CopiedValNos.insert(DstValNo)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001354 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1355 li_->getVNInfoAllocator());
Evan Chengc3fc7d92007-11-29 09:49:23 +00001356 ValNo->hasPHIKill = DstValNo->hasPHIKill;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001357 RealInt.addKills(ValNo, DstValNo->kills);
1358 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
Evan Chengf5c73592007-10-15 18:33:50 +00001359 }
Evan Cheng34729252007-10-14 10:08:34 +00001360 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001361
1362 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001363 }
1364
David Greene25133302007-06-08 17:18:56 +00001365 // Update the liveintervals of sub-registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001366 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +00001367 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +00001368 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +00001369 }
1370
Evan Chengc8d044e2008-02-15 18:24:29 +00001371 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1372 // larger super-register.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001373 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1374 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001375 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
Evan Chengc8d044e2008-02-15 18:24:29 +00001376 std::swap(SrcReg, DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +00001377 std::swap(ResSrcInt, ResDstInt);
1378 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001379 }
1380
Evan Chenge00f5de2008-06-19 01:39:21 +00001381 // Coalescing to a virtual register that is of a sub-register class of the
1382 // other. Make sure the resulting register is set to the right register class.
1383 if (SubRC) {
1384 mri_->setRegClass(DstReg, SubRC);
1385 ++numSubJoins;
1386 }
1387
Evan Cheng8fc9a102007-11-06 08:52:21 +00001388 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001389 // Add all copies that define val# in the source interval into the queue.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001390 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1391 e = ResSrcInt->vni_end(); i != e; ++i) {
1392 const VNInfo *vni = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001393 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1394 continue;
1395 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1396 unsigned NewSrcReg, NewDstReg;
1397 if (CopyMI &&
1398 JoinedCopies.count(CopyMI) == 0 &&
1399 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001400 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
Evan Chengc8d044e2008-02-15 18:24:29 +00001401 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1402 isBackEdgeCopy(CopyMI, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001403 }
1404 }
1405 }
1406
Evan Chengc8d044e2008-02-15 18:24:29 +00001407 // Remember to delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001408 JoinedCopies.insert(CopyMI);
Evan Chengc8d044e2008-02-15 18:24:29 +00001409
Evan Cheng4ff3f1c2008-03-10 08:11:32 +00001410 // Some live range has been lengthened due to colaescing, eliminate the
1411 // unnecessary kills.
1412 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1413 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1414 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1415
Evan Cheng7e073ba2008-04-09 20:57:25 +00001416 if (isInsSubReg)
1417 // Avoid:
1418 // r1024 = op
1419 // r1024 = implicit_def
1420 // ...
1421 // = r1024
1422 RemoveDeadImpDef(DstReg, *ResDstInt);
Evan Chengc8d044e2008-02-15 18:24:29 +00001423 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1424
Evan Chengcd047082008-08-30 09:09:33 +00001425 // SrcReg is guarateed to be the register whose live interval that is
1426 // being merged.
1427 li_->removeInterval(SrcReg);
1428
Evan Chengdb9b1c32008-04-03 16:41:54 +00001429 if (isEmpty) {
1430 // Now the copy is being coalesced away, the val# previously defined
1431 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1432 // length interval. Remove the val#.
1433 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
Evan Chengff7a3e52008-04-16 18:48:43 +00001434 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001435 VNInfo *ImpVal = LR->valno;
1436 assert(ImpVal->def == CopyIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001437 unsigned NextDef = LR->end;
1438 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001439 ResDstInt->removeValNo(ImpVal);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001440 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1441 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1442 // Special case: vr1024 = implicit_def
1443 // vr1024 = insert_subreg vr1024, vr1025, c
1444 // The insert_subreg becomes a "copy" that defines a val# which can itself
1445 // be coalesced away.
1446 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1447 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1448 LR->valno->copy = DefMI;
1449 }
Evan Chengdb9b1c32008-04-03 16:41:54 +00001450 }
1451
Evan Cheng3ef2d602008-09-09 21:44:23 +00001452 // If resulting interval has a preference that no longer fits because of subreg
1453 // coalescing, just clear the preference.
Evan Cheng40869062008-09-11 18:40:32 +00001454 if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1455 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
Evan Cheng3ef2d602008-09-09 21:44:23 +00001456 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1457 if (!RC->contains(ResDstInt->preference))
1458 ResDstInt->preference = 0;
1459 }
1460
Evan Chengdb9b1c32008-04-03 16:41:54 +00001461 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1462 DOUT << "\n";
1463
David Greene25133302007-06-08 17:18:56 +00001464 ++numJoins;
1465 return true;
1466}
1467
1468/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1469/// compute what the resultant value numbers for each value in the input two
1470/// ranges will be. This is complicated by copies between the two which can
1471/// and will commonly cause multiple value numbers to be merged into one.
1472///
1473/// VN is the value number that we're trying to resolve. InstDefiningValue
1474/// keeps track of the new InstDefiningValue assignment for the result
1475/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1476/// whether a value in this or other is a copy from the opposite set.
1477/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1478/// already been assigned.
1479///
1480/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1481/// contains the value number the copy is from.
1482///
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001483static unsigned ComputeUltimateVN(VNInfo *VNI,
1484 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +00001485 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1486 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +00001487 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001488 SmallVector<int, 16> &OtherValNoAssignments) {
1489 unsigned VN = VNI->id;
1490
David Greene25133302007-06-08 17:18:56 +00001491 // If the VN has already been computed, just return it.
1492 if (ThisValNoAssignments[VN] >= 0)
1493 return ThisValNoAssignments[VN];
1494// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001495
David Greene25133302007-06-08 17:18:56 +00001496 // If this val is not a copy from the other val, then it must be a new value
1497 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +00001498 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +00001499 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001500 NewVNInfo.push_back(VNI);
1501 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001502 }
Evan Chengc14b1442007-08-31 08:04:17 +00001503 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +00001504
1505 // Otherwise, this *is* a copy from the RHS. If the other side has already
1506 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001507 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1508 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +00001509
1510 // Mark this value number as currently being computed, then ask what the
1511 // ultimate value # of the other value is.
1512 ThisValNoAssignments[VN] = -2;
1513 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001514 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1515 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001516 return ThisValNoAssignments[VN] = UltimateVN;
1517}
1518
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001519static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +00001520 return std::find(V.begin(), V.end(), Val) != V.end();
1521}
1522
Evan Cheng7e073ba2008-04-09 20:57:25 +00001523/// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1524/// the specified live interval is defined by a copy from the specified
1525/// register.
1526bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1527 LiveRange *LR,
1528 unsigned Reg) {
1529 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1530 if (SrcReg == Reg)
1531 return true;
1532 if (LR->valno->def == ~0U &&
1533 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1534 *tri_->getSuperRegisters(li.reg)) {
1535 // It's a sub-register live interval, we may not have precise information.
1536 // Re-compute it.
1537 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1538 unsigned SrcReg, DstReg;
Evan Cheng76a4d582008-07-17 19:48:53 +00001539 if (DefMI && tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
Evan Cheng7e073ba2008-04-09 20:57:25 +00001540 DstReg == li.reg && SrcReg == Reg) {
1541 // Cache computed info.
1542 LR->valno->def = LR->start;
1543 LR->valno->copy = DefMI;
1544 return true;
1545 }
1546 }
1547 return false;
1548}
1549
David Greene25133302007-06-08 17:18:56 +00001550/// SimpleJoin - Attempt to joint the specified interval into this one. The
1551/// caller of this method must guarantee that the RHS only contains a single
1552/// value number and that the RHS is not defined by a copy from this
1553/// interval. This returns false if the intervals are not joinable, or it
1554/// joins them and returns true.
Bill Wendling2674d712008-01-04 08:59:18 +00001555bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
David Greene25133302007-06-08 17:18:56 +00001556 assert(RHS.containsOneValue());
1557
1558 // Some number (potentially more than one) value numbers in the current
1559 // interval may be defined as copies from the RHS. Scan the overlapping
1560 // portions of the LHS and RHS, keeping track of this and looking for
1561 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001562 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +00001563
1564 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1565 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1566
1567 if (LHSIt->start < RHSIt->start) {
1568 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1569 if (LHSIt != LHS.begin()) --LHSIt;
1570 } else if (RHSIt->start < LHSIt->start) {
1571 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1572 if (RHSIt != RHS.begin()) --RHSIt;
1573 }
1574
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001575 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +00001576
1577 while (1) {
1578 // Determine if these live intervals overlap.
1579 bool Overlaps = false;
1580 if (LHSIt->start <= RHSIt->start)
1581 Overlaps = LHSIt->end > RHSIt->start;
1582 else
1583 Overlaps = RHSIt->end > LHSIt->start;
1584
1585 // If the live intervals overlap, there are two interesting cases: if the
1586 // LHS interval is defined by a copy from the RHS, it's ok and we record
1587 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +00001588 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +00001589 if (Overlaps) {
1590 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001591 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001592 // Copy from the RHS?
Evan Cheng7e073ba2008-04-09 20:57:25 +00001593 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
David Greene25133302007-06-08 17:18:56 +00001594 return false; // Nope, bail out.
Evan Chengf4ea5102008-05-21 22:34:12 +00001595
1596 if (LHSIt->contains(RHSIt->valno->def))
1597 // Here is an interesting situation:
1598 // BB1:
1599 // vr1025 = copy vr1024
1600 // ..
1601 // BB2:
1602 // vr1024 = op
1603 // = vr1025
1604 // Even though vr1025 is copied from vr1024, it's not safe to
1605 // coalesced them since live range of vr1025 intersects the
1606 // def of vr1024. This happens because vr1025 is assigned the
1607 // value of the previous iteration of vr1024.
1608 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001609 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001610 }
1611
1612 // We know this entire LHS live range is okay, so skip it now.
1613 if (++LHSIt == LHSEnd) break;
1614 continue;
1615 }
1616
1617 if (LHSIt->end < RHSIt->end) {
1618 if (++LHSIt == LHSEnd) break;
1619 } else {
1620 // One interesting case to check here. It's possible that we have
1621 // something like "X3 = Y" which defines a new value number in the LHS,
1622 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001623 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +00001624 // the live ranges don't actually overlap.
1625 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001626 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001627 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +00001628 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +00001629 if (++LHSIt == LHSEnd) break;
1630 } else {
1631 // Otherwise, if this is a copy from the RHS, mark it as being merged
1632 // in.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001633 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
Evan Chengf4ea5102008-05-21 22:34:12 +00001634 if (LHSIt->contains(RHSIt->valno->def))
1635 // Here is an interesting situation:
1636 // BB1:
1637 // vr1025 = copy vr1024
1638 // ..
1639 // BB2:
1640 // vr1024 = op
1641 // = vr1025
1642 // Even though vr1025 is copied from vr1024, it's not safe to
1643 // coalesced them since live range of vr1025 intersects the
1644 // def of vr1024. This happens because vr1025 is assigned the
1645 // value of the previous iteration of vr1024.
1646 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001647 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001648
1649 // We know this entire LHS live range is okay, so skip it now.
1650 if (++LHSIt == LHSEnd) break;
1651 }
1652 }
1653 }
1654
1655 if (++RHSIt == RHSEnd) break;
1656 }
1657 }
1658
Gabor Greife510b3a2007-07-09 12:00:59 +00001659 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +00001660 // the value numbers in EliminatedLHSVals will all be merged together. Since
1661 // the most common case is that EliminatedLHSVals has a single number, we
1662 // optimize for it: if there is more than one value, we merge them all into
1663 // the lowest numbered one, then handle the interval as if we were merging
1664 // with one value number.
Devang Patel8a84e442009-01-05 17:31:22 +00001665 VNInfo *LHSValNo = NULL;
David Greene25133302007-06-08 17:18:56 +00001666 if (EliminatedLHSVals.size() > 1) {
1667 // Loop through all the equal value numbers merging them into the smallest
1668 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001669 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +00001670 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001671 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +00001672 // Merge the current notion of the smallest into the smaller one.
1673 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1674 Smallest = EliminatedLHSVals[i];
1675 } else {
1676 // Merge into the smallest.
1677 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1678 }
1679 }
1680 LHSValNo = Smallest;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001681 } else if (EliminatedLHSVals.empty()) {
1682 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1683 *tri_->getSuperRegisters(LHS.reg))
1684 // Imprecise sub-register information. Can't handle it.
1685 return false;
1686 assert(0 && "No copies from the RHS?");
David Greene25133302007-06-08 17:18:56 +00001687 } else {
David Greene25133302007-06-08 17:18:56 +00001688 LHSValNo = EliminatedLHSVals[0];
1689 }
1690
1691 // Okay, now that there is a single LHS value number that we're merging the
1692 // RHS into, update the value number info for the LHS to indicate that the
1693 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +00001694 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001695 LHSValNo->def = VNI->def;
1696 LHSValNo->copy = VNI->copy;
David Greene25133302007-06-08 17:18:56 +00001697
1698 // Okay, the final step is to loop over the RHS live intervals, adding them to
1699 // the LHS.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001700 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001701 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +00001702 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +00001703 LHS.weight += RHS.weight;
1704 if (RHS.preference && !LHS.preference)
1705 LHS.preference = RHS.preference;
1706
1707 return true;
1708}
1709
1710/// JoinIntervals - Attempt to join these two intervals. On failure, this
1711/// returns false. Otherwise, if one of the intervals being joined is a
1712/// physreg, this method always canonicalizes LHS to be it. The output
1713/// "RHS" will not have been modified, so we can use this information
1714/// below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001715bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1716 LiveInterval &RHS, bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +00001717 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +00001718 // coalesced.
David Greene25133302007-06-08 17:18:56 +00001719 SmallVector<int, 16> LHSValNoAssignments;
1720 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +00001721 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1722 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001723 SmallVector<VNInfo*, 16> NewVNInfo;
David Greene25133302007-06-08 17:18:56 +00001724
1725 // If a live interval is a physical register, conservatively check if any
1726 // of its sub-registers is overlapping the live interval of the virtual
1727 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001728 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1729 *tri_->getSubRegisters(LHS.reg)) {
1730 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001731 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1732 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001733 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001734 return false;
1735 }
Dan Gohman6f0d0242008-02-10 18:45:23 +00001736 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1737 *tri_->getSubRegisters(RHS.reg)) {
1738 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001739 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1740 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001741 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001742 return false;
1743 }
1744 }
1745
1746 // Compute ultimate value numbers for the LHS and RHS values.
1747 if (RHS.containsOneValue()) {
1748 // Copies from a liveinterval with a single value are simple to handle and
1749 // very common, handle the special case here. This is important, because
1750 // often RHS is small and LHS is large (e.g. a physreg).
1751
1752 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +00001753 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +00001754 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001755 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001756 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001757 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1758 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001759 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +00001760 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +00001761 // can't swap the LHS/RHS intervals though.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001762 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001763 return SimpleJoin(LHS, RHS);
1764 } else {
Evan Chengc14b1442007-08-31 08:04:17 +00001765 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001766 }
1767 } else {
1768 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +00001769 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001770 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001771 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +00001772 }
1773
1774 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1775 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001776 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +00001777
1778 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1779 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001780 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1781 i != e; ++i) {
1782 VNInfo *VNI = *i;
1783 unsigned VN = VNI->id;
Evan Chengc8d044e2008-02-15 18:24:29 +00001784 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1785 if (LHSSrcReg != RHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001786 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +00001787 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001788 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001789 LHSValNoAssignments[VN] = VN;
1790 } else if (RHSValID == -1) {
1791 // Otherwise, it is a copy from the RHS, and we don't already have a
1792 // value# for it. Keep the current value number, but remember it.
1793 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001794 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001795 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001796 } else {
1797 // Otherwise, use the specified value #.
1798 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001799 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1800 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001801 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001802 }
David Greene25133302007-06-08 17:18:56 +00001803 }
1804 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001805 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001806 LHSValNoAssignments[VN] = VN;
1807 }
1808 }
1809
1810 assert(RHSValID != -1 && "Didn't find value #?");
1811 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001812 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +00001813 // This path doesn't go through ComputeUltimateVN so just set
1814 // it to anything.
1815 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001816 }
David Greene25133302007-06-08 17:18:56 +00001817 } else {
1818 // Loop over the value numbers of the LHS, seeing if any are defined from
1819 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001820 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1821 i != e; ++i) {
1822 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001823 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001824 continue;
1825
1826 // DstReg is known to be a register in the LHS interval. If the src is
1827 // from the RHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001828 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00001829 continue;
1830
1831 // Figure out the value # from the RHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001832 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001833 }
1834
1835 // Loop over the value numbers of the RHS, seeing if any are defined from
1836 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001837 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1838 i != e; ++i) {
1839 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001840 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001841 continue;
1842
1843 // DstReg is known to be a register in the RHS interval. If the src is
1844 // from the LHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001845 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
David Greene25133302007-06-08 17:18:56 +00001846 continue;
1847
1848 // Figure out the value # from the LHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001849 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001850 }
1851
1852 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1853 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001854 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +00001855
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001856 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1857 i != e; ++i) {
1858 VNInfo *VNI = *i;
1859 unsigned VN = VNI->id;
1860 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001861 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001862 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001863 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001864 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001865 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001866 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1867 i != e; ++i) {
1868 VNInfo *VNI = *i;
1869 unsigned VN = VNI->id;
1870 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001871 continue;
1872 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +00001873 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001874 NewVNInfo.push_back(VNI);
1875 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001876 continue;
1877 }
1878
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001879 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001880 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001881 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001882 }
1883 }
1884
1885 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +00001886 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +00001887 LiveInterval::const_iterator I = LHS.begin();
1888 LiveInterval::const_iterator IE = LHS.end();
1889 LiveInterval::const_iterator J = RHS.begin();
1890 LiveInterval::const_iterator JE = RHS.end();
1891
1892 // Skip ahead until the first place of potential sharing.
1893 if (I->start < J->start) {
1894 I = std::upper_bound(I, IE, J->start);
1895 if (I != LHS.begin()) --I;
1896 } else if (J->start < I->start) {
1897 J = std::upper_bound(J, JE, I->start);
1898 if (J != RHS.begin()) --J;
1899 }
1900
1901 while (1) {
1902 // Determine if these two live ranges overlap.
1903 bool Overlaps;
1904 if (I->start < J->start) {
1905 Overlaps = I->end > J->start;
1906 } else {
1907 Overlaps = J->end > I->start;
1908 }
1909
1910 // If so, check value # info to determine if they are really different.
1911 if (Overlaps) {
1912 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +00001913 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001914 if (LHSValNoAssignments[I->valno->id] !=
1915 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +00001916 return false;
1917 }
1918
1919 if (I->end < J->end) {
1920 ++I;
1921 if (I == IE) break;
1922 } else {
1923 ++J;
1924 if (J == JE) break;
1925 }
1926 }
1927
Evan Cheng34729252007-10-14 10:08:34 +00001928 // Update kill info. Some live ranges are extended due to copy coalescing.
1929 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1930 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1931 VNInfo *VNI = I->first;
1932 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1933 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001934 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001935 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1936 }
1937
1938 // Update kill info. Some live ranges are extended due to copy coalescing.
1939 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1940 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1941 VNInfo *VNI = I->first;
1942 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1943 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001944 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001945 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1946 }
1947
Gabor Greife510b3a2007-07-09 12:00:59 +00001948 // If we get here, we know that we can coalesce the live ranges. Ask the
1949 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001950 if ((RHS.ranges.size() > LHS.ranges.size() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00001951 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1952 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001953 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001954 Swapped = true;
1955 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001956 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001957 Swapped = false;
1958 }
David Greene25133302007-06-08 17:18:56 +00001959 return true;
1960}
1961
1962namespace {
1963 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1964 // depth of the basic block (the unsigned), and then on the MBB number.
1965 struct DepthMBBCompare {
1966 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1967 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1968 if (LHS.first > RHS.first) return true; // Deeper loops first
1969 return LHS.first == RHS.first &&
1970 LHS.second->getNumber() < RHS.second->getNumber();
1971 }
1972 };
1973}
1974
Evan Cheng8fc9a102007-11-06 08:52:21 +00001975/// getRepIntervalSize - Returns the size of the interval that represents the
1976/// specified register.
1977template<class SF>
1978unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1979 return Rc->getRepIntervalSize(Reg);
1980}
1981
1982/// CopyRecSort::operator - Join priority queue sorting function.
1983///
1984bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1985 // Inner loops first.
1986 if (left.LoopDepth > right.LoopDepth)
1987 return false;
Evan Chengc8d044e2008-02-15 18:24:29 +00001988 else if (left.LoopDepth == right.LoopDepth)
Evan Cheng8fc9a102007-11-06 08:52:21 +00001989 if (left.isBackEdge && !right.isBackEdge)
1990 return false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001991 return true;
1992}
1993
Gabor Greife510b3a2007-07-09 12:00:59 +00001994void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00001995 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00001996 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00001997
Evan Cheng8b0b8742007-10-16 08:04:24 +00001998 std::vector<CopyRec> VirtCopies;
1999 std::vector<CopyRec> PhysCopies;
Evan Cheng7e073ba2008-04-09 20:57:25 +00002000 std::vector<CopyRec> ImpDefCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002001 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00002002 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2003 MII != E;) {
2004 MachineInstr *Inst = MII++;
2005
Evan Cheng32dfbea2007-10-12 08:50:34 +00002006 // If this isn't a copy nor a extract_subreg, we can't join intervals.
David Greene25133302007-06-08 17:18:56 +00002007 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00002008 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2009 DstReg = Inst->getOperand(0).getReg();
2010 SrcReg = Inst->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +00002011 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2012 DstReg = Inst->getOperand(0).getReg();
2013 SrcReg = Inst->getOperand(2).getReg();
Evan Cheng32dfbea2007-10-12 08:50:34 +00002014 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
2015 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00002016
Evan Chengc8d044e2008-02-15 18:24:29 +00002017 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2018 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00002019 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002020 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002021 } else {
Evan Cheng7e073ba2008-04-09 20:57:25 +00002022 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2023 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2024 else if (SrcIsPhys || DstIsPhys)
Evan Chengc8d044e2008-02-15 18:24:29 +00002025 PhysCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002026 else
Evan Chengc8d044e2008-02-15 18:24:29 +00002027 VirtCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002028 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002029 }
2030
Evan Cheng8fc9a102007-11-06 08:52:21 +00002031 if (NewHeuristic)
2032 return;
2033
Evan Cheng7e073ba2008-04-09 20:57:25 +00002034 // Try coalescing implicit copies first, followed by copies to / from
2035 // physical registers, then finally copies from virtual registers to
2036 // virtual registers.
2037 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2038 CopyRec &TheCopy = ImpDefCopies[i];
2039 bool Again = false;
2040 if (!JoinCopy(TheCopy, Again))
2041 if (Again)
2042 TryAgain.push_back(TheCopy);
2043 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002044 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2045 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002046 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002047 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002048 if (Again)
2049 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00002050 }
2051 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2052 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002053 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002054 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002055 if (Again)
2056 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00002057 }
2058}
2059
2060void SimpleRegisterCoalescing::joinIntervals() {
2061 DOUT << "********** JOINING INTERVALS ***********\n";
2062
Evan Cheng8fc9a102007-11-06 08:52:21 +00002063 if (NewHeuristic)
2064 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2065
David Greene25133302007-06-08 17:18:56 +00002066 std::vector<CopyRec> TryAgainList;
Dan Gohmana8c763b2008-08-14 18:13:49 +00002067 if (loopInfo->empty()) {
David Greene25133302007-06-08 17:18:56 +00002068 // If there are no loops in the function, join intervals in function order.
2069 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2070 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002071 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002072 } else {
2073 // Otherwise, join intervals in inner loops before other intervals.
2074 // Unfortunately we can't just iterate over loop hierarchy here because
2075 // there may be more MBB's than BB's. Collect MBB's for sorting.
2076
2077 // Join intervals in the function prolog first. We want to join physical
2078 // registers with virtual registers before the intervals got too long.
2079 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002080 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2081 MachineBasicBlock *MBB = I;
2082 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2083 }
David Greene25133302007-06-08 17:18:56 +00002084
2085 // Sort by loop depth.
2086 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2087
2088 // Finally, join intervals in loop nest order.
2089 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002090 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002091 }
2092
2093 // Joining intervals can allow other intervals to be joined. Iteratively join
2094 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00002095 if (NewHeuristic) {
2096 SmallVector<CopyRec, 16> TryAgain;
2097 bool ProgressMade = true;
2098 while (ProgressMade) {
2099 ProgressMade = false;
2100 while (!JoinQueue->empty()) {
2101 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00002102 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002103 bool Success = JoinCopy(R, Again);
2104 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00002105 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002106 else if (Again)
2107 TryAgain.push_back(R);
2108 }
2109
2110 if (ProgressMade) {
2111 while (!TryAgain.empty()) {
2112 JoinQueue->push(TryAgain.back());
2113 TryAgain.pop_back();
2114 }
2115 }
2116 }
2117 } else {
2118 bool ProgressMade = true;
2119 while (ProgressMade) {
2120 ProgressMade = false;
2121
2122 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2123 CopyRec &TheCopy = TryAgainList[i];
2124 if (TheCopy.MI) {
2125 bool Again = false;
2126 bool Success = JoinCopy(TheCopy, Again);
2127 if (Success || !Again) {
2128 TheCopy.MI = 0; // Mark this one as done.
2129 ProgressMade = true;
2130 }
Evan Cheng0547bab2007-11-01 06:22:48 +00002131 }
David Greene25133302007-06-08 17:18:56 +00002132 }
2133 }
2134 }
2135
Evan Cheng8fc9a102007-11-06 08:52:21 +00002136 if (NewHeuristic)
Evan Chengc8d044e2008-02-15 18:24:29 +00002137 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00002138}
2139
2140/// Return true if the two specified registers belong to different register
Evan Chenge00f5de2008-06-19 01:39:21 +00002141/// classes. The registers may be either phys or virt regs. In the
2142/// case where both registers are virtual registers, it would also returns
2143/// true by reference the RegB register class in SubRC if it is a subset of
2144/// RegA's register class.
2145bool
2146SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
2147 const TargetRegisterClass *&SubRC) const {
David Greene25133302007-06-08 17:18:56 +00002148
2149 // Get the register classes for the first reg.
Dan Gohman6f0d0242008-02-10 18:45:23 +00002150 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2151 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
David Greene25133302007-06-08 17:18:56 +00002152 "Shouldn't consider two physregs!");
Evan Chengc8d044e2008-02-15 18:24:29 +00002153 return !mri_->getRegClass(RegB)->contains(RegA);
David Greene25133302007-06-08 17:18:56 +00002154 }
2155
2156 // Compare against the regclass for the second reg.
Evan Chenge00f5de2008-06-19 01:39:21 +00002157 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2158 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2159 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2160 if (RegClassA == RegClassB)
2161 return false;
2162 SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
2163 return true;
2164 }
2165 return !RegClassA->contains(RegB);
David Greene25133302007-06-08 17:18:56 +00002166}
2167
2168/// lastRegisterUse - Returns the last use of the specific register between
Evan Chengc8d044e2008-02-15 18:24:29 +00002169/// cycles Start and End or NULL if there are no uses.
2170MachineOperand *
Chris Lattner84bc5422007-12-31 04:13:23 +00002171SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
Evan Chengc8d044e2008-02-15 18:24:29 +00002172 unsigned Reg, unsigned &UseIdx) const{
2173 UseIdx = 0;
2174 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2175 MachineOperand *LastUse = NULL;
2176 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2177 E = mri_->use_end(); I != E; ++I) {
2178 MachineOperand &Use = I.getOperand();
2179 MachineInstr *UseMI = Use.getParent();
Evan Chenga2fb6342008-03-25 02:02:19 +00002180 unsigned SrcReg, DstReg;
2181 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
2182 // Ignore identity copies.
2183 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +00002184 unsigned Idx = li_->getInstructionIndex(UseMI);
2185 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2186 LastUse = &Use;
2187 UseIdx = Idx;
2188 }
2189 }
2190 return LastUse;
2191 }
2192
David Greene25133302007-06-08 17:18:56 +00002193 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2194 int s = Start;
2195 while (e >= s) {
2196 // Skip deleted instructions
2197 MachineInstr *MI = li_->getInstructionFromIndex(e);
2198 while ((e - InstrSlots::NUM) >= s && !MI) {
2199 e -= InstrSlots::NUM;
2200 MI = li_->getInstructionFromIndex(e);
2201 }
2202 if (e < s || MI == NULL)
2203 return NULL;
2204
Evan Chenga2fb6342008-03-25 02:02:19 +00002205 // Ignore identity copies.
2206 unsigned SrcReg, DstReg;
2207 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
2208 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2209 MachineOperand &Use = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002210 if (Use.isReg() && Use.isUse() && Use.getReg() &&
Evan Chenga2fb6342008-03-25 02:02:19 +00002211 tri_->regsOverlap(Use.getReg(), Reg)) {
2212 UseIdx = e;
2213 return &Use;
2214 }
David Greene25133302007-06-08 17:18:56 +00002215 }
David Greene25133302007-06-08 17:18:56 +00002216
2217 e -= InstrSlots::NUM;
2218 }
2219
2220 return NULL;
2221}
2222
2223
David Greene25133302007-06-08 17:18:56 +00002224void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +00002225 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +00002226 cerr << tri_->getName(reg);
David Greene25133302007-06-08 17:18:56 +00002227 else
2228 cerr << "%reg" << reg;
2229}
2230
2231void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng8fc9a102007-11-06 08:52:21 +00002232 JoinedCopies.clear();
Evan Chengcd047082008-08-30 09:09:33 +00002233 ReMatCopies.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002234 ReMatDefs.clear();
David Greene25133302007-06-08 17:18:56 +00002235}
2236
2237static bool isZeroLengthInterval(LiveInterval *li) {
2238 for (LiveInterval::Ranges::const_iterator
2239 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2240 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2241 return false;
2242 return true;
2243}
2244
Evan Chengdb9b1c32008-04-03 16:41:54 +00002245/// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2246/// turn the copy into an implicit def.
2247bool
2248SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2249 MachineBasicBlock *MBB,
2250 unsigned DstReg, unsigned SrcReg) {
2251 MachineInstr *CopyMI = &*I;
2252 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2253 if (!li_->hasInterval(SrcReg))
2254 return false;
2255 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2256 if (!SrcInt.empty())
2257 return false;
Evan Chengf20d9432008-04-09 01:30:15 +00002258 if (!li_->hasInterval(DstReg))
2259 return false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002260 LiveInterval &DstInt = li_->getInterval(DstReg);
Evan Chengff7a3e52008-04-16 18:48:43 +00002261 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002262 DstInt.removeValNo(DstLR->valno);
2263 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2264 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2265 CopyMI->RemoveOperand(i);
Dan Gohmana8c763b2008-08-14 18:13:49 +00002266 bool NoUse = mri_->use_empty(SrcReg);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002267 if (NoUse) {
2268 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2269 E = mri_->reg_end(); I != E; ) {
2270 assert(I.getOperand().isDef());
2271 MachineInstr *DefMI = &*I;
2272 ++I;
2273 // The implicit_def source has no other uses, delete it.
2274 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2275 li_->RemoveMachineInstrFromMaps(DefMI);
2276 DefMI->eraseFromParent();
Evan Chengdb9b1c32008-04-03 16:41:54 +00002277 }
2278 }
2279 ++I;
2280 return true;
2281}
2282
2283
David Greene25133302007-06-08 17:18:56 +00002284bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2285 mf_ = &fn;
Evan Cheng70071432008-02-13 03:01:43 +00002286 mri_ = &fn.getRegInfo();
David Greene25133302007-06-08 17:18:56 +00002287 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00002288 tri_ = tm_->getRegisterInfo();
David Greene25133302007-06-08 17:18:56 +00002289 tii_ = tm_->getInstrInfo();
2290 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00002291 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00002292
2293 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2294 << "********** Function: "
2295 << ((Value*)mf_->getFunction())->getName() << '\n';
2296
Dan Gohman6f0d0242008-02-10 18:45:23 +00002297 allocatableRegs_ = tri_->getAllocatableSet(fn);
2298 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2299 E = tri_->regclass_end(); I != E; ++I)
Bill Wendling2674d712008-01-04 08:59:18 +00002300 allocatableRCRegs_.insert(std::make_pair(*I,
Dan Gohman6f0d0242008-02-10 18:45:23 +00002301 tri_->getAllocatableSet(fn, *I)));
David Greene25133302007-06-08 17:18:56 +00002302
Gabor Greife510b3a2007-07-09 12:00:59 +00002303 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00002304 if (EnableJoining) {
2305 joinIntervals();
Bill Wendlingbebbded2008-12-19 02:09:57 +00002306 DEBUG({
2307 DOUT << "********** INTERVALS POST JOINING **********\n";
2308 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2309 I->second->print(DOUT, tri_);
2310 DOUT << "\n";
2311 }
2312 });
David Greene25133302007-06-08 17:18:56 +00002313 }
2314
Evan Chengc8d044e2008-02-15 18:24:29 +00002315 // Perform a final pass over the instructions and compute spill weights
2316 // and remove identity moves.
Evan Chengb3990d52008-10-27 23:21:01 +00002317 SmallVector<unsigned, 4> DeadDefs;
David Greene25133302007-06-08 17:18:56 +00002318 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2319 mbbi != mbbe; ++mbbi) {
2320 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002321 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00002322
2323 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2324 mii != mie; ) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002325 MachineInstr *MI = mii;
2326 unsigned SrcReg, DstReg;
2327 if (JoinedCopies.count(MI)) {
2328 // Delete all coalesced copies.
2329 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2330 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2331 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2332 "Unrecognized copy instruction");
2333 DstReg = MI->getOperand(0).getReg();
2334 }
2335 if (MI->registerDefIsDead(DstReg)) {
2336 LiveInterval &li = li_->getInterval(DstReg);
2337 if (!ShortenDeadCopySrcLiveRange(li, MI))
2338 ShortenDeadCopyLiveRange(li, MI);
2339 }
2340 li_->RemoveMachineInstrFromMaps(MI);
2341 mii = mbbi->erase(mii);
2342 ++numPeep;
2343 continue;
2344 }
2345
Evan Cheng20580a12008-09-19 17:38:47 +00002346 // Now check if this is a remat'ed def instruction which is now dead.
2347 if (ReMatDefs.count(MI)) {
2348 bool isDead = true;
2349 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2350 const MachineOperand &MO = MI->getOperand(i);
Evan Chengb3990d52008-10-27 23:21:01 +00002351 if (!MO.isReg())
Evan Cheng20580a12008-09-19 17:38:47 +00002352 continue;
2353 unsigned Reg = MO.getReg();
Evan Chengb3990d52008-10-27 23:21:01 +00002354 if (TargetRegisterInfo::isVirtualRegister(Reg))
2355 DeadDefs.push_back(Reg);
2356 if (MO.isDead())
2357 continue;
Evan Cheng20580a12008-09-19 17:38:47 +00002358 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2359 !mri_->use_empty(Reg)) {
2360 isDead = false;
2361 break;
2362 }
2363 }
2364 if (isDead) {
Evan Chengb3990d52008-10-27 23:21:01 +00002365 while (!DeadDefs.empty()) {
2366 unsigned DeadDef = DeadDefs.back();
2367 DeadDefs.pop_back();
2368 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2369 }
Evan Cheng20580a12008-09-19 17:38:47 +00002370 li_->RemoveMachineInstrFromMaps(mii);
2371 mii = mbbi->erase(mii);
Evan Chengfee2d692008-09-19 22:49:39 +00002372 continue;
Evan Chengb3990d52008-10-27 23:21:01 +00002373 } else
2374 DeadDefs.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002375 }
2376
Evan Chenga971dbd2008-04-24 09:06:33 +00002377 // If the move will be an identity move delete it
Evan Cheng20580a12008-09-19 17:38:47 +00002378 bool isMove = tii_->isMoveInstr(*MI, SrcReg, DstReg);
Evan Chenga971dbd2008-04-24 09:06:33 +00002379 if (isMove && SrcReg == DstReg) {
2380 if (li_->hasInterval(SrcReg)) {
2381 LiveInterval &RegInt = li_->getInterval(SrcReg);
Evan Cheng3c88d742008-03-18 08:26:47 +00002382 // If def of this move instruction is dead, remove its live range
2383 // from the dstination register's live interval.
Evan Cheng20580a12008-09-19 17:38:47 +00002384 if (MI->registerDefIsDead(DstReg)) {
2385 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2386 ShortenDeadCopyLiveRange(RegInt, MI);
Evan Cheng3c88d742008-03-18 08:26:47 +00002387 }
2388 }
Evan Cheng20580a12008-09-19 17:38:47 +00002389 li_->RemoveMachineInstrFromMaps(MI);
David Greene25133302007-06-08 17:18:56 +00002390 mii = mbbi->erase(mii);
2391 ++numPeep;
Evan Chenga971dbd2008-04-24 09:06:33 +00002392 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
David Greene25133302007-06-08 17:18:56 +00002393 SmallSet<unsigned, 4> UniqueUses;
Evan Cheng20580a12008-09-19 17:38:47 +00002394 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2395 const MachineOperand &mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002396 if (mop.isReg() && mop.getReg() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002397 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002398 unsigned reg = mop.getReg();
David Greene25133302007-06-08 17:18:56 +00002399 // Multiple uses of reg by the same instruction. It should not
2400 // contribute to spill weight again.
2401 if (UniqueUses.count(reg) != 0)
2402 continue;
2403 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002404 RegInt.weight +=
Evan Chengc3417602008-06-21 06:45:54 +00002405 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00002406 UniqueUses.insert(reg);
2407 }
2408 }
2409 ++mii;
2410 }
2411 }
2412 }
2413
2414 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +00002415 LiveInterval &LI = *I->second;
Dan Gohman6f0d0242008-02-10 18:45:23 +00002416 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
David Greene25133302007-06-08 17:18:56 +00002417 // If the live interval length is essentially zero, i.e. in every live
2418 // range the use follows def immediately, it doesn't make sense to spill
2419 // it and hope it will be easier to allocate for this li.
2420 if (isZeroLengthInterval(&LI))
2421 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002422 else {
2423 bool isLoad = false;
Evan Chengdc377862008-09-30 15:44:16 +00002424 SmallVector<LiveInterval*, 4> SpillIs;
2425 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00002426 // If all of the definitions of the interval are re-materializable,
2427 // it is a preferred candidate for spilling. If non of the defs are
2428 // loads, then it's potentially very cheap to re-materialize.
2429 // FIXME: this gets much more complicated once we support non-trivial
2430 // re-materialization.
2431 if (isLoad)
2432 LI.weight *= 0.9F;
2433 else
2434 LI.weight *= 0.5F;
2435 }
2436 }
David Greene25133302007-06-08 17:18:56 +00002437
2438 // Slightly prefer live interval that has been assigned a preferred reg.
2439 if (LI.preference)
2440 LI.weight *= 1.01F;
2441
2442 // Divide the weight of the interval by its size. This encourages
2443 // spilling of intervals that are large and have few uses, and
2444 // discourages spilling of small intervals with many uses.
Owen Anderson496bac52008-07-23 19:47:27 +00002445 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
David Greene25133302007-06-08 17:18:56 +00002446 }
2447 }
2448
2449 DEBUG(dump());
2450 return true;
2451}
2452
2453/// print - Implement the dump method.
2454void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2455 li_->print(O, m);
2456}
David Greene2c17c4d2007-09-06 16:18:45 +00002457
2458RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2459 return new SimpleRegisterCoalescing();
2460}
2461
2462// Make sure that anything that uses RegisterCoalescer pulls in this file...
2463DEFINING_FILE_FOR(SimpleRegisterCoalescing)