blob: db7109e7a63aedf4748bd1482c5078f4a615c4ae [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 Cheng8c08d8c2009-01-23 02:15:19 +000039STATISTIC(numCrossRCs , "Number of cross class 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");
Evan Cheng77fde2c2009-02-08 07:48:37 +000045STATISTIC(numDeadValNo, "Number of valno def marked dead");
David Greene25133302007-06-08 17:18:56 +000046
47char SimpleRegisterCoalescing::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000048static cl::opt<bool>
49EnableJoining("join-liveintervals",
50 cl::desc("Coalesce copies (default=true)"),
51 cl::init(true));
David Greene25133302007-06-08 17:18:56 +000052
Dan Gohman844731a2008-05-13 00:00:25 +000053static cl::opt<bool>
54NewHeuristic("new-coalescer-heuristic",
Evan Chenge00f5de2008-06-19 01:39:21 +000055 cl::desc("Use new coalescer heuristic"),
56 cl::init(false), cl::Hidden);
57
58static cl::opt<bool>
Evan Cheng8c08d8c2009-01-23 02:15:19 +000059CrossClassJoin("join-cross-class-copies",
60 cl::desc("Coalesce cross register class copies"),
Evan Chenge00f5de2008-06-19 01:39:21 +000061 cl::init(false), cl::Hidden);
Evan Cheng8fc9a102007-11-06 08:52:21 +000062
Dan Gohman844731a2008-05-13 00:00:25 +000063static RegisterPass<SimpleRegisterCoalescing>
64X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000065
Dan Gohman844731a2008-05-13 00:00:25 +000066// Declare that we implement the RegisterCoalescer interface
67static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000068
Dan Gohman6ddba2b2008-05-13 02:05:11 +000069const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
David Greene25133302007-06-08 17:18:56 +000070
71void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
Evan Chengbbeeb2a2008-09-22 20:58:04 +000072 AU.addRequired<LiveIntervals>();
David Greene25133302007-06-08 17:18:56 +000073 AU.addPreserved<LiveIntervals>();
Evan Chengbbeeb2a2008-09-22 20:58:04 +000074 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000075 AU.addPreserved<MachineLoopInfo>();
76 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000077 if (StrongPHIElim)
78 AU.addPreservedID(StrongPHIEliminationID);
79 else
80 AU.addPreservedID(PHIEliminationID);
David Greene25133302007-06-08 17:18:56 +000081 AU.addPreservedID(TwoAddressInstructionPassID);
David Greene25133302007-06-08 17:18:56 +000082 MachineFunctionPass::getAnalysisUsage(AU);
83}
84
Gabor Greife510b3a2007-07-09 12:00:59 +000085/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000086/// being the source and IntB being the dest, thus this defines a value number
87/// in IntB. If the source value number (in IntA) is defined by a copy from B,
88/// see if we can merge these two pieces of B into a single value number,
89/// eliminating a copy. For example:
90///
91/// A3 = B0
92/// ...
93/// B1 = A3 <- this copy
94///
95/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
96/// value number to be replaced with B0 (which simplifies the B liveinterval).
97///
98/// This returns true if an interval was modified.
99///
Bill Wendling2674d712008-01-04 08:59:18 +0000100bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
101 LiveInterval &IntB,
102 MachineInstr *CopyMI) {
David Greene25133302007-06-08 17:18:56 +0000103 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
104
105 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
106 // the example above.
107 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000108 assert(BLR != IntB.end() && "Live range not found!");
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);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000119 assert(ALR != IntA.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000120 VNInfo *AValNo = ALR->valno;
Evan Cheng5379f412008-12-19 20:58:01 +0000121 // If it's re-defined by an early clobber somewhere in the live range, then
122 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
123 // See PR3149:
124 // 172 %ECX<def> = MOV32rr %reg1039<kill>
125 // 180 INLINEASM <es:subl $5,$1
126 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
127 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
128 // 188 %EAX<def> = MOV32rr %EAX<kill>
129 // 196 %ECX<def> = MOV32rr %ECX<kill>
130 // 204 %ECX<def> = MOV32rr %ECX<kill>
131 // 212 %EAX<def> = MOV32rr %EAX<kill>
132 // 220 %EAX<def> = MOV32rr %EAX
133 // 228 %reg1039<def> = MOV32rr %ECX<kill>
134 // The early clobber operand ties ECX input to the ECX def.
135 //
136 // The live interval of ECX is represented as this:
137 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
138 // The coalescer has no idea there was a def in the middle of [174,230].
139 if (AValNo->redefByEC)
140 return false;
David Greene25133302007-06-08 17:18:56 +0000141
Evan Cheng70071432008-02-13 03:01:43 +0000142 // If AValNo is defined as a copy from IntB, we can potentially process this.
David Greene25133302007-06-08 17:18:56 +0000143 // Get the instruction that defines this value number.
Evan Chengc8d044e2008-02-15 18:24:29 +0000144 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
David Greene25133302007-06-08 17:18:56 +0000145 if (!SrcReg) return false; // Not defined by a copy.
146
147 // If the value number is not defined by a copy instruction, ignore it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000148
David Greene25133302007-06-08 17:18:56 +0000149 // If the source register comes from an interval other than IntB, we can't
150 // handle this.
Evan Chengc8d044e2008-02-15 18:24:29 +0000151 if (SrcReg != IntB.reg) return false;
David Greene25133302007-06-08 17:18:56 +0000152
153 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000154 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000155 assert(ValLR != IntB.end() && "Live range not found!");
David Greene25133302007-06-08 17:18:56 +0000156
157 // Make sure that the end of the live range is inside the same block as
158 // CopyMI.
159 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
160 if (!ValLREndInst ||
161 ValLREndInst->getParent() != CopyMI->getParent()) return false;
162
163 // Okay, we now know that ValLR ends in the same block that the CopyMI
164 // live-range starts. If there are no intervening live ranges between them in
165 // IntB, we can merge them.
166 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000167
168 // If a live interval is a physical register, conservatively check if any
169 // of its sub-registers is overlapping the live interval of the virtual
170 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000171 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
172 *tri_->getSubRegisters(IntB.reg)) {
173 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
Evan Chengdc5294f2007-08-14 23:19:28 +0000174 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
175 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000176 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Chengdc5294f2007-08-14 23:19:28 +0000177 return false;
178 }
179 }
David Greene25133302007-06-08 17:18:56 +0000180
Dan Gohman6f0d0242008-02-10 18:45:23 +0000181 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000182
Evan Chenga8d94f12007-08-07 23:49:57 +0000183 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000184 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000185 // that defines this value #'. Update the the valnum with the new defining
186 // instruction #.
Evan Chengc8d044e2008-02-15 18:24:29 +0000187 BValNo->def = FillerStart;
188 BValNo->copy = NULL;
David Greene25133302007-06-08 17:18:56 +0000189
190 // Okay, we can merge them. We need to insert a new liverange:
191 // [ValLR.end, BLR.begin) of either value number, then we merge the
192 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000193 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
194
195 // If the IntB live range is assigned to a physical register, and if that
196 // physreg has aliases,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000197 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
David Greene25133302007-06-08 17:18:56 +0000198 // Update the liveintervals of sub-registers.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000199 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
David Greene25133302007-06-08 17:18:56 +0000200 LiveInterval &AliasLI = li_->getInterval(*AS);
201 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000202 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000203 }
204 }
205
206 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng25f34a32008-09-15 06:28:41 +0000207 if (BValNo != ValLR->valno) {
208 IntB.addKills(ValLR->valno, BValNo->kills);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000209 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
Evan Cheng25f34a32008-09-15 06:28:41 +0000210 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000211 DOUT << " result = "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000212 DOUT << "\n";
213
214 // If the source instruction was killing the source register before the
215 // merge, unset the isKill marker given the live range has been extended.
216 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
Evan Cheng25f34a32008-09-15 06:28:41 +0000217 if (UIdx != -1) {
Chris Lattnerf7382302007-12-30 21:56:09 +0000218 ValLREndInst->getOperand(UIdx).setIsKill(false);
Evan Cheng25f34a32008-09-15 06:28:41 +0000219 IntB.removeKill(ValLR->valno, FillerStart);
220 }
Evan Cheng70071432008-02-13 03:01:43 +0000221
222 ++numExtends;
223 return true;
224}
225
Evan Cheng559f4222008-02-16 02:32:17 +0000226/// HasOtherReachingDefs - Return true if there are definitions of IntB
227/// other than BValNo val# that can reach uses of AValno val# of IntA.
228bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
229 LiveInterval &IntB,
230 VNInfo *AValNo,
231 VNInfo *BValNo) {
232 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
233 AI != AE; ++AI) {
234 if (AI->valno != AValNo) continue;
235 LiveInterval::Ranges::iterator BI =
236 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
237 if (BI != IntB.ranges.begin())
238 --BI;
239 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
240 if (BI->valno == BValNo)
241 continue;
242 if (BI->start <= AI->start && BI->end > AI->start)
243 return true;
244 if (BI->start > AI->start && BI->start < AI->end)
245 return true;
246 }
247 }
248 return false;
249}
250
Evan Cheng70071432008-02-13 03:01:43 +0000251/// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
252/// being the source and IntB being the dest, thus this defines a value number
253/// in IntB. If the source value number (in IntA) is defined by a commutable
254/// instruction and its other operand is coalesced to the copy dest register,
255/// see if we can transform the copy into a noop by commuting the definition. For
256/// example,
257///
258/// A3 = op A2 B0<kill>
259/// ...
260/// B1 = A3 <- this copy
261/// ...
262/// = op A3 <- more uses
263///
264/// ==>
265///
266/// B2 = op B0 A2<kill>
267/// ...
268/// B1 = B2 <- now an identify copy
269/// ...
270/// = op B2 <- more uses
271///
272/// This returns true if an interval was modified.
273///
274bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
275 LiveInterval &IntB,
276 MachineInstr *CopyMI) {
Evan Cheng70071432008-02-13 03:01:43 +0000277 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
278
Evan Chenga9407f52008-02-18 18:56:31 +0000279 // FIXME: For now, only eliminate the copy by commuting its def when the
280 // source register is a virtual register. We want to guard against cases
281 // where the copy is a back edge copy and commuting the def lengthen the
282 // live interval of the source register to the entire loop.
283 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
Evan Cheng96cfff02008-02-18 08:40:53 +0000284 return false;
285
Evan Chengc8d044e2008-02-15 18:24:29 +0000286 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
Evan Cheng70071432008-02-13 03:01:43 +0000287 // the example above.
288 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000289 assert(BLR != IntB.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000290 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000291
Evan Cheng70071432008-02-13 03:01:43 +0000292 // Get the location that B is defined at. Two options: either this value has
293 // an unknown definition point or it is defined at CopyIdx. If unknown, we
294 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000295 if (!BValNo->copy) return false;
Evan Cheng70071432008-02-13 03:01:43 +0000296 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
297
298 // AValNo is the value number in A that defines the copy, A3 in the example.
299 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000300 assert(ALR != IntA.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000301 VNInfo *AValNo = ALR->valno;
Evan Chenge35a6d12008-02-13 08:41:08 +0000302 // If other defs can reach uses of this def, then it's not safe to perform
303 // the optimization.
304 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
Evan Cheng70071432008-02-13 03:01:43 +0000305 return false;
306 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
307 const TargetInstrDesc &TID = DefMI->getDesc();
Evan Chengc8d044e2008-02-15 18:24:29 +0000308 unsigned NewDstIdx;
309 if (!TID.isCommutable() ||
310 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
Evan Cheng70071432008-02-13 03:01:43 +0000311 return false;
312
Evan Chengc8d044e2008-02-15 18:24:29 +0000313 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
314 unsigned NewReg = NewDstMO.getReg();
315 if (NewReg != IntB.reg || !NewDstMO.isKill())
Evan Cheng70071432008-02-13 03:01:43 +0000316 return false;
317
318 // Make sure there are no other definitions of IntB that would reach the
319 // uses which the new definition can reach.
Evan Cheng559f4222008-02-16 02:32:17 +0000320 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
321 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000322
Evan Chenged70cbb32008-03-26 19:03:01 +0000323 // If some of the uses of IntA.reg is already coalesced away, return false.
324 // It's not possible to determine whether it's safe to perform the coalescing.
325 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
326 UE = mri_->use_end(); UI != UE; ++UI) {
327 MachineInstr *UseMI = &*UI;
328 unsigned UseIdx = li_->getInstructionIndex(UseMI);
329 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000330 if (ULR == IntA.end())
331 continue;
Evan Chenged70cbb32008-03-26 19:03:01 +0000332 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
333 return false;
334 }
335
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000336 // At this point we have decided that it is legal to do this
337 // transformation. Start by commuting the instruction.
Evan Cheng70071432008-02-13 03:01:43 +0000338 MachineBasicBlock *MBB = DefMI->getParent();
339 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
Evan Cheng559f4222008-02-16 02:32:17 +0000340 if (!NewMI)
341 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000342 if (NewMI != DefMI) {
343 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
344 MBB->insert(DefMI, NewMI);
345 MBB->erase(DefMI);
346 }
Evan Cheng6130f662008-03-05 00:59:57 +0000347 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
Evan Cheng70071432008-02-13 03:01:43 +0000348 NewMI->getOperand(OpIdx).setIsKill();
349
Evan Cheng70071432008-02-13 03:01:43 +0000350 bool BHasPHIKill = BValNo->hasPHIKill;
351 SmallVector<VNInfo*, 4> BDeadValNos;
352 SmallVector<unsigned, 4> BKills;
353 std::map<unsigned, unsigned> BExtend;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000354
355 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
356 // A = or A, B
357 // ...
358 // B = A
359 // ...
360 // C = A<kill>
361 // ...
362 // = B
363 //
364 // then do not add kills of A to the newly created B interval.
365 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
366 if (Extended)
367 BExtend[ALR->end] = BLR->end;
368
369 // Update uses of IntA of the specific Val# with IntB.
Evan Cheng70071432008-02-13 03:01:43 +0000370 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
371 UE = mri_->use_end(); UI != UE;) {
372 MachineOperand &UseMO = UI.getOperand();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000373 MachineInstr *UseMI = &*UI;
Evan Cheng70071432008-02-13 03:01:43 +0000374 ++UI;
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000375 if (JoinedCopies.count(UseMI))
Evan Chenged70cbb32008-03-26 19:03:01 +0000376 continue;
Evan Cheng70071432008-02-13 03:01:43 +0000377 unsigned UseIdx = li_->getInstructionIndex(UseMI);
378 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000379 if (ULR == IntA.end() || ULR->valno != AValNo)
Evan Cheng70071432008-02-13 03:01:43 +0000380 continue;
381 UseMO.setReg(NewReg);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000382 if (UseMI == CopyMI)
383 continue;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000384 if (UseMO.isKill()) {
385 if (Extended)
386 UseMO.setIsKill(false);
387 else
388 BKills.push_back(li_->getUseIndex(UseIdx)+1);
389 }
Evan Cheng04ee5a12009-01-20 19:12:24 +0000390 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
391 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000392 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +0000393 if (DstReg == IntB.reg) {
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000394 // This copy will become a noop. If it's defining a new val#,
395 // remove that val# as well. However this live range is being
396 // extended to the end of the existing live range defined by the copy.
397 unsigned DefIdx = li_->getDefIndex(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000398 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000399 BHasPHIKill |= DLR->valno->hasPHIKill;
400 assert(DLR->valno->def == DefIdx);
401 BDeadValNos.push_back(DLR->valno);
402 BExtend[DLR->start] = DLR->end;
403 JoinedCopies.insert(UseMI);
404 // If this is a kill but it's going to be removed, the last use
405 // of the same val# is the new kill.
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000406 if (UseMO.isKill())
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000407 BKills.pop_back();
Evan Cheng70071432008-02-13 03:01:43 +0000408 }
409 }
410
411 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
412 // simply extend BLR if CopyMI doesn't end the range.
413 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
414
Evan Cheng739583b2008-06-17 20:11:16 +0000415 // Remove val#'s defined by copies that will be coalesced away.
Evan Cheng70071432008-02-13 03:01:43 +0000416 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
417 IntB.removeValNo(BDeadValNos[i]);
Evan Cheng739583b2008-06-17 20:11:16 +0000418
419 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
420 // is updated. Kills are also updated.
421 VNInfo *ValNo = BValNo;
422 ValNo->def = AValNo->def;
423 ValNo->copy = NULL;
424 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
425 unsigned Kill = ValNo->kills[j];
426 if (Kill != BLR->end)
427 BKills.push_back(Kill);
428 }
429 ValNo->kills.clear();
Evan Cheng70071432008-02-13 03:01:43 +0000430 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
431 AI != AE; ++AI) {
432 if (AI->valno != AValNo) continue;
433 unsigned End = AI->end;
434 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
435 if (EI != BExtend.end())
436 End = EI->second;
437 IntB.addRange(LiveRange(AI->start, End, ValNo));
438 }
439 IntB.addKills(ValNo, BKills);
440 ValNo->hasPHIKill = BHasPHIKill;
441
442 DOUT << " result = "; IntB.print(DOUT, tri_);
443 DOUT << "\n";
444
445 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
446 IntA.removeValNo(AValNo);
447 DOUT << " result = "; IntA.print(DOUT, tri_);
448 DOUT << "\n";
449
450 ++numCommutes;
David Greene25133302007-06-08 17:18:56 +0000451 return true;
452}
453
Evan Cheng961154f2009-02-05 08:45:04 +0000454/// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
455/// fallthoughs to SuccMBB.
456static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
457 MachineBasicBlock *SuccMBB,
458 const TargetInstrInfo *tii_) {
459 if (MBB == SuccMBB)
460 return true;
461 MachineBasicBlock *TBB = 0, *FBB = 0;
462 SmallVector<MachineOperand, 4> Cond;
463 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
464 MBB->isSuccessor(SuccMBB);
465}
466
467/// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
468/// from a physical register live interval as well as from the live intervals
469/// of its sub-registers.
470static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
471 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
472 li.removeRange(Start, End, true);
473 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
474 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
475 if (!li_->hasInterval(*SR))
476 continue;
477 LiveInterval &sli = li_->getInterval(*SR);
478 unsigned RemoveEnd = Start;
479 while (RemoveEnd != End) {
480 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
481 if (LR == sli.end())
482 break;
483 RemoveEnd = (LR->end < End) ? LR->end : End;
484 sli.removeRange(Start, RemoveEnd, true);
485 Start = RemoveEnd;
486 }
487 }
488 }
489}
490
491/// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
Evan Cheng86fb9fd2009-02-08 08:24:28 +0000492/// as the copy instruction, trim the live interval to the last use and return
Evan Cheng961154f2009-02-05 08:45:04 +0000493/// true.
494bool
495SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(unsigned CopyIdx,
496 MachineBasicBlock *CopyMBB,
497 LiveInterval &li,
498 const LiveRange *LR) {
499 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
500 unsigned LastUseIdx;
501 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
502 LastUseIdx);
503 if (LastUse) {
504 MachineInstr *LastUseMI = LastUse->getParent();
505 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
506 // r1024 = op
507 // ...
508 // BB1:
509 // = r1024
510 //
511 // BB2:
512 // r1025<dead> = r1024<kill>
513 if (MBBStart < LR->end)
514 removeRange(li, MBBStart, LR->end, li_, tri_);
515 return true;
516 }
517
518 // There are uses before the copy, just shorten the live range to the end
519 // of last use.
520 LastUse->setIsKill();
521 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
522 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
523 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
524 DstReg == li.reg) {
525 // Last use is itself an identity code.
526 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
527 LastUseMI->getOperand(DeadIdx).setIsDead();
528 }
529 return true;
530 }
531
532 // Is it livein?
533 if (LR->start <= MBBStart && LR->end > MBBStart) {
534 if (LR->start == 0) {
535 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
536 // Live-in to the function but dead. Remove it from entry live-in set.
537 mf_->begin()->removeLiveIn(li.reg);
538 }
539 // FIXME: Shorten intervals in BBs that reaches this BB.
540 }
541
542 return false;
543}
544
Evan Chengcd047082008-08-30 09:09:33 +0000545/// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
546/// computation, replace the copy by rematerialize the definition.
547bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
548 unsigned DstReg,
549 MachineInstr *CopyMI) {
550 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
551 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000552 assert(SrcLR != SrcInt.end() && "Live range not found!");
Evan Chengcd047082008-08-30 09:09:33 +0000553 VNInfo *ValNo = SrcLR->valno;
554 // If other defs can reach uses of this def, then it's not safe to perform
555 // the optimization.
556 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
557 return false;
558 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
559 const TargetInstrDesc &TID = DefMI->getDesc();
560 if (!TID.isAsCheapAsAMove())
561 return false;
Evan Cheng54801f782009-02-05 22:24:17 +0000562 if (!DefMI->getDesc().isRematerializable() ||
563 !tii_->isTriviallyReMaterializable(DefMI))
564 return false;
Evan Chengcd047082008-08-30 09:09:33 +0000565 bool SawStore = false;
566 if (!DefMI->isSafeToMove(tii_, SawStore))
567 return false;
568
569 unsigned DefIdx = li_->getDefIndex(CopyIdx);
570 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
571 DLR->valno->copy = NULL;
Evan Cheng195cd3a2008-10-13 18:35:52 +0000572 // Don't forget to update sub-register intervals.
573 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
574 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
575 if (!li_->hasInterval(*SR))
576 continue;
577 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
578 if (DLR && DLR->valno->copy == CopyMI)
579 DLR->valno->copy = NULL;
580 }
581 }
Evan Chengcd047082008-08-30 09:09:33 +0000582
Evan Cheng961154f2009-02-05 08:45:04 +0000583 // If copy kills the source register, find the last use and propagate
584 // kill.
Evan Chengcd047082008-08-30 09:09:33 +0000585 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng961154f2009-02-05 08:45:04 +0000586 if (CopyMI->killsRegister(SrcInt.reg))
587 TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR);
588
Dan Gohman3afda6e2008-10-21 03:24:31 +0000589 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
590 CopyMI->removeFromParent();
Evan Chengcd047082008-08-30 09:09:33 +0000591 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
592 MachineInstr *NewMI = prior(MII);
Chris Lattner99cbdff2008-10-11 23:59:03 +0000593 // CopyMI may have implicit operands, transfer them over to the newly
Evan Chengcd047082008-08-30 09:09:33 +0000594 // rematerialized instruction. And update implicit def interval valnos.
595 for (unsigned i = CopyMI->getDesc().getNumOperands(),
596 e = CopyMI->getNumOperands(); i != e; ++i) {
597 MachineOperand &MO = CopyMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000598 if (MO.isReg() && MO.isImplicit())
Evan Chengcd047082008-08-30 09:09:33 +0000599 NewMI->addOperand(MO);
Owen Anderson369e9872008-09-10 20:41:13 +0000600 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
Evan Chengcd047082008-08-30 09:09:33 +0000601 unsigned Reg = MO.getReg();
602 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
603 if (DLR && DLR->valno->copy == CopyMI)
604 DLR->valno->copy = NULL;
605 }
606 }
607
608 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
Dan Gohman3afda6e2008-10-21 03:24:31 +0000609 MBB->getParent()->DeleteMachineInstr(CopyMI);
Evan Chengcd047082008-08-30 09:09:33 +0000610 ReMatCopies.insert(CopyMI);
Evan Cheng20580a12008-09-19 17:38:47 +0000611 ReMatDefs.insert(DefMI);
Evan Chengcd047082008-08-30 09:09:33 +0000612 ++NumReMats;
613 return true;
614}
615
Evan Cheng8fc9a102007-11-06 08:52:21 +0000616/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
617///
618bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
Evan Cheng7e073ba2008-04-09 20:57:25 +0000619 unsigned DstReg) const {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000620 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000621 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000622 if (!L)
623 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000624 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000625 return false;
626
Evan Cheng8fc9a102007-11-06 08:52:21 +0000627 LiveInterval &LI = li_->getInterval(DstReg);
628 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
629 LiveInterval::const_iterator DstLR =
630 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
631 if (DstLR == LI.end())
632 return false;
Owen Andersonb3db9c92008-06-23 22:12:23 +0000633 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
Evan Cheng70071432008-02-13 03:01:43 +0000634 if (DstLR->valno->kills.size() == 1 &&
635 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
Evan Cheng8fc9a102007-11-06 08:52:21 +0000636 return true;
637 return false;
638}
639
Evan Chengc8d044e2008-02-15 18:24:29 +0000640/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
641/// update the subregister number if it is not zero. If DstReg is a
642/// physical register and the existing subregister number of the def / use
643/// being updated is not zero, make sure to set it to the correct physical
644/// subregister.
645void
646SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
647 unsigned SubIdx) {
648 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
649 if (DstIsPhys && SubIdx) {
650 // Figure out the real physical register we are updating with.
651 DstReg = tri_->getSubReg(DstReg, SubIdx);
652 SubIdx = 0;
653 }
654
655 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
656 E = mri_->reg_end(); I != E; ) {
657 MachineOperand &O = I.getOperand();
Evan Cheng70366b92008-03-21 19:09:30 +0000658 MachineInstr *UseMI = &*I;
Evan Chengc8d044e2008-02-15 18:24:29 +0000659 ++I;
Evan Cheng621d1572008-04-17 00:06:42 +0000660 unsigned OldSubIdx = O.getSubReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000661 if (DstIsPhys) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000662 unsigned UseDstReg = DstReg;
Evan Cheng621d1572008-04-17 00:06:42 +0000663 if (OldSubIdx)
664 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
Evan Chengcd047082008-08-30 09:09:33 +0000665
Evan Cheng04ee5a12009-01-20 19:12:24 +0000666 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
667 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
668 CopySrcSubIdx, CopyDstSubIdx) &&
Evan Chengcd047082008-08-30 09:09:33 +0000669 CopySrcReg != CopyDstReg &&
670 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
671 // If the use is a copy and it won't be coalesced away, and its source
672 // is defined by a trivial computation, try to rematerialize it instead.
673 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
674 continue;
675 }
676
Evan Chengc8d044e2008-02-15 18:24:29 +0000677 O.setReg(UseDstReg);
678 O.setSubReg(0);
Evan Chengee9e1b02008-09-12 18:13:14 +0000679 continue;
680 }
681
682 // Sub-register indexes goes from small to large. e.g.
683 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
684 // EAX: 1 -> AL, 2 -> AX
685 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
686 // sub-register 2 is also AX.
687 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
688 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
689 else if (SubIdx)
690 O.setSubReg(SubIdx);
691 // Remove would-be duplicated kill marker.
692 if (O.isKill() && UseMI->killsRegister(DstReg))
693 O.setIsKill(false);
694 O.setReg(DstReg);
695
696 // After updating the operand, check if the machine instruction has
697 // become a copy. If so, update its val# information.
698 const TargetInstrDesc &TID = UseMI->getDesc();
Evan Cheng04ee5a12009-01-20 19:12:24 +0000699 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
Evan Chengee9e1b02008-09-12 18:13:14 +0000700 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +0000701 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
702 CopySrcSubIdx, CopyDstSubIdx) &&
Evan Cheng870e4be2008-09-17 18:36:25 +0000703 CopySrcReg != CopyDstReg &&
704 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
705 allocatableRegs_[CopyDstReg])) {
Evan Chengee9e1b02008-09-12 18:13:14 +0000706 LiveInterval &LI = li_->getInterval(CopyDstReg);
707 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
708 const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
Evan Cheng25f34a32008-09-15 06:28:41 +0000709 if (DLR->valno->def == DefIdx)
710 DLR->valno->copy = UseMI;
Evan Chengc8d044e2008-02-15 18:24:29 +0000711 }
712 }
713}
714
Evan Cheng7e073ba2008-04-09 20:57:25 +0000715/// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
716/// registers due to insert_subreg coalescing. e.g.
717/// r1024 = op
718/// r1025 = implicit_def
719/// r1025 = insert_subreg r1025, r1024
720/// = op r1025
721/// =>
722/// r1025 = op
723/// r1025 = implicit_def
724/// r1025 = insert_subreg r1025, r1025
725/// = op r1025
726void
727SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
728 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
729 E = mri_->reg_end(); I != E; ) {
730 MachineOperand &O = I.getOperand();
731 MachineInstr *DefMI = &*I;
732 ++I;
733 if (!O.isDef())
734 continue;
735 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
736 continue;
737 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
738 continue;
739 li_->RemoveMachineInstrFromMaps(DefMI);
740 DefMI->eraseFromParent();
741 }
742}
743
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000744/// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
745/// due to live range lengthening as the result of coalescing.
746void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
747 LiveInterval &LI) {
748 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
749 UE = mri_->use_end(); UI != UE; ++UI) {
750 MachineOperand &UseMO = UI.getOperand();
751 if (UseMO.isKill()) {
752 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000753 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
754 if (JoinedCopies.count(UseMI))
755 continue;
Evan Chengff7a3e52008-04-16 18:48:43 +0000756 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
Evan Cheng068b4ff2008-08-05 07:10:38 +0000757 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000758 UseMO.setIsKill(false);
759 }
760 }
761}
762
Evan Cheng3c88d742008-03-18 08:26:47 +0000763/// removeIntervalIfEmpty - Check if the live interval of a physical register
764/// is empty, if so remove it and also remove the empty intervals of its
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000765/// sub-registers. Return true if live interval is removed.
766static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
Evan Cheng3c88d742008-03-18 08:26:47 +0000767 const TargetRegisterInfo *tri_) {
768 if (li.empty()) {
Evan Cheng3c88d742008-03-18 08:26:47 +0000769 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
770 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
771 if (!li_->hasInterval(*SR))
772 continue;
773 LiveInterval &sli = li_->getInterval(*SR);
774 if (sli.empty())
775 li_->removeInterval(*SR);
776 }
Evan Chengd94950c2008-04-16 01:22:28 +0000777 li_->removeInterval(li.reg);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000778 return true;
Evan Cheng3c88d742008-03-18 08:26:47 +0000779 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000780 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000781}
782
783/// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000784/// Return true if live interval is removed.
785bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
Evan Chengecb2a8b2008-03-05 22:09:42 +0000786 MachineInstr *CopyMI) {
787 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
788 LiveInterval::iterator MLR =
789 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
Evan Cheng3c88d742008-03-18 08:26:47 +0000790 if (MLR == li.end())
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000791 return false; // Already removed by ShortenDeadCopySrcLiveRange.
Evan Chengecb2a8b2008-03-05 22:09:42 +0000792 unsigned RemoveStart = MLR->start;
793 unsigned RemoveEnd = MLR->end;
Evan Cheng3c88d742008-03-18 08:26:47 +0000794 // Remove the liverange that's defined by this.
795 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
796 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000797 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000798 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000799 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000800}
801
Evan Chengb3990d52008-10-27 23:21:01 +0000802/// RemoveDeadDef - If a def of a live interval is now determined dead, remove
803/// the val# it defines. If the live interval becomes empty, remove it as well.
804bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
805 MachineInstr *DefMI) {
806 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
807 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
808 if (DefIdx != MLR->valno->def)
809 return false;
810 li.removeValNo(MLR->valno);
811 return removeIntervalIfEmpty(li, li_, tri_);
812}
813
Evan Cheng0c284322008-03-26 20:15:49 +0000814/// PropagateDeadness - Propagate the dead marker to the instruction which
815/// defines the val#.
816static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
817 unsigned &LRStart, LiveIntervals *li_,
818 const TargetRegisterInfo* tri_) {
819 MachineInstr *DefMI =
820 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
821 if (DefMI && DefMI != CopyMI) {
822 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
823 if (DeadIdx != -1) {
824 DefMI->getOperand(DeadIdx).setIsDead();
825 // A dead def should have a single cycle interval.
826 ++LRStart;
827 }
828 }
829}
830
Bill Wendlingf2317782008-04-17 05:20:39 +0000831/// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
832/// extended by a dead copy. Mark the last use (if any) of the val# as kill as
833/// ends the live range there. If there isn't another use, then this live range
834/// is dead. Return true if live interval is removed.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000835bool
Evan Cheng3c88d742008-03-18 08:26:47 +0000836SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
837 MachineInstr *CopyMI) {
838 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
839 if (CopyIdx == 0) {
840 // FIXME: special case: function live in. It can be a general case if the
841 // first instruction index starts at > 0 value.
842 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
843 // Live-in to the function but dead. Remove it from entry live-in set.
Evan Chenga971dbd2008-04-24 09:06:33 +0000844 if (mf_->begin()->isLiveIn(li.reg))
845 mf_->begin()->removeLiveIn(li.reg);
Evan Chengff7a3e52008-04-16 18:48:43 +0000846 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000847 removeRange(li, LR->start, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000848 return removeIntervalIfEmpty(li, li_, tri_);
Evan Cheng3c88d742008-03-18 08:26:47 +0000849 }
850
851 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
852 if (LR == li.end())
853 // Livein but defined by a phi.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000854 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000855
856 unsigned RemoveStart = LR->start;
857 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
858 if (LR->end > RemoveEnd)
859 // More uses past this copy? Nothing to do.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000860 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000861
Evan Cheng961154f2009-02-05 08:45:04 +0000862 // If there is a last use in the same bb, we can't remove the live range.
863 // Shorten the live interval and return.
864 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMI->getParent(), li, LR))
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000865 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000866
Evan Cheng77fde2c2009-02-08 07:48:37 +0000867 if (LR->valno->def == RemoveStart) {
868 // If the def MI defines the val# and this copy is the only kill of the
869 // val#, then propagate the dead marker.
Evan Cheng86fb9fd2009-02-08 08:24:28 +0000870 if (!li.isOnlyLROfValNo(LR)) {
871 if (li.isKill(LR->valno, RemoveEnd))
872 li.removeKill(LR->valno, RemoveEnd);
873 } else {
Evan Cheng77fde2c2009-02-08 07:48:37 +0000874 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
875 ++numDeadValNo;
Evan Chengf18134a2009-02-08 08:00:36 +0000876 }
Evan Cheng77fde2c2009-02-08 07:48:37 +0000877 }
Evan Cheng0c284322008-03-26 20:15:49 +0000878
879 removeRange(li, RemoveStart, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000880 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000881}
882
Evan Cheng7e073ba2008-04-09 20:57:25 +0000883/// CanCoalesceWithImpDef - Returns true if the specified copy instruction
884/// from an implicit def to another register can be coalesced away.
885bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
886 LiveInterval &li,
887 LiveInterval &ImpLi) const{
888 if (!CopyMI->killsRegister(ImpLi.reg))
889 return false;
890 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
891 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
892 if (LR == li.end())
893 return false;
894 if (LR->valno->hasPHIKill)
895 return false;
896 if (LR->valno->def != CopyIdx)
897 return false;
898 // Make sure all of val# uses are copies.
899 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
900 UE = mri_->use_end(); UI != UE;) {
901 MachineInstr *UseMI = &*UI;
902 ++UI;
903 if (JoinedCopies.count(UseMI))
904 continue;
905 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
906 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000907 if (ULR == li.end() || ULR->valno != LR->valno)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000908 continue;
909 // If the use is not a use, then it's not safe to coalesce the move.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000910 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
911 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +0000912 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
913 UseMI->getOperand(1).getReg() == li.reg)
914 continue;
915 return false;
916 }
917 }
918 return true;
919}
920
921
922/// RemoveCopiesFromValNo - The specified value# is defined by an implicit
923/// def and it is being removed. Turn all copies from this value# into
924/// identity copies so they will be removed.
925void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
926 VNInfo *VNI) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000927 SmallVector<MachineInstr*, 4> ImpDefs;
Evan Chengd2012d02008-04-10 23:48:35 +0000928 MachineOperand *LastUse = NULL;
929 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
930 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
931 RE = mri_->reg_end(); RI != RE;) {
932 MachineOperand *MO = &RI.getOperand();
933 MachineInstr *MI = &*RI;
934 ++RI;
935 if (MO->isDef()) {
936 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000937 ImpDefs.push_back(MI);
Evan Chengd2012d02008-04-10 23:48:35 +0000938 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000939 continue;
Evan Chengd2012d02008-04-10 23:48:35 +0000940 }
941 if (JoinedCopies.count(MI))
942 continue;
943 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
Evan Cheng7e073ba2008-04-09 20:57:25 +0000944 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000945 if (ULR == li.end() || ULR->valno != VNI)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000946 continue;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000947 // If the use is a copy, turn it into an identity copy.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000948 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
949 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
950 SrcReg == li.reg) {
Evan Chengd2012d02008-04-10 23:48:35 +0000951 // Each use MI may have multiple uses of this register. Change them all.
952 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
953 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000954 if (MO.isReg() && MO.getReg() == li.reg)
Evan Chengd2012d02008-04-10 23:48:35 +0000955 MO.setReg(DstReg);
956 }
957 JoinedCopies.insert(MI);
958 } else if (UseIdx > LastUseIdx) {
959 LastUseIdx = UseIdx;
960 LastUse = MO;
Evan Cheng172b70c2008-04-10 18:38:47 +0000961 }
Evan Chengd2012d02008-04-10 23:48:35 +0000962 }
963 if (LastUse)
964 LastUse->setIsKill();
965 else {
Evan Chengd77d4f92008-05-28 17:40:10 +0000966 // Remove dead implicit_def's.
967 while (!ImpDefs.empty()) {
968 MachineInstr *ImpDef = ImpDefs.back();
969 ImpDefs.pop_back();
970 li_->RemoveMachineInstrFromMaps(ImpDef);
971 ImpDef->eraseFromParent();
972 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000973 }
974}
975
Evan Cheng8db86682008-09-11 20:07:10 +0000976/// getMatchingSuperReg - Return a super-register of the specified register
977/// Reg so its sub-register of index SubIdx is Reg.
Evan Cheng7e073ba2008-04-09 20:57:25 +0000978static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
979 const TargetRegisterClass *RC,
980 const TargetRegisterInfo* TRI) {
981 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
982 unsigned SR = *SRs; ++SRs)
983 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
984 return SR;
985 return 0;
986}
987
Evan Cheng8c08d8c2009-01-23 02:15:19 +0000988/// isWinToJoinCrossClass - Return true if it's profitable to coalesce
989/// two virtual registers from different register classes.
Evan Chenge00f5de2008-06-19 01:39:21 +0000990bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +0000991SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
992 unsigned SmallReg,
993 unsigned Threshold) {
Evan Chenge00f5de2008-06-19 01:39:21 +0000994 // Then make sure the intervals are *short*.
Evan Cheng8c08d8c2009-01-23 02:15:19 +0000995 LiveInterval &LargeInt = li_->getInterval(LargeReg);
996 LiveInterval &SmallInt = li_->getInterval(SmallReg);
997 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
998 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
999 if (SmallSize > Threshold || LargeSize > Threshold)
1000 if ((float)std::distance(mri_->use_begin(SmallReg),
1001 mri_->use_end()) / SmallSize <
1002 (float)std::distance(mri_->use_begin(LargeReg),
1003 mri_->use_end()) / LargeSize)
1004 return false;
1005 return true;
Evan Chenge00f5de2008-06-19 01:39:21 +00001006}
1007
Evan Cheng8db86682008-09-11 20:07:10 +00001008/// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1009/// register with a physical register, check if any of the virtual register
1010/// operand is a sub-register use or def. If so, make sure it won't result
1011/// in an illegal extract_subreg or insert_subreg instruction. e.g.
1012/// vr1024 = extract_subreg vr1025, 1
1013/// ...
1014/// vr1024 = mov8rr AH
1015/// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1016/// AH does not have a super-reg whose sub-register 1 is AH.
1017bool
1018SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1019 unsigned VirtReg,
1020 unsigned PhysReg) {
1021 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1022 E = mri_->reg_end(); I != E; ++I) {
1023 MachineOperand &O = I.getOperand();
1024 MachineInstr *MI = &*I;
1025 if (MI == CopyMI || JoinedCopies.count(MI))
1026 continue;
1027 unsigned SubIdx = O.getSubReg();
1028 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1029 return true;
1030 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1031 SubIdx = MI->getOperand(2).getImm();
1032 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1033 return true;
1034 if (O.isDef()) {
1035 unsigned SrcReg = MI->getOperand(1).getReg();
1036 const TargetRegisterClass *RC =
1037 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1038 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1039 : mri_->getRegClass(SrcReg);
1040 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1041 return true;
1042 }
1043 }
1044 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1045 SubIdx = MI->getOperand(3).getImm();
1046 if (VirtReg == MI->getOperand(0).getReg()) {
1047 if (!tri_->getSubReg(PhysReg, SubIdx))
1048 return true;
1049 } else {
1050 unsigned DstReg = MI->getOperand(0).getReg();
1051 const TargetRegisterClass *RC =
1052 TargetRegisterInfo::isPhysicalRegister(DstReg)
1053 ? tri_->getPhysicalRegisterRegClass(DstReg)
1054 : mri_->getRegClass(DstReg);
1055 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1056 return true;
1057 }
1058 }
1059 }
1060 return false;
1061}
1062
Evan Chenge00f5de2008-06-19 01:39:21 +00001063
Evan Chenge08eb9c2009-01-20 06:44:16 +00001064/// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1065/// an extract_subreg where dst is a physical register, e.g.
1066/// cl = EXTRACT_SUBREG reg1024, 1
1067bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001068SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1069 unsigned SrcReg, unsigned SubIdx,
1070 unsigned &RealDstReg) {
Evan Chenge08eb9c2009-01-20 06:44:16 +00001071 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1072 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1073 assert(RealDstReg && "Invalid extract_subreg instruction!");
1074
1075 // For this type of EXTRACT_SUBREG, conservatively
1076 // check if the live interval of the source register interfere with the
1077 // actual super physical register we are trying to coalesce with.
1078 LiveInterval &RHS = li_->getInterval(SrcReg);
1079 if (li_->hasInterval(RealDstReg) &&
1080 RHS.overlaps(li_->getInterval(RealDstReg))) {
1081 DOUT << "Interfere with register ";
1082 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
1083 return false; // Not coalescable
1084 }
1085 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1086 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1087 DOUT << "Interfere with sub-register ";
1088 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1089 return false; // Not coalescable
1090 }
1091 return true;
1092}
1093
1094/// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1095/// an insert_subreg where src is a physical register, e.g.
1096/// reg1024 = INSERT_SUBREG reg1024, c1, 0
1097bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001098SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1099 unsigned SrcReg, unsigned SubIdx,
1100 unsigned &RealSrcReg) {
Evan Chenge08eb9c2009-01-20 06:44:16 +00001101 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1102 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1103 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1104
1105 LiveInterval &RHS = li_->getInterval(DstReg);
1106 if (li_->hasInterval(RealSrcReg) &&
1107 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1108 DOUT << "Interfere with register ";
1109 DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_));
1110 return false; // Not coalescable
1111 }
1112 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1113 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1114 DOUT << "Interfere with sub-register ";
1115 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1116 return false; // Not coalescable
1117 }
1118 return true;
1119}
1120
David Greene25133302007-06-08 17:18:56 +00001121/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1122/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +00001123/// if the copy was successfully coalesced away. If it is not currently
1124/// possible to coalesce this interval, but it may be possible if other
1125/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng70071432008-02-13 03:01:43 +00001126bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001127 MachineInstr *CopyMI = TheCopy.MI;
1128
1129 Again = false;
Evan Chengcd047082008-08-30 09:09:33 +00001130 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
Evan Cheng8fc9a102007-11-06 08:52:21 +00001131 return false; // Already done.
1132
David Greene25133302007-06-08 17:18:56 +00001133 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1134
Evan Cheng04ee5a12009-01-20 19:12:24 +00001135 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Chengc8d044e2008-02-15 18:24:29 +00001136 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001137 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
Evan Chengc8d044e2008-02-15 18:24:29 +00001138 unsigned SubIdx = 0;
1139 if (isExtSubReg) {
1140 DstReg = CopyMI->getOperand(0).getReg();
1141 SrcReg = CopyMI->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001142 } else if (isInsSubReg) {
1143 if (CopyMI->getOperand(2).getSubReg()) {
1144 DOUT << "\tSource of insert_subreg is already coalesced "
1145 << "to another register.\n";
1146 return false; // Not coalescable.
1147 }
1148 DstReg = CopyMI->getOperand(0).getReg();
1149 SrcReg = CopyMI->getOperand(2).getReg();
Evan Cheng04ee5a12009-01-20 19:12:24 +00001150 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
Evan Chengc8d044e2008-02-15 18:24:29 +00001151 assert(0 && "Unrecognized copy instruction!");
1152 return false;
Evan Cheng70071432008-02-13 03:01:43 +00001153 }
1154
David Greene25133302007-06-08 17:18:56 +00001155 // If they are already joined we continue.
Evan Chengc8d044e2008-02-15 18:24:29 +00001156 if (SrcReg == DstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001157 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001158 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001159 }
1160
Evan Chengc8d044e2008-02-15 18:24:29 +00001161 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1162 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
David Greene25133302007-06-08 17:18:56 +00001163
1164 // If they are both physical registers, we cannot join them.
1165 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001166 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001167 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001168 }
1169
1170 // We only join virtual registers with allocatable physical registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001171 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
David Greene25133302007-06-08 17:18:56 +00001172 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001173 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001174 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001175 if (DstIsPhys && !allocatableRegs_[DstReg]) {
David Greene25133302007-06-08 17:18:56 +00001176 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001177 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001178 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001179
Evan Chenge00f5de2008-06-19 01:39:21 +00001180 // Should be non-null only when coalescing to a sub-register class.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001181 bool CrossRC = false;
1182 const TargetRegisterClass *NewRC = NULL;
Evan Chenge00f5de2008-06-19 01:39:21 +00001183 MachineBasicBlock *CopyMBB = CopyMI->getParent();
Evan Cheng32dfbea2007-10-12 08:50:34 +00001184 unsigned RealDstReg = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001185 unsigned RealSrcReg = 0;
1186 if (isExtSubReg || isInsSubReg) {
1187 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1188 if (SrcIsPhys && isExtSubReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001189 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1190 // coalesced with AX.
Evan Cheng621d1572008-04-17 00:06:42 +00001191 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001192 if (DstSubIdx) {
1193 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1194 // coalesced to a larger register so the subreg indices cancel out.
1195 if (DstSubIdx != SubIdx) {
1196 DOUT << "\t Sub-register indices mismatch.\n";
1197 return false; // Not coalescable.
1198 }
1199 } else
Evan Cheng621d1572008-04-17 00:06:42 +00001200 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +00001201 SubIdx = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001202 } else if (DstIsPhys && isInsSubReg) {
1203 // EAX = INSERT_SUBREG EAX, r1024, 0
Evan Cheng621d1572008-04-17 00:06:42 +00001204 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001205 if (SrcSubIdx) {
1206 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1207 // coalesced to a larger register so the subreg indices cancel out.
1208 if (SrcSubIdx != SubIdx) {
1209 DOUT << "\t Sub-register indices mismatch.\n";
1210 return false; // Not coalescable.
1211 }
1212 } else
1213 DstReg = tri_->getSubReg(DstReg, SubIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001214 SubIdx = 0;
1215 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001216 if (CopyMI->getOperand(1).getSubReg()) {
1217 DOUT << "\tSrc of extract_subreg already coalesced with reg"
1218 << " of a super-class.\n";
1219 return false; // Not coalescable.
1220 }
1221
Evan Cheng7e073ba2008-04-09 20:57:25 +00001222 if (isExtSubReg) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001223 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
Evan Cheng0547bab2007-11-01 06:22:48 +00001224 return false; // Not coalescable
Evan Chenge08eb9c2009-01-20 06:44:16 +00001225 } else {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001226 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
Evan Chenge08eb9c2009-01-20 06:44:16 +00001227 return false; // Not coalescable
1228 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001229 SubIdx = 0;
Evan Cheng0547bab2007-11-01 06:22:48 +00001230 } else {
Evan Cheng639f4932008-04-17 07:58:04 +00001231 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1232 : CopyMI->getOperand(2).getSubReg();
1233 if (OldSubIdx) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001234 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
Evan Cheng639f4932008-04-17 07:58:04 +00001235 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1236 // coalesced to a larger register so the subreg indices cancel out.
Evan Cheng8509fcf2008-04-29 01:41:44 +00001237 // Also check if the other larger register is of the same register
1238 // class as the would be resulting register.
Evan Cheng639f4932008-04-17 07:58:04 +00001239 SubIdx = 0;
1240 else {
1241 DOUT << "\t Sub-register indices mismatch.\n";
1242 return false; // Not coalescable.
1243 }
1244 }
1245 if (SubIdx) {
1246 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1247 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001248 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1249 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1250 Again = true; // May be possible to coalesce later.
1251 return false;
Evan Cheng0547bab2007-11-01 06:22:48 +00001252 }
1253 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001254 }
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001255 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1256 if (!CrossClassJoin)
1257 return false;
1258 CrossRC = true;
1259
1260 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
Evan Chengc8d044e2008-02-15 18:24:29 +00001261 // with another? If it's the resulting destination register, then
1262 // the subidx must be propagated to uses (but only those defined
1263 // by the EXTRACT_SUBREG). If it's being coalesced into another
1264 // register, it should be safe because register is assumed to have
1265 // the register class of the super-register.
1266
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001267 // Process moves where one of the registers have a sub-register index.
1268 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1269 if (DstMO->getSubReg())
1270 // FIXME: Can we handle this?
1271 return false;
1272 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1273 SubIdx = SrcMO->getSubReg();
1274 if (SubIdx) {
1275 // This is not a extract_subreg but it looks like one.
1276 // e.g. %cl = MOV16rr %reg1024:2
1277 isExtSubReg = true;
1278 if (DstIsPhys) {
1279 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1280 return false; // Not coalescable
1281 SubIdx = 0;
1282 }
1283 }
1284
1285 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1286 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1287 unsigned LargeReg = SrcReg;
1288 unsigned SmallReg = DstReg;
1289 unsigned Limit = 0;
1290
1291 // Now determine the register class of the joined register.
1292 if (isExtSubReg) {
1293 if (SubIdx && DstRC && DstRC->isASubClass()) {
1294 // This is a move to a sub-register class. However, the source is a
1295 // sub-register of a larger register class. We don't know what should
1296 // the register class be. FIXME.
1297 Again = true;
1298 return false;
1299 }
1300 Limit = allocatableRCRegs_[DstRC].count();
1301 } else if (!SrcIsPhys && !SrcIsPhys) {
1302 unsigned SrcSize = SrcRC->getSize();
1303 unsigned DstSize = DstRC->getSize();
1304 if (SrcSize < DstSize)
1305 // For example X86::MOVSD2PDrr copies from FR64 to VR128.
1306 NewRC = DstRC;
1307 else if (DstSize > SrcSize) {
1308 NewRC = SrcRC;
1309 std::swap(LargeReg, SmallReg);
1310 } else {
1311 unsigned SrcNumRegs = SrcRC->getNumRegs();
1312 unsigned DstNumRegs = DstRC->getNumRegs();
1313 if (DstNumRegs < SrcNumRegs)
1314 // Sub-register class?
1315 NewRC = DstRC;
1316 else if (SrcNumRegs < DstNumRegs) {
1317 NewRC = SrcRC;
1318 std::swap(LargeReg, SmallReg);
1319 } else
1320 // No idea what's the right register class to use.
1321 return false;
1322 }
1323 }
1324
Evan Chengc16d37e2009-01-23 05:48:59 +00001325 // If we are joining two virtual registers and the resulting register
1326 // class is more restrictive (fewer register, smaller size). Check if it's
1327 // worth doing the merge.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001328 if (!SrcIsPhys && !DstIsPhys &&
Evan Chengc16d37e2009-01-23 05:48:59 +00001329 (isExtSubReg || DstRC->isASubClass()) &&
1330 !isWinToJoinCrossClass(LargeReg, SmallReg,
1331 allocatableRCRegs_[NewRC].count())) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001332 DOUT << "\tSrc/Dest are different register classes.\n";
1333 // Allow the coalescer to try again in case either side gets coalesced to
1334 // a physical register that's compatible with the other side. e.g.
1335 // r1024 = MOV32to32_ r1025
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001336 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
Evan Chenge00f5de2008-06-19 01:39:21 +00001337 Again = true; // May be possible to coalesce later.
1338 return false;
1339 }
David Greene25133302007-06-08 17:18:56 +00001340 }
Evan Cheng8db86682008-09-11 20:07:10 +00001341
1342 // Will it create illegal extract_subreg / insert_subreg?
1343 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1344 return false;
1345 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1346 return false;
David Greene25133302007-06-08 17:18:56 +00001347
Evan Chengc8d044e2008-02-15 18:24:29 +00001348 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1349 LiveInterval &DstInt = li_->getInterval(DstReg);
1350 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
David Greene25133302007-06-08 17:18:56 +00001351 "Register mapping is horribly broken!");
1352
Dan Gohman6f0d0242008-02-10 18:45:23 +00001353 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1354 DOUT << " and "; DstInt.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00001355 DOUT << ": ";
1356
Evan Cheng3c88d742008-03-18 08:26:47 +00001357 // Check if it is necessary to propagate "isDead" property.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001358 if (!isExtSubReg && !isInsSubReg) {
1359 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1360 bool isDead = mopd->isDead();
David Greene25133302007-06-08 17:18:56 +00001361
Evan Cheng7e073ba2008-04-09 20:57:25 +00001362 // We need to be careful about coalescing a source physical register with a
1363 // virtual register. Once the coalescing is done, it cannot be broken and
1364 // these are not spillable! If the destination interval uses are far away,
1365 // think twice about coalescing them!
1366 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1367 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1368 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1369 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1370 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1371 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1372 if (TheCopy.isBackEdge)
1373 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +00001374
Evan Cheng7e073ba2008-04-09 20:57:25 +00001375 // If the virtual register live interval is long but it has low use desity,
1376 // do not join them, instead mark the physical register as its allocation
1377 // preference.
Owen Andersona1566f22008-07-22 22:46:49 +00001378 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001379 if (Length > Threshold &&
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001380 (((float)std::distance(mri_->use_begin(JoinVReg), mri_->use_end())
1381 / Length) < (1.0 / Threshold))) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001382 JoinVInt.preference = JoinPReg;
1383 ++numAborts;
1384 DOUT << "\tMay tie down a physical register, abort!\n";
1385 Again = true; // May be possible to coalesce later.
1386 return false;
1387 }
David Greene25133302007-06-08 17:18:56 +00001388 }
1389 }
1390
1391 // Okay, attempt to join these two intervals. On failure, this returns false.
1392 // Otherwise, if one of the intervals being joined is a physreg, this method
1393 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1394 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001395 bool Swapped = false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00001396 // If SrcInt is implicitly defined, it's safe to coalesce.
1397 bool isEmpty = SrcInt.empty();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001398 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
Evan Chengdb9b1c32008-04-03 16:41:54 +00001399 // Only coalesce an empty interval (defined by implicit_def) with
Evan Cheng7e073ba2008-04-09 20:57:25 +00001400 // another interval which has a valno defined by the CopyMI and the CopyMI
1401 // is a kill of the implicit def.
Evan Chengdb9b1c32008-04-03 16:41:54 +00001402 DOUT << "Not profitable!\n";
1403 return false;
1404 }
1405
1406 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001407 // Coalescing failed.
Evan Chengcd047082008-08-30 09:09:33 +00001408
1409 // If definition of source is defined by trivial computation, try
1410 // rematerializing it.
1411 if (!isExtSubReg && !isInsSubReg &&
1412 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1413 return true;
David Greene25133302007-06-08 17:18:56 +00001414
1415 // If we can eliminate the copy without merging the live ranges, do so now.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001416 if (!isExtSubReg && !isInsSubReg &&
Evan Cheng70071432008-02-13 03:01:43 +00001417 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1418 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001419 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +00001420 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001421 }
Evan Cheng70071432008-02-13 03:01:43 +00001422
David Greene25133302007-06-08 17:18:56 +00001423 // Otherwise, we are unable to join the intervals.
1424 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001425 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +00001426 return false;
1427 }
1428
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001429 LiveInterval *ResSrcInt = &SrcInt;
1430 LiveInterval *ResDstInt = &DstInt;
1431 if (Swapped) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001432 std::swap(SrcReg, DstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001433 std::swap(ResSrcInt, ResDstInt);
1434 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001435 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
David Greene25133302007-06-08 17:18:56 +00001436 "LiveInterval::join didn't work right!");
1437
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001438 // If we're about to merge live ranges into a physical register live interval,
David Greene25133302007-06-08 17:18:56 +00001439 // we have to update any aliased register's live ranges to indicate that they
1440 // have clobbered values for this range.
Evan Chengc8d044e2008-02-15 18:24:29 +00001441 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001442 // If this is a extract_subreg where dst is a physical register, e.g.
1443 // cl = EXTRACT_SUBREG reg1024, 1
1444 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001445 if (RealDstReg || RealSrcReg) {
1446 LiveInterval &RealInt =
1447 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
Evan Chengf5c73592007-10-15 18:33:50 +00001448 SmallSet<const VNInfo*, 4> CopiedValNos;
1449 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1450 E = ResSrcInt->ranges.end(); I != E; ++I) {
Evan Chengff7a3e52008-04-16 18:48:43 +00001451 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1452 assert(DstLR && "Invalid joined interval!");
Evan Chengf5c73592007-10-15 18:33:50 +00001453 const VNInfo *DstValNo = DstLR->valno;
1454 if (CopiedValNos.insert(DstValNo)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001455 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1456 li_->getVNInfoAllocator());
Evan Chengc3fc7d92007-11-29 09:49:23 +00001457 ValNo->hasPHIKill = DstValNo->hasPHIKill;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001458 RealInt.addKills(ValNo, DstValNo->kills);
1459 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
Evan Chengf5c73592007-10-15 18:33:50 +00001460 }
Evan Cheng34729252007-10-14 10:08:34 +00001461 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001462
1463 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001464 }
1465
David Greene25133302007-06-08 17:18:56 +00001466 // Update the liveintervals of sub-registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001467 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +00001468 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +00001469 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +00001470 }
1471
Evan Chengc8d044e2008-02-15 18:24:29 +00001472 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1473 // larger super-register.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001474 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1475 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001476 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
Evan Chengc8d044e2008-02-15 18:24:29 +00001477 std::swap(SrcReg, DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +00001478 std::swap(ResSrcInt, ResDstInt);
1479 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001480 }
1481
Evan Chenge00f5de2008-06-19 01:39:21 +00001482 // Coalescing to a virtual register that is of a sub-register class of the
1483 // other. Make sure the resulting register is set to the right register class.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001484 if (CrossRC) {
1485 ++numCrossRCs;
1486 if (NewRC)
1487 mri_->setRegClass(DstReg, NewRC);
Evan Chenge00f5de2008-06-19 01:39:21 +00001488 }
1489
Evan Cheng8fc9a102007-11-06 08:52:21 +00001490 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001491 // Add all copies that define val# in the source interval into the queue.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001492 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1493 e = ResSrcInt->vni_end(); i != e; ++i) {
1494 const VNInfo *vni = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001495 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1496 continue;
1497 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +00001498 unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
Evan Chengc8d044e2008-02-15 18:24:29 +00001499 if (CopyMI &&
1500 JoinedCopies.count(CopyMI) == 0 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +00001501 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1502 NewSrcSubIdx, NewDstSubIdx)) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001503 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
Evan Chengc8d044e2008-02-15 18:24:29 +00001504 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1505 isBackEdgeCopy(CopyMI, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001506 }
1507 }
1508 }
1509
Evan Chengc8d044e2008-02-15 18:24:29 +00001510 // Remember to delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001511 JoinedCopies.insert(CopyMI);
Evan Chengc8d044e2008-02-15 18:24:29 +00001512
Evan Cheng4ff3f1c2008-03-10 08:11:32 +00001513 // Some live range has been lengthened due to colaescing, eliminate the
1514 // unnecessary kills.
1515 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1516 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1517 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1518
Evan Cheng7e073ba2008-04-09 20:57:25 +00001519 if (isInsSubReg)
1520 // Avoid:
1521 // r1024 = op
1522 // r1024 = implicit_def
1523 // ...
1524 // = r1024
1525 RemoveDeadImpDef(DstReg, *ResDstInt);
Evan Chengc8d044e2008-02-15 18:24:29 +00001526 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1527
Evan Chengcd047082008-08-30 09:09:33 +00001528 // SrcReg is guarateed to be the register whose live interval that is
1529 // being merged.
1530 li_->removeInterval(SrcReg);
1531
Evan Chengdb9b1c32008-04-03 16:41:54 +00001532 if (isEmpty) {
1533 // Now the copy is being coalesced away, the val# previously defined
1534 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1535 // length interval. Remove the val#.
1536 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
Evan Chengff7a3e52008-04-16 18:48:43 +00001537 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001538 VNInfo *ImpVal = LR->valno;
1539 assert(ImpVal->def == CopyIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001540 unsigned NextDef = LR->end;
1541 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001542 ResDstInt->removeValNo(ImpVal);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001543 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1544 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1545 // Special case: vr1024 = implicit_def
1546 // vr1024 = insert_subreg vr1024, vr1025, c
1547 // The insert_subreg becomes a "copy" that defines a val# which can itself
1548 // be coalesced away.
1549 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1550 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1551 LR->valno->copy = DefMI;
1552 }
Evan Chengdb9b1c32008-04-03 16:41:54 +00001553 }
1554
Evan Cheng3ef2d602008-09-09 21:44:23 +00001555 // If resulting interval has a preference that no longer fits because of subreg
1556 // coalescing, just clear the preference.
Evan Cheng40869062008-09-11 18:40:32 +00001557 if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1558 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
Evan Cheng3ef2d602008-09-09 21:44:23 +00001559 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1560 if (!RC->contains(ResDstInt->preference))
1561 ResDstInt->preference = 0;
1562 }
1563
Evan Chengdb9b1c32008-04-03 16:41:54 +00001564 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1565 DOUT << "\n";
1566
David Greene25133302007-06-08 17:18:56 +00001567 ++numJoins;
1568 return true;
1569}
1570
1571/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1572/// compute what the resultant value numbers for each value in the input two
1573/// ranges will be. This is complicated by copies between the two which can
1574/// and will commonly cause multiple value numbers to be merged into one.
1575///
1576/// VN is the value number that we're trying to resolve. InstDefiningValue
1577/// keeps track of the new InstDefiningValue assignment for the result
1578/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1579/// whether a value in this or other is a copy from the opposite set.
1580/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1581/// already been assigned.
1582///
1583/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1584/// contains the value number the copy is from.
1585///
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001586static unsigned ComputeUltimateVN(VNInfo *VNI,
1587 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +00001588 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1589 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +00001590 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001591 SmallVector<int, 16> &OtherValNoAssignments) {
1592 unsigned VN = VNI->id;
1593
David Greene25133302007-06-08 17:18:56 +00001594 // If the VN has already been computed, just return it.
1595 if (ThisValNoAssignments[VN] >= 0)
1596 return ThisValNoAssignments[VN];
1597// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001598
David Greene25133302007-06-08 17:18:56 +00001599 // If this val is not a copy from the other val, then it must be a new value
1600 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +00001601 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +00001602 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001603 NewVNInfo.push_back(VNI);
1604 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001605 }
Evan Chengc14b1442007-08-31 08:04:17 +00001606 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +00001607
1608 // Otherwise, this *is* a copy from the RHS. If the other side has already
1609 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001610 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1611 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +00001612
1613 // Mark this value number as currently being computed, then ask what the
1614 // ultimate value # of the other value is.
1615 ThisValNoAssignments[VN] = -2;
1616 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001617 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1618 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001619 return ThisValNoAssignments[VN] = UltimateVN;
1620}
1621
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001622static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +00001623 return std::find(V.begin(), V.end(), Val) != V.end();
1624}
1625
Evan Cheng7e073ba2008-04-09 20:57:25 +00001626/// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1627/// the specified live interval is defined by a copy from the specified
1628/// register.
1629bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1630 LiveRange *LR,
1631 unsigned Reg) {
1632 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1633 if (SrcReg == Reg)
1634 return true;
1635 if (LR->valno->def == ~0U &&
1636 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1637 *tri_->getSuperRegisters(li.reg)) {
1638 // It's a sub-register live interval, we may not have precise information.
1639 // Re-compute it.
1640 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
Evan Cheng04ee5a12009-01-20 19:12:24 +00001641 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1642 if (DefMI &&
1643 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
Evan Cheng7e073ba2008-04-09 20:57:25 +00001644 DstReg == li.reg && SrcReg == Reg) {
1645 // Cache computed info.
1646 LR->valno->def = LR->start;
1647 LR->valno->copy = DefMI;
1648 return true;
1649 }
1650 }
1651 return false;
1652}
1653
David Greene25133302007-06-08 17:18:56 +00001654/// SimpleJoin - Attempt to joint the specified interval into this one. The
1655/// caller of this method must guarantee that the RHS only contains a single
1656/// value number and that the RHS is not defined by a copy from this
1657/// interval. This returns false if the intervals are not joinable, or it
1658/// joins them and returns true.
Bill Wendling2674d712008-01-04 08:59:18 +00001659bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
David Greene25133302007-06-08 17:18:56 +00001660 assert(RHS.containsOneValue());
1661
1662 // Some number (potentially more than one) value numbers in the current
1663 // interval may be defined as copies from the RHS. Scan the overlapping
1664 // portions of the LHS and RHS, keeping track of this and looking for
1665 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001666 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +00001667
1668 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1669 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1670
1671 if (LHSIt->start < RHSIt->start) {
1672 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1673 if (LHSIt != LHS.begin()) --LHSIt;
1674 } else if (RHSIt->start < LHSIt->start) {
1675 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1676 if (RHSIt != RHS.begin()) --RHSIt;
1677 }
1678
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001679 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +00001680
1681 while (1) {
1682 // Determine if these live intervals overlap.
1683 bool Overlaps = false;
1684 if (LHSIt->start <= RHSIt->start)
1685 Overlaps = LHSIt->end > RHSIt->start;
1686 else
1687 Overlaps = RHSIt->end > LHSIt->start;
1688
1689 // If the live intervals overlap, there are two interesting cases: if the
1690 // LHS interval is defined by a copy from the RHS, it's ok and we record
1691 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +00001692 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +00001693 if (Overlaps) {
1694 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001695 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001696 // Copy from the RHS?
Evan Cheng7e073ba2008-04-09 20:57:25 +00001697 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
David Greene25133302007-06-08 17:18:56 +00001698 return false; // Nope, bail out.
Evan Chengf4ea5102008-05-21 22:34:12 +00001699
1700 if (LHSIt->contains(RHSIt->valno->def))
1701 // Here is an interesting situation:
1702 // BB1:
1703 // vr1025 = copy vr1024
1704 // ..
1705 // BB2:
1706 // vr1024 = op
1707 // = vr1025
1708 // Even though vr1025 is copied from vr1024, it's not safe to
1709 // coalesced them since live range of vr1025 intersects the
1710 // def of vr1024. This happens because vr1025 is assigned the
1711 // value of the previous iteration of vr1024.
1712 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001713 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001714 }
1715
1716 // We know this entire LHS live range is okay, so skip it now.
1717 if (++LHSIt == LHSEnd) break;
1718 continue;
1719 }
1720
1721 if (LHSIt->end < RHSIt->end) {
1722 if (++LHSIt == LHSEnd) break;
1723 } else {
1724 // One interesting case to check here. It's possible that we have
1725 // something like "X3 = Y" which defines a new value number in the LHS,
1726 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001727 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +00001728 // the live ranges don't actually overlap.
1729 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001730 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001731 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +00001732 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +00001733 if (++LHSIt == LHSEnd) break;
1734 } else {
1735 // Otherwise, if this is a copy from the RHS, mark it as being merged
1736 // in.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001737 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
Evan Chengf4ea5102008-05-21 22:34:12 +00001738 if (LHSIt->contains(RHSIt->valno->def))
1739 // Here is an interesting situation:
1740 // BB1:
1741 // vr1025 = copy vr1024
1742 // ..
1743 // BB2:
1744 // vr1024 = op
1745 // = vr1025
1746 // Even though vr1025 is copied from vr1024, it's not safe to
1747 // coalesced them since live range of vr1025 intersects the
1748 // def of vr1024. This happens because vr1025 is assigned the
1749 // value of the previous iteration of vr1024.
1750 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001751 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001752
1753 // We know this entire LHS live range is okay, so skip it now.
1754 if (++LHSIt == LHSEnd) break;
1755 }
1756 }
1757 }
1758
1759 if (++RHSIt == RHSEnd) break;
1760 }
1761 }
1762
Gabor Greife510b3a2007-07-09 12:00:59 +00001763 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +00001764 // the value numbers in EliminatedLHSVals will all be merged together. Since
1765 // the most common case is that EliminatedLHSVals has a single number, we
1766 // optimize for it: if there is more than one value, we merge them all into
1767 // the lowest numbered one, then handle the interval as if we were merging
1768 // with one value number.
Devang Patel8a84e442009-01-05 17:31:22 +00001769 VNInfo *LHSValNo = NULL;
David Greene25133302007-06-08 17:18:56 +00001770 if (EliminatedLHSVals.size() > 1) {
1771 // Loop through all the equal value numbers merging them into the smallest
1772 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001773 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +00001774 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001775 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +00001776 // Merge the current notion of the smallest into the smaller one.
1777 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1778 Smallest = EliminatedLHSVals[i];
1779 } else {
1780 // Merge into the smallest.
1781 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1782 }
1783 }
1784 LHSValNo = Smallest;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001785 } else if (EliminatedLHSVals.empty()) {
1786 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1787 *tri_->getSuperRegisters(LHS.reg))
1788 // Imprecise sub-register information. Can't handle it.
1789 return false;
1790 assert(0 && "No copies from the RHS?");
David Greene25133302007-06-08 17:18:56 +00001791 } else {
David Greene25133302007-06-08 17:18:56 +00001792 LHSValNo = EliminatedLHSVals[0];
1793 }
1794
1795 // Okay, now that there is a single LHS value number that we're merging the
1796 // RHS into, update the value number info for the LHS to indicate that the
1797 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +00001798 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001799 LHSValNo->def = VNI->def;
1800 LHSValNo->copy = VNI->copy;
David Greene25133302007-06-08 17:18:56 +00001801
1802 // Okay, the final step is to loop over the RHS live intervals, adding them to
1803 // the LHS.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001804 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001805 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +00001806 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +00001807 LHS.weight += RHS.weight;
1808 if (RHS.preference && !LHS.preference)
1809 LHS.preference = RHS.preference;
1810
1811 return true;
1812}
1813
1814/// JoinIntervals - Attempt to join these two intervals. On failure, this
1815/// returns false. Otherwise, if one of the intervals being joined is a
1816/// physreg, this method always canonicalizes LHS to be it. The output
1817/// "RHS" will not have been modified, so we can use this information
1818/// below to update aliases.
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001819bool
1820SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
1821 bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +00001822 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +00001823 // coalesced.
David Greene25133302007-06-08 17:18:56 +00001824 SmallVector<int, 16> LHSValNoAssignments;
1825 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +00001826 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1827 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001828 SmallVector<VNInfo*, 16> NewVNInfo;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001829
David Greene25133302007-06-08 17:18:56 +00001830 // If a live interval is a physical register, conservatively check if any
1831 // of its sub-registers is overlapping the live interval of the virtual
1832 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001833 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1834 *tri_->getSubRegisters(LHS.reg)) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001835 // If it's coalescing a virtual register to a physical register, estimate
1836 // its live interval length. This is the *cost* of scanning an entire live
1837 // interval. If the cost is low, we'll do an exhaustive check instead.
Evan Cheng1d8a76d2009-01-13 03:57:45 +00001838
1839 // If this is something like this:
1840 // BB1:
1841 // v1024 = op
1842 // ...
1843 // BB2:
1844 // ...
1845 // RAX = v1024
1846 //
1847 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
1848 // less conservative check. It's possible a sub-register is defined before
1849 // v1024 (or live in) and live out of BB1.
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001850 if (RHS.containsOneValue() &&
Evan Cheng167650d2009-01-13 06:08:37 +00001851 li_->intervalIsInOneMBB(RHS) &&
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001852 li_->getApproximateInstructionCount(RHS) <= 10) {
1853 // Perform a more exhaustive check for some common cases.
1854 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
David Greene25133302007-06-08 17:18:56 +00001855 return false;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001856 } else {
1857 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1858 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1859 DOUT << "Interfere with sub-register ";
1860 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1861 return false;
1862 }
1863 }
Dan Gohman6f0d0242008-02-10 18:45:23 +00001864 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1865 *tri_->getSubRegisters(RHS.reg)) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001866 if (LHS.containsOneValue() &&
1867 li_->getApproximateInstructionCount(LHS) <= 10) {
1868 // Perform a more exhaustive check for some common cases.
1869 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
David Greene25133302007-06-08 17:18:56 +00001870 return false;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001871 } else {
1872 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1873 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1874 DOUT << "Interfere with sub-register ";
1875 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1876 return false;
1877 }
1878 }
David Greene25133302007-06-08 17:18:56 +00001879 }
1880
1881 // Compute ultimate value numbers for the LHS and RHS values.
1882 if (RHS.containsOneValue()) {
1883 // Copies from a liveinterval with a single value are simple to handle and
1884 // very common, handle the special case here. This is important, because
1885 // often RHS is small and LHS is large (e.g. a physreg).
1886
1887 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +00001888 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +00001889 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001890 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001891 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001892 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001893 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001894 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +00001895 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +00001896 // can't swap the LHS/RHS intervals though.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001897 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001898 return SimpleJoin(LHS, RHS);
1899 } else {
Evan Chengc14b1442007-08-31 08:04:17 +00001900 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001901 }
1902 } else {
1903 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +00001904 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001905 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001906 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +00001907 }
1908
1909 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1910 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001911 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +00001912
1913 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1914 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001915 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1916 i != e; ++i) {
1917 VNInfo *VNI = *i;
1918 unsigned VN = VNI->id;
Evan Chengc8d044e2008-02-15 18:24:29 +00001919 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1920 if (LHSSrcReg != RHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001921 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +00001922 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001923 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001924 LHSValNoAssignments[VN] = VN;
1925 } else if (RHSValID == -1) {
1926 // Otherwise, it is a copy from the RHS, and we don't already have a
1927 // value# for it. Keep the current value number, but remember it.
1928 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001929 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001930 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001931 } else {
1932 // Otherwise, use the specified value #.
1933 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001934 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1935 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001936 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001937 }
David Greene25133302007-06-08 17:18:56 +00001938 }
1939 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001940 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001941 LHSValNoAssignments[VN] = VN;
1942 }
1943 }
1944
1945 assert(RHSValID != -1 && "Didn't find value #?");
1946 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001947 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +00001948 // This path doesn't go through ComputeUltimateVN so just set
1949 // it to anything.
1950 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001951 }
David Greene25133302007-06-08 17:18:56 +00001952 } else {
1953 // Loop over the value numbers of the LHS, seeing if any are defined from
1954 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001955 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1956 i != e; ++i) {
1957 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001958 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001959 continue;
1960
1961 // DstReg is known to be a register in the LHS interval. If the src is
1962 // from the RHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001963 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00001964 continue;
1965
1966 // Figure out the value # from the RHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001967 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001968 }
1969
1970 // Loop over the value numbers of the RHS, seeing if any are defined from
1971 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001972 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1973 i != e; ++i) {
1974 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001975 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001976 continue;
1977
1978 // DstReg is known to be a register in the RHS interval. If the src is
1979 // from the LHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001980 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
David Greene25133302007-06-08 17:18:56 +00001981 continue;
1982
1983 // Figure out the value # from the LHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001984 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001985 }
1986
1987 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1988 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001989 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +00001990
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001991 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1992 i != e; ++i) {
1993 VNInfo *VNI = *i;
1994 unsigned VN = VNI->id;
1995 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001996 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001997 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001998 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001999 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00002000 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002001 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2002 i != e; ++i) {
2003 VNInfo *VNI = *i;
2004 unsigned VN = VNI->id;
2005 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00002006 continue;
2007 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +00002008 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002009 NewVNInfo.push_back(VNI);
2010 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00002011 continue;
2012 }
2013
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002014 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00002015 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002016 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00002017 }
2018 }
2019
2020 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +00002021 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +00002022 LiveInterval::const_iterator I = LHS.begin();
2023 LiveInterval::const_iterator IE = LHS.end();
2024 LiveInterval::const_iterator J = RHS.begin();
2025 LiveInterval::const_iterator JE = RHS.end();
2026
2027 // Skip ahead until the first place of potential sharing.
2028 if (I->start < J->start) {
2029 I = std::upper_bound(I, IE, J->start);
2030 if (I != LHS.begin()) --I;
2031 } else if (J->start < I->start) {
2032 J = std::upper_bound(J, JE, I->start);
2033 if (J != RHS.begin()) --J;
2034 }
2035
2036 while (1) {
2037 // Determine if these two live ranges overlap.
2038 bool Overlaps;
2039 if (I->start < J->start) {
2040 Overlaps = I->end > J->start;
2041 } else {
2042 Overlaps = J->end > I->start;
2043 }
2044
2045 // If so, check value # info to determine if they are really different.
2046 if (Overlaps) {
2047 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +00002048 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002049 if (LHSValNoAssignments[I->valno->id] !=
2050 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +00002051 return false;
2052 }
2053
2054 if (I->end < J->end) {
2055 ++I;
2056 if (I == IE) break;
2057 } else {
2058 ++J;
2059 if (J == JE) break;
2060 }
2061 }
2062
Evan Cheng34729252007-10-14 10:08:34 +00002063 // Update kill info. Some live ranges are extended due to copy coalescing.
2064 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2065 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2066 VNInfo *VNI = I->first;
2067 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2068 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00002069 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00002070 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2071 }
2072
2073 // Update kill info. Some live ranges are extended due to copy coalescing.
2074 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2075 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2076 VNInfo *VNI = I->first;
2077 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2078 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00002079 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00002080 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2081 }
2082
Gabor Greife510b3a2007-07-09 12:00:59 +00002083 // If we get here, we know that we can coalesce the live ranges. Ask the
2084 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002085 if ((RHS.ranges.size() > LHS.ranges.size() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002086 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2087 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002088 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002089 Swapped = true;
2090 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002091 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002092 Swapped = false;
2093 }
David Greene25133302007-06-08 17:18:56 +00002094 return true;
2095}
2096
2097namespace {
2098 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2099 // depth of the basic block (the unsigned), and then on the MBB number.
2100 struct DepthMBBCompare {
2101 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2102 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2103 if (LHS.first > RHS.first) return true; // Deeper loops first
2104 return LHS.first == RHS.first &&
2105 LHS.second->getNumber() < RHS.second->getNumber();
2106 }
2107 };
2108}
2109
Evan Cheng8fc9a102007-11-06 08:52:21 +00002110/// getRepIntervalSize - Returns the size of the interval that represents the
2111/// specified register.
2112template<class SF>
2113unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2114 return Rc->getRepIntervalSize(Reg);
2115}
2116
2117/// CopyRecSort::operator - Join priority queue sorting function.
2118///
2119bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2120 // Inner loops first.
2121 if (left.LoopDepth > right.LoopDepth)
2122 return false;
Evan Chengc8d044e2008-02-15 18:24:29 +00002123 else if (left.LoopDepth == right.LoopDepth)
Evan Cheng8fc9a102007-11-06 08:52:21 +00002124 if (left.isBackEdge && !right.isBackEdge)
2125 return false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002126 return true;
2127}
2128
Gabor Greife510b3a2007-07-09 12:00:59 +00002129void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00002130 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00002131 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00002132
Evan Cheng8b0b8742007-10-16 08:04:24 +00002133 std::vector<CopyRec> VirtCopies;
2134 std::vector<CopyRec> PhysCopies;
Evan Cheng7e073ba2008-04-09 20:57:25 +00002135 std::vector<CopyRec> ImpDefCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002136 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00002137 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2138 MII != E;) {
2139 MachineInstr *Inst = MII++;
2140
Evan Cheng32dfbea2007-10-12 08:50:34 +00002141 // If this isn't a copy nor a extract_subreg, we can't join intervals.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002142 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Cheng32dfbea2007-10-12 08:50:34 +00002143 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2144 DstReg = Inst->getOperand(0).getReg();
2145 SrcReg = Inst->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +00002146 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2147 DstReg = Inst->getOperand(0).getReg();
2148 SrcReg = Inst->getOperand(2).getReg();
Evan Cheng04ee5a12009-01-20 19:12:24 +00002149 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
Evan Cheng32dfbea2007-10-12 08:50:34 +00002150 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00002151
Evan Chengc8d044e2008-02-15 18:24:29 +00002152 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2153 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00002154 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002155 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002156 } else {
Evan Cheng7e073ba2008-04-09 20:57:25 +00002157 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2158 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2159 else if (SrcIsPhys || DstIsPhys)
Evan Chengc8d044e2008-02-15 18:24:29 +00002160 PhysCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002161 else
Evan Chengc8d044e2008-02-15 18:24:29 +00002162 VirtCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002163 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002164 }
2165
Evan Cheng8fc9a102007-11-06 08:52:21 +00002166 if (NewHeuristic)
2167 return;
2168
Evan Cheng7e073ba2008-04-09 20:57:25 +00002169 // Try coalescing implicit copies first, followed by copies to / from
2170 // physical registers, then finally copies from virtual registers to
2171 // virtual registers.
2172 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2173 CopyRec &TheCopy = ImpDefCopies[i];
2174 bool Again = false;
2175 if (!JoinCopy(TheCopy, Again))
2176 if (Again)
2177 TryAgain.push_back(TheCopy);
2178 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002179 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2180 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002181 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002182 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002183 if (Again)
2184 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00002185 }
2186 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2187 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002188 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002189 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002190 if (Again)
2191 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00002192 }
2193}
2194
2195void SimpleRegisterCoalescing::joinIntervals() {
2196 DOUT << "********** JOINING INTERVALS ***********\n";
2197
Evan Cheng8fc9a102007-11-06 08:52:21 +00002198 if (NewHeuristic)
2199 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2200
David Greene25133302007-06-08 17:18:56 +00002201 std::vector<CopyRec> TryAgainList;
Dan Gohmana8c763b2008-08-14 18:13:49 +00002202 if (loopInfo->empty()) {
David Greene25133302007-06-08 17:18:56 +00002203 // If there are no loops in the function, join intervals in function order.
2204 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2205 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002206 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002207 } else {
2208 // Otherwise, join intervals in inner loops before other intervals.
2209 // Unfortunately we can't just iterate over loop hierarchy here because
2210 // there may be more MBB's than BB's. Collect MBB's for sorting.
2211
2212 // Join intervals in the function prolog first. We want to join physical
2213 // registers with virtual registers before the intervals got too long.
2214 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002215 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2216 MachineBasicBlock *MBB = I;
2217 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2218 }
David Greene25133302007-06-08 17:18:56 +00002219
2220 // Sort by loop depth.
2221 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2222
2223 // Finally, join intervals in loop nest order.
2224 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002225 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002226 }
2227
2228 // Joining intervals can allow other intervals to be joined. Iteratively join
2229 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00002230 if (NewHeuristic) {
2231 SmallVector<CopyRec, 16> TryAgain;
2232 bool ProgressMade = true;
2233 while (ProgressMade) {
2234 ProgressMade = false;
2235 while (!JoinQueue->empty()) {
2236 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00002237 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002238 bool Success = JoinCopy(R, Again);
2239 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00002240 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002241 else if (Again)
2242 TryAgain.push_back(R);
2243 }
2244
2245 if (ProgressMade) {
2246 while (!TryAgain.empty()) {
2247 JoinQueue->push(TryAgain.back());
2248 TryAgain.pop_back();
2249 }
2250 }
2251 }
2252 } else {
2253 bool ProgressMade = true;
2254 while (ProgressMade) {
2255 ProgressMade = false;
2256
2257 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2258 CopyRec &TheCopy = TryAgainList[i];
2259 if (TheCopy.MI) {
2260 bool Again = false;
2261 bool Success = JoinCopy(TheCopy, Again);
2262 if (Success || !Again) {
2263 TheCopy.MI = 0; // Mark this one as done.
2264 ProgressMade = true;
2265 }
Evan Cheng0547bab2007-11-01 06:22:48 +00002266 }
David Greene25133302007-06-08 17:18:56 +00002267 }
2268 }
2269 }
2270
Evan Cheng8fc9a102007-11-06 08:52:21 +00002271 if (NewHeuristic)
Evan Chengc8d044e2008-02-15 18:24:29 +00002272 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00002273}
2274
2275/// Return true if the two specified registers belong to different register
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002276/// classes. The registers may be either phys or virt regs.
Evan Chenge00f5de2008-06-19 01:39:21 +00002277bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002278SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2279 unsigned RegB) const {
David Greene25133302007-06-08 17:18:56 +00002280 // Get the register classes for the first reg.
Dan Gohman6f0d0242008-02-10 18:45:23 +00002281 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2282 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
David Greene25133302007-06-08 17:18:56 +00002283 "Shouldn't consider two physregs!");
Evan Chengc8d044e2008-02-15 18:24:29 +00002284 return !mri_->getRegClass(RegB)->contains(RegA);
David Greene25133302007-06-08 17:18:56 +00002285 }
2286
2287 // Compare against the regclass for the second reg.
Evan Chenge00f5de2008-06-19 01:39:21 +00002288 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2289 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2290 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002291 return RegClassA != RegClassB;
Evan Chenge00f5de2008-06-19 01:39:21 +00002292 }
2293 return !RegClassA->contains(RegB);
David Greene25133302007-06-08 17:18:56 +00002294}
2295
2296/// lastRegisterUse - Returns the last use of the specific register between
Evan Chengc8d044e2008-02-15 18:24:29 +00002297/// cycles Start and End or NULL if there are no uses.
2298MachineOperand *
Chris Lattner84bc5422007-12-31 04:13:23 +00002299SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
Evan Chengc8d044e2008-02-15 18:24:29 +00002300 unsigned Reg, unsigned &UseIdx) const{
2301 UseIdx = 0;
2302 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2303 MachineOperand *LastUse = NULL;
2304 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2305 E = mri_->use_end(); I != E; ++I) {
2306 MachineOperand &Use = I.getOperand();
2307 MachineInstr *UseMI = Use.getParent();
Evan Cheng04ee5a12009-01-20 19:12:24 +00002308 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2309 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2310 SrcReg == DstReg)
Evan Chenga2fb6342008-03-25 02:02:19 +00002311 // Ignore identity copies.
2312 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +00002313 unsigned Idx = li_->getInstructionIndex(UseMI);
2314 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2315 LastUse = &Use;
2316 UseIdx = Idx;
2317 }
2318 }
2319 return LastUse;
2320 }
2321
David Greene25133302007-06-08 17:18:56 +00002322 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2323 int s = Start;
2324 while (e >= s) {
2325 // Skip deleted instructions
2326 MachineInstr *MI = li_->getInstructionFromIndex(e);
2327 while ((e - InstrSlots::NUM) >= s && !MI) {
2328 e -= InstrSlots::NUM;
2329 MI = li_->getInstructionFromIndex(e);
2330 }
2331 if (e < s || MI == NULL)
2332 return NULL;
2333
Evan Chenga2fb6342008-03-25 02:02:19 +00002334 // Ignore identity copies.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002335 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2336 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2337 SrcReg == DstReg))
Evan Chenga2fb6342008-03-25 02:02:19 +00002338 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2339 MachineOperand &Use = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002340 if (Use.isReg() && Use.isUse() && Use.getReg() &&
Evan Chenga2fb6342008-03-25 02:02:19 +00002341 tri_->regsOverlap(Use.getReg(), Reg)) {
2342 UseIdx = e;
2343 return &Use;
2344 }
David Greene25133302007-06-08 17:18:56 +00002345 }
David Greene25133302007-06-08 17:18:56 +00002346
2347 e -= InstrSlots::NUM;
2348 }
2349
2350 return NULL;
2351}
2352
2353
David Greene25133302007-06-08 17:18:56 +00002354void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +00002355 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +00002356 cerr << tri_->getName(reg);
David Greene25133302007-06-08 17:18:56 +00002357 else
2358 cerr << "%reg" << reg;
2359}
2360
2361void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng8fc9a102007-11-06 08:52:21 +00002362 JoinedCopies.clear();
Evan Chengcd047082008-08-30 09:09:33 +00002363 ReMatCopies.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002364 ReMatDefs.clear();
David Greene25133302007-06-08 17:18:56 +00002365}
2366
2367static bool isZeroLengthInterval(LiveInterval *li) {
2368 for (LiveInterval::Ranges::const_iterator
2369 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2370 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2371 return false;
2372 return true;
2373}
2374
Evan Chengdb9b1c32008-04-03 16:41:54 +00002375/// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2376/// turn the copy into an implicit def.
2377bool
2378SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2379 MachineBasicBlock *MBB,
2380 unsigned DstReg, unsigned SrcReg) {
2381 MachineInstr *CopyMI = &*I;
2382 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2383 if (!li_->hasInterval(SrcReg))
2384 return false;
2385 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2386 if (!SrcInt.empty())
2387 return false;
Evan Chengf20d9432008-04-09 01:30:15 +00002388 if (!li_->hasInterval(DstReg))
2389 return false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002390 LiveInterval &DstInt = li_->getInterval(DstReg);
Evan Chengff7a3e52008-04-16 18:48:43 +00002391 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002392 DstInt.removeValNo(DstLR->valno);
2393 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2394 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2395 CopyMI->RemoveOperand(i);
Dan Gohmana8c763b2008-08-14 18:13:49 +00002396 bool NoUse = mri_->use_empty(SrcReg);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002397 if (NoUse) {
2398 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2399 E = mri_->reg_end(); I != E; ) {
2400 assert(I.getOperand().isDef());
2401 MachineInstr *DefMI = &*I;
2402 ++I;
2403 // The implicit_def source has no other uses, delete it.
2404 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2405 li_->RemoveMachineInstrFromMaps(DefMI);
2406 DefMI->eraseFromParent();
Evan Chengdb9b1c32008-04-03 16:41:54 +00002407 }
2408 }
2409 ++I;
2410 return true;
2411}
2412
2413
David Greene25133302007-06-08 17:18:56 +00002414bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2415 mf_ = &fn;
Evan Cheng70071432008-02-13 03:01:43 +00002416 mri_ = &fn.getRegInfo();
David Greene25133302007-06-08 17:18:56 +00002417 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00002418 tri_ = tm_->getRegisterInfo();
David Greene25133302007-06-08 17:18:56 +00002419 tii_ = tm_->getInstrInfo();
2420 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00002421 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00002422
2423 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2424 << "********** Function: "
2425 << ((Value*)mf_->getFunction())->getName() << '\n';
2426
Dan Gohman6f0d0242008-02-10 18:45:23 +00002427 allocatableRegs_ = tri_->getAllocatableSet(fn);
2428 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2429 E = tri_->regclass_end(); I != E; ++I)
Bill Wendling2674d712008-01-04 08:59:18 +00002430 allocatableRCRegs_.insert(std::make_pair(*I,
Dan Gohman6f0d0242008-02-10 18:45:23 +00002431 tri_->getAllocatableSet(fn, *I)));
David Greene25133302007-06-08 17:18:56 +00002432
Gabor Greife510b3a2007-07-09 12:00:59 +00002433 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00002434 if (EnableJoining) {
2435 joinIntervals();
Bill Wendlingbebbded2008-12-19 02:09:57 +00002436 DEBUG({
2437 DOUT << "********** INTERVALS POST JOINING **********\n";
2438 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2439 I->second->print(DOUT, tri_);
2440 DOUT << "\n";
2441 }
2442 });
David Greene25133302007-06-08 17:18:56 +00002443 }
2444
Evan Chengc8d044e2008-02-15 18:24:29 +00002445 // Perform a final pass over the instructions and compute spill weights
2446 // and remove identity moves.
Evan Chengb3990d52008-10-27 23:21:01 +00002447 SmallVector<unsigned, 4> DeadDefs;
David Greene25133302007-06-08 17:18:56 +00002448 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2449 mbbi != mbbe; ++mbbi) {
2450 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002451 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00002452
2453 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2454 mii != mie; ) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002455 MachineInstr *MI = mii;
Evan Cheng04ee5a12009-01-20 19:12:24 +00002456 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Chenga971dbd2008-04-24 09:06:33 +00002457 if (JoinedCopies.count(MI)) {
2458 // Delete all coalesced copies.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002459 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002460 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2461 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2462 "Unrecognized copy instruction");
2463 DstReg = MI->getOperand(0).getReg();
2464 }
2465 if (MI->registerDefIsDead(DstReg)) {
2466 LiveInterval &li = li_->getInterval(DstReg);
2467 if (!ShortenDeadCopySrcLiveRange(li, MI))
2468 ShortenDeadCopyLiveRange(li, MI);
2469 }
2470 li_->RemoveMachineInstrFromMaps(MI);
2471 mii = mbbi->erase(mii);
2472 ++numPeep;
2473 continue;
2474 }
2475
Evan Cheng20580a12008-09-19 17:38:47 +00002476 // Now check if this is a remat'ed def instruction which is now dead.
2477 if (ReMatDefs.count(MI)) {
2478 bool isDead = true;
2479 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2480 const MachineOperand &MO = MI->getOperand(i);
Evan Chengb3990d52008-10-27 23:21:01 +00002481 if (!MO.isReg())
Evan Cheng20580a12008-09-19 17:38:47 +00002482 continue;
2483 unsigned Reg = MO.getReg();
Evan Cheng6792e902009-02-04 18:18:58 +00002484 if (!Reg)
2485 continue;
Evan Chengb3990d52008-10-27 23:21:01 +00002486 if (TargetRegisterInfo::isVirtualRegister(Reg))
2487 DeadDefs.push_back(Reg);
2488 if (MO.isDead())
2489 continue;
Evan Cheng20580a12008-09-19 17:38:47 +00002490 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2491 !mri_->use_empty(Reg)) {
2492 isDead = false;
2493 break;
2494 }
2495 }
2496 if (isDead) {
Evan Chengb3990d52008-10-27 23:21:01 +00002497 while (!DeadDefs.empty()) {
2498 unsigned DeadDef = DeadDefs.back();
2499 DeadDefs.pop_back();
2500 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2501 }
Evan Cheng20580a12008-09-19 17:38:47 +00002502 li_->RemoveMachineInstrFromMaps(mii);
2503 mii = mbbi->erase(mii);
Evan Chengfee2d692008-09-19 22:49:39 +00002504 continue;
Evan Chengb3990d52008-10-27 23:21:01 +00002505 } else
2506 DeadDefs.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002507 }
2508
Evan Chenga971dbd2008-04-24 09:06:33 +00002509 // If the move will be an identity move delete it
Evan Cheng04ee5a12009-01-20 19:12:24 +00002510 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
Evan Chenga971dbd2008-04-24 09:06:33 +00002511 if (isMove && SrcReg == DstReg) {
2512 if (li_->hasInterval(SrcReg)) {
2513 LiveInterval &RegInt = li_->getInterval(SrcReg);
Evan Cheng3c88d742008-03-18 08:26:47 +00002514 // If def of this move instruction is dead, remove its live range
2515 // from the dstination register's live interval.
Evan Cheng20580a12008-09-19 17:38:47 +00002516 if (MI->registerDefIsDead(DstReg)) {
2517 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2518 ShortenDeadCopyLiveRange(RegInt, MI);
Evan Cheng3c88d742008-03-18 08:26:47 +00002519 }
2520 }
Evan Cheng20580a12008-09-19 17:38:47 +00002521 li_->RemoveMachineInstrFromMaps(MI);
David Greene25133302007-06-08 17:18:56 +00002522 mii = mbbi->erase(mii);
2523 ++numPeep;
Evan Chenga971dbd2008-04-24 09:06:33 +00002524 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
David Greene25133302007-06-08 17:18:56 +00002525 SmallSet<unsigned, 4> UniqueUses;
Evan Cheng20580a12008-09-19 17:38:47 +00002526 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2527 const MachineOperand &mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002528 if (mop.isReg() && mop.getReg() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002529 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002530 unsigned reg = mop.getReg();
David Greene25133302007-06-08 17:18:56 +00002531 // Multiple uses of reg by the same instruction. It should not
2532 // contribute to spill weight again.
2533 if (UniqueUses.count(reg) != 0)
2534 continue;
2535 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002536 RegInt.weight +=
Evan Chengc3417602008-06-21 06:45:54 +00002537 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00002538 UniqueUses.insert(reg);
2539 }
2540 }
2541 ++mii;
2542 }
2543 }
2544 }
2545
2546 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +00002547 LiveInterval &LI = *I->second;
Dan Gohman6f0d0242008-02-10 18:45:23 +00002548 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
David Greene25133302007-06-08 17:18:56 +00002549 // If the live interval length is essentially zero, i.e. in every live
2550 // range the use follows def immediately, it doesn't make sense to spill
2551 // it and hope it will be easier to allocate for this li.
2552 if (isZeroLengthInterval(&LI))
2553 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002554 else {
2555 bool isLoad = false;
Evan Chengdc377862008-09-30 15:44:16 +00002556 SmallVector<LiveInterval*, 4> SpillIs;
2557 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00002558 // If all of the definitions of the interval are re-materializable,
2559 // it is a preferred candidate for spilling. If non of the defs are
2560 // loads, then it's potentially very cheap to re-materialize.
2561 // FIXME: this gets much more complicated once we support non-trivial
2562 // re-materialization.
2563 if (isLoad)
2564 LI.weight *= 0.9F;
2565 else
2566 LI.weight *= 0.5F;
2567 }
2568 }
David Greene25133302007-06-08 17:18:56 +00002569
2570 // Slightly prefer live interval that has been assigned a preferred reg.
2571 if (LI.preference)
2572 LI.weight *= 1.01F;
2573
2574 // Divide the weight of the interval by its size. This encourages
2575 // spilling of intervals that are large and have few uses, and
2576 // discourages spilling of small intervals with many uses.
Owen Anderson496bac52008-07-23 19:47:27 +00002577 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
David Greene25133302007-06-08 17:18:56 +00002578 }
2579 }
2580
2581 DEBUG(dump());
2582 return true;
2583}
2584
2585/// print - Implement the dump method.
2586void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2587 li_->print(O, m);
2588}
David Greene2c17c4d2007-09-06 16:18:45 +00002589
2590RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2591 return new SimpleRegisterCoalescing();
2592}
2593
2594// Make sure that anything that uses RegisterCoalescer pulls in this file...
2595DEFINING_FILE_FOR(SimpleRegisterCoalescing)