blob: 60f7f403a093504763926eb23efb9bddaaf6d379 [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
Evan Chenga2e64352009-03-11 00:03:21 +0000196 // physreg has sub-registers, update their live intervals as well.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000197 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
Evan Chenga2e64352009-03-11 00:03:21 +0000198 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
199 LiveInterval &SRLI = li_->getInterval(*SR);
200 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
201 SRLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000202 }
203 }
204
205 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng25f34a32008-09-15 06:28:41 +0000206 if (BValNo != ValLR->valno) {
207 IntB.addKills(ValLR->valno, BValNo->kills);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000208 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
Evan Cheng25f34a32008-09-15 06:28:41 +0000209 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000210 DOUT << " result = "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000211 DOUT << "\n";
212
213 // If the source instruction was killing the source register before the
214 // merge, unset the isKill marker given the live range has been extended.
215 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
Evan Cheng25f34a32008-09-15 06:28:41 +0000216 if (UIdx != -1) {
Chris Lattnerf7382302007-12-30 21:56:09 +0000217 ValLREndInst->getOperand(UIdx).setIsKill(false);
Evan Cheng25f34a32008-09-15 06:28:41 +0000218 IntB.removeKill(ValLR->valno, FillerStart);
219 }
Evan Cheng70071432008-02-13 03:01:43 +0000220
221 ++numExtends;
222 return true;
223}
224
Evan Cheng559f4222008-02-16 02:32:17 +0000225/// HasOtherReachingDefs - Return true if there are definitions of IntB
226/// other than BValNo val# that can reach uses of AValno val# of IntA.
227bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
228 LiveInterval &IntB,
229 VNInfo *AValNo,
230 VNInfo *BValNo) {
231 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
232 AI != AE; ++AI) {
233 if (AI->valno != AValNo) continue;
234 LiveInterval::Ranges::iterator BI =
235 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
236 if (BI != IntB.ranges.begin())
237 --BI;
238 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
239 if (BI->valno == BValNo)
240 continue;
241 if (BI->start <= AI->start && BI->end > AI->start)
242 return true;
243 if (BI->start > AI->start && BI->start < AI->end)
244 return true;
245 }
246 }
247 return false;
248}
249
Evan Cheng70071432008-02-13 03:01:43 +0000250/// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
251/// being the source and IntB being the dest, thus this defines a value number
252/// in IntB. If the source value number (in IntA) is defined by a commutable
253/// instruction and its other operand is coalesced to the copy dest register,
254/// see if we can transform the copy into a noop by commuting the definition. For
255/// example,
256///
257/// A3 = op A2 B0<kill>
258/// ...
259/// B1 = A3 <- this copy
260/// ...
261/// = op A3 <- more uses
262///
263/// ==>
264///
265/// B2 = op B0 A2<kill>
266/// ...
267/// B1 = B2 <- now an identify copy
268/// ...
269/// = op B2 <- more uses
270///
271/// This returns true if an interval was modified.
272///
273bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
274 LiveInterval &IntB,
275 MachineInstr *CopyMI) {
Evan Cheng70071432008-02-13 03:01:43 +0000276 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
277
Evan Chenga9407f52008-02-18 18:56:31 +0000278 // FIXME: For now, only eliminate the copy by commuting its def when the
279 // source register is a virtual register. We want to guard against cases
280 // where the copy is a back edge copy and commuting the def lengthen the
281 // live interval of the source register to the entire loop.
282 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
Evan Cheng96cfff02008-02-18 08:40:53 +0000283 return false;
284
Evan Chengc8d044e2008-02-15 18:24:29 +0000285 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
Evan Cheng70071432008-02-13 03:01:43 +0000286 // the example above.
287 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000288 assert(BLR != IntB.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000289 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000290
Evan Cheng70071432008-02-13 03:01:43 +0000291 // Get the location that B is defined at. Two options: either this value has
292 // an unknown definition point or it is defined at CopyIdx. If unknown, we
293 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000294 if (!BValNo->copy) return false;
Evan Cheng70071432008-02-13 03:01:43 +0000295 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
296
297 // AValNo is the value number in A that defines the copy, A3 in the example.
298 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000299 assert(ALR != IntA.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000300 VNInfo *AValNo = ALR->valno;
Evan Chenge35a6d12008-02-13 08:41:08 +0000301 // If other defs can reach uses of this def, then it's not safe to perform
302 // the optimization.
303 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
Evan Cheng70071432008-02-13 03:01:43 +0000304 return false;
305 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
306 const TargetInstrDesc &TID = DefMI->getDesc();
Evan Chengc8d044e2008-02-15 18:24:29 +0000307 unsigned NewDstIdx;
308 if (!TID.isCommutable() ||
309 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
Evan Cheng70071432008-02-13 03:01:43 +0000310 return false;
311
Evan Chengc8d044e2008-02-15 18:24:29 +0000312 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
313 unsigned NewReg = NewDstMO.getReg();
314 if (NewReg != IntB.reg || !NewDstMO.isKill())
Evan Cheng70071432008-02-13 03:01:43 +0000315 return false;
316
317 // Make sure there are no other definitions of IntB that would reach the
318 // uses which the new definition can reach.
Evan Cheng559f4222008-02-16 02:32:17 +0000319 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
320 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000321
Evan Chenged70cbb32008-03-26 19:03:01 +0000322 // If some of the uses of IntA.reg is already coalesced away, return false.
323 // It's not possible to determine whether it's safe to perform the coalescing.
324 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
325 UE = mri_->use_end(); UI != UE; ++UI) {
326 MachineInstr *UseMI = &*UI;
327 unsigned UseIdx = li_->getInstructionIndex(UseMI);
328 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000329 if (ULR == IntA.end())
330 continue;
Evan Chenged70cbb32008-03-26 19:03:01 +0000331 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
332 return false;
333 }
334
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000335 // At this point we have decided that it is legal to do this
336 // transformation. Start by commuting the instruction.
Evan Cheng70071432008-02-13 03:01:43 +0000337 MachineBasicBlock *MBB = DefMI->getParent();
338 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
Evan Cheng559f4222008-02-16 02:32:17 +0000339 if (!NewMI)
340 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000341 if (NewMI != DefMI) {
342 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
343 MBB->insert(DefMI, NewMI);
344 MBB->erase(DefMI);
345 }
Evan Cheng6130f662008-03-05 00:59:57 +0000346 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
Evan Cheng70071432008-02-13 03:01:43 +0000347 NewMI->getOperand(OpIdx).setIsKill();
348
Evan Cheng70071432008-02-13 03:01:43 +0000349 bool BHasPHIKill = BValNo->hasPHIKill;
350 SmallVector<VNInfo*, 4> BDeadValNos;
351 SmallVector<unsigned, 4> BKills;
352 std::map<unsigned, unsigned> BExtend;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000353
354 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
355 // A = or A, B
356 // ...
357 // B = A
358 // ...
359 // C = A<kill>
360 // ...
361 // = B
362 //
363 // then do not add kills of A to the newly created B interval.
364 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
365 if (Extended)
366 BExtend[ALR->end] = BLR->end;
367
368 // Update uses of IntA of the specific Val# with IntB.
Evan Chenga2e64352009-03-11 00:03:21 +0000369 bool BHasSubRegs = false;
370 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
371 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
Evan Cheng70071432008-02-13 03:01:43 +0000372 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
373 UE = mri_->use_end(); UI != UE;) {
374 MachineOperand &UseMO = UI.getOperand();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000375 MachineInstr *UseMI = &*UI;
Evan Cheng70071432008-02-13 03:01:43 +0000376 ++UI;
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000377 if (JoinedCopies.count(UseMI))
Evan Chenged70cbb32008-03-26 19:03:01 +0000378 continue;
Evan Cheng70071432008-02-13 03:01:43 +0000379 unsigned UseIdx = li_->getInstructionIndex(UseMI);
380 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000381 if (ULR == IntA.end() || ULR->valno != AValNo)
Evan Cheng70071432008-02-13 03:01:43 +0000382 continue;
383 UseMO.setReg(NewReg);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000384 if (UseMI == CopyMI)
385 continue;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000386 if (UseMO.isKill()) {
387 if (Extended)
388 UseMO.setIsKill(false);
389 else
390 BKills.push_back(li_->getUseIndex(UseIdx)+1);
391 }
Evan Cheng04ee5a12009-01-20 19:12:24 +0000392 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
393 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000394 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +0000395 if (DstReg == IntB.reg) {
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000396 // This copy will become a noop. If it's defining a new val#,
397 // remove that val# as well. However this live range is being
398 // extended to the end of the existing live range defined by the copy.
399 unsigned DefIdx = li_->getDefIndex(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000400 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000401 BHasPHIKill |= DLR->valno->hasPHIKill;
402 assert(DLR->valno->def == DefIdx);
403 BDeadValNos.push_back(DLR->valno);
404 BExtend[DLR->start] = DLR->end;
405 JoinedCopies.insert(UseMI);
406 // If this is a kill but it's going to be removed, the last use
407 // of the same val# is the new kill.
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000408 if (UseMO.isKill())
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000409 BKills.pop_back();
Evan Cheng70071432008-02-13 03:01:43 +0000410 }
411 }
412
413 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
414 // simply extend BLR if CopyMI doesn't end the range.
415 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
416
Evan Cheng739583b2008-06-17 20:11:16 +0000417 // Remove val#'s defined by copies that will be coalesced away.
Evan Chenga597a972009-03-11 22:18:44 +0000418 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
419 VNInfo *DeadVNI = BDeadValNos[i];
420 if (BHasSubRegs) {
421 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
422 LiveInterval &SRLI = li_->getInterval(*SR);
423 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
424 SRLI.removeValNo(SRLR->valno);
425 }
426 }
Evan Cheng70071432008-02-13 03:01:43 +0000427 IntB.removeValNo(BDeadValNos[i]);
Evan Chenga597a972009-03-11 22:18:44 +0000428 }
Evan Cheng739583b2008-06-17 20:11:16 +0000429
430 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
431 // is updated. Kills are also updated.
432 VNInfo *ValNo = BValNo;
433 ValNo->def = AValNo->def;
434 ValNo->copy = NULL;
435 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
436 unsigned Kill = ValNo->kills[j];
437 if (Kill != BLR->end)
438 BKills.push_back(Kill);
439 }
440 ValNo->kills.clear();
Evan Cheng70071432008-02-13 03:01:43 +0000441 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
442 AI != AE; ++AI) {
443 if (AI->valno != AValNo) continue;
444 unsigned End = AI->end;
445 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
446 if (EI != BExtend.end())
447 End = EI->second;
448 IntB.addRange(LiveRange(AI->start, End, ValNo));
Evan Chenga2e64352009-03-11 00:03:21 +0000449
450 // If the IntB live range is assigned to a physical register, and if that
451 // physreg has sub-registers, update their live intervals as well.
Evan Chenga597a972009-03-11 22:18:44 +0000452 if (BHasSubRegs) {
Evan Chenga2e64352009-03-11 00:03:21 +0000453 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
454 LiveInterval &SRLI = li_->getInterval(*SR);
455 SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
456 }
457 }
Evan Cheng70071432008-02-13 03:01:43 +0000458 }
459 IntB.addKills(ValNo, BKills);
460 ValNo->hasPHIKill = BHasPHIKill;
461
462 DOUT << " result = "; IntB.print(DOUT, tri_);
463 DOUT << "\n";
464
465 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
466 IntA.removeValNo(AValNo);
467 DOUT << " result = "; IntA.print(DOUT, tri_);
468 DOUT << "\n";
469
470 ++numCommutes;
David Greene25133302007-06-08 17:18:56 +0000471 return true;
472}
473
Evan Cheng961154f2009-02-05 08:45:04 +0000474/// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
475/// fallthoughs to SuccMBB.
476static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
477 MachineBasicBlock *SuccMBB,
478 const TargetInstrInfo *tii_) {
479 if (MBB == SuccMBB)
480 return true;
481 MachineBasicBlock *TBB = 0, *FBB = 0;
482 SmallVector<MachineOperand, 4> Cond;
483 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
484 MBB->isSuccessor(SuccMBB);
485}
486
487/// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
488/// from a physical register live interval as well as from the live intervals
489/// of its sub-registers.
490static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
491 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
492 li.removeRange(Start, End, true);
493 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
494 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
495 if (!li_->hasInterval(*SR))
496 continue;
497 LiveInterval &sli = li_->getInterval(*SR);
498 unsigned RemoveEnd = Start;
499 while (RemoveEnd != End) {
500 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
501 if (LR == sli.end())
502 break;
503 RemoveEnd = (LR->end < End) ? LR->end : End;
504 sli.removeRange(Start, RemoveEnd, true);
505 Start = RemoveEnd;
506 }
507 }
508 }
509}
510
511/// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
Evan Cheng86fb9fd2009-02-08 08:24:28 +0000512/// as the copy instruction, trim the live interval to the last use and return
Evan Cheng961154f2009-02-05 08:45:04 +0000513/// true.
514bool
515SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(unsigned CopyIdx,
516 MachineBasicBlock *CopyMBB,
517 LiveInterval &li,
518 const LiveRange *LR) {
519 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
520 unsigned LastUseIdx;
521 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
522 LastUseIdx);
523 if (LastUse) {
524 MachineInstr *LastUseMI = LastUse->getParent();
525 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
526 // r1024 = op
527 // ...
528 // BB1:
529 // = r1024
530 //
531 // BB2:
532 // r1025<dead> = r1024<kill>
533 if (MBBStart < LR->end)
534 removeRange(li, MBBStart, LR->end, li_, tri_);
535 return true;
536 }
537
538 // There are uses before the copy, just shorten the live range to the end
539 // of last use.
540 LastUse->setIsKill();
541 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
Evan Cheng58207f12009-02-22 08:35:56 +0000542 li.addKill(LR->valno, LastUseIdx+1);
Evan Cheng961154f2009-02-05 08:45:04 +0000543 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
544 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
545 DstReg == li.reg) {
546 // Last use is itself an identity code.
547 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
548 LastUseMI->getOperand(DeadIdx).setIsDead();
549 }
550 return true;
551 }
552
553 // Is it livein?
554 if (LR->start <= MBBStart && LR->end > MBBStart) {
555 if (LR->start == 0) {
556 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
557 // Live-in to the function but dead. Remove it from entry live-in set.
558 mf_->begin()->removeLiveIn(li.reg);
559 }
560 // FIXME: Shorten intervals in BBs that reaches this BB.
561 }
562
563 return false;
564}
565
Evan Chengcd047082008-08-30 09:09:33 +0000566/// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
567/// computation, replace the copy by rematerialize the definition.
568bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
569 unsigned DstReg,
570 MachineInstr *CopyMI) {
571 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
572 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000573 assert(SrcLR != SrcInt.end() && "Live range not found!");
Evan Chengcd047082008-08-30 09:09:33 +0000574 VNInfo *ValNo = SrcLR->valno;
575 // If other defs can reach uses of this def, then it's not safe to perform
576 // the optimization.
577 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
578 return false;
579 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
580 const TargetInstrDesc &TID = DefMI->getDesc();
581 if (!TID.isAsCheapAsAMove())
582 return false;
Evan Cheng54801f782009-02-05 22:24:17 +0000583 if (!DefMI->getDesc().isRematerializable() ||
584 !tii_->isTriviallyReMaterializable(DefMI))
585 return false;
Evan Chengcd047082008-08-30 09:09:33 +0000586 bool SawStore = false;
587 if (!DefMI->isSafeToMove(tii_, SawStore))
588 return false;
589
590 unsigned DefIdx = li_->getDefIndex(CopyIdx);
591 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
592 DLR->valno->copy = NULL;
Evan Cheng195cd3a2008-10-13 18:35:52 +0000593 // Don't forget to update sub-register intervals.
594 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
595 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
596 if (!li_->hasInterval(*SR))
597 continue;
598 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
599 if (DLR && DLR->valno->copy == CopyMI)
600 DLR->valno->copy = NULL;
601 }
602 }
Evan Chengcd047082008-08-30 09:09:33 +0000603
Evan Cheng961154f2009-02-05 08:45:04 +0000604 // If copy kills the source register, find the last use and propagate
605 // kill.
Evan Chengcd047082008-08-30 09:09:33 +0000606 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng961154f2009-02-05 08:45:04 +0000607 if (CopyMI->killsRegister(SrcInt.reg))
608 TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR);
609
Dan Gohman3afda6e2008-10-21 03:24:31 +0000610 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
611 CopyMI->removeFromParent();
Evan Chengcd047082008-08-30 09:09:33 +0000612 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
613 MachineInstr *NewMI = prior(MII);
Chris Lattner99cbdff2008-10-11 23:59:03 +0000614 // CopyMI may have implicit operands, transfer them over to the newly
Evan Chengcd047082008-08-30 09:09:33 +0000615 // rematerialized instruction. And update implicit def interval valnos.
616 for (unsigned i = CopyMI->getDesc().getNumOperands(),
617 e = CopyMI->getNumOperands(); i != e; ++i) {
618 MachineOperand &MO = CopyMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000619 if (MO.isReg() && MO.isImplicit())
Evan Chengcd047082008-08-30 09:09:33 +0000620 NewMI->addOperand(MO);
Owen Anderson369e9872008-09-10 20:41:13 +0000621 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
Evan Chengcd047082008-08-30 09:09:33 +0000622 unsigned Reg = MO.getReg();
623 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
624 if (DLR && DLR->valno->copy == CopyMI)
625 DLR->valno->copy = NULL;
626 }
627 }
628
629 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
Dan Gohman3afda6e2008-10-21 03:24:31 +0000630 MBB->getParent()->DeleteMachineInstr(CopyMI);
Evan Chengcd047082008-08-30 09:09:33 +0000631 ReMatCopies.insert(CopyMI);
Evan Cheng20580a12008-09-19 17:38:47 +0000632 ReMatDefs.insert(DefMI);
Evan Chengcd047082008-08-30 09:09:33 +0000633 ++NumReMats;
634 return true;
635}
636
Evan Cheng8fc9a102007-11-06 08:52:21 +0000637/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
638///
639bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
Evan Cheng7e073ba2008-04-09 20:57:25 +0000640 unsigned DstReg) const {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000641 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000642 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000643 if (!L)
644 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000645 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000646 return false;
647
Evan Cheng8fc9a102007-11-06 08:52:21 +0000648 LiveInterval &LI = li_->getInterval(DstReg);
649 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
650 LiveInterval::const_iterator DstLR =
651 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
652 if (DstLR == LI.end())
653 return false;
Owen Andersonb3db9c92008-06-23 22:12:23 +0000654 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
Evan Cheng70071432008-02-13 03:01:43 +0000655 if (DstLR->valno->kills.size() == 1 &&
656 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
Evan Cheng8fc9a102007-11-06 08:52:21 +0000657 return true;
658 return false;
659}
660
Evan Chengc8d044e2008-02-15 18:24:29 +0000661/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
662/// update the subregister number if it is not zero. If DstReg is a
663/// physical register and the existing subregister number of the def / use
664/// being updated is not zero, make sure to set it to the correct physical
665/// subregister.
666void
667SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
668 unsigned SubIdx) {
669 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
670 if (DstIsPhys && SubIdx) {
671 // Figure out the real physical register we are updating with.
672 DstReg = tri_->getSubReg(DstReg, SubIdx);
673 SubIdx = 0;
674 }
675
676 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
677 E = mri_->reg_end(); I != E; ) {
678 MachineOperand &O = I.getOperand();
Evan Cheng70366b92008-03-21 19:09:30 +0000679 MachineInstr *UseMI = &*I;
Evan Chengc8d044e2008-02-15 18:24:29 +0000680 ++I;
Evan Cheng621d1572008-04-17 00:06:42 +0000681 unsigned OldSubIdx = O.getSubReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000682 if (DstIsPhys) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000683 unsigned UseDstReg = DstReg;
Evan Cheng621d1572008-04-17 00:06:42 +0000684 if (OldSubIdx)
685 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
Evan Chengcd047082008-08-30 09:09:33 +0000686
Evan Cheng04ee5a12009-01-20 19:12:24 +0000687 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
688 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
689 CopySrcSubIdx, CopyDstSubIdx) &&
Evan Chengcd047082008-08-30 09:09:33 +0000690 CopySrcReg != CopyDstReg &&
691 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
692 // If the use is a copy and it won't be coalesced away, and its source
693 // is defined by a trivial computation, try to rematerialize it instead.
694 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
695 continue;
696 }
697
Evan Chengc8d044e2008-02-15 18:24:29 +0000698 O.setReg(UseDstReg);
699 O.setSubReg(0);
Evan Chengee9e1b02008-09-12 18:13:14 +0000700 continue;
701 }
702
703 // Sub-register indexes goes from small to large. e.g.
704 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
705 // EAX: 1 -> AL, 2 -> AX
706 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
707 // sub-register 2 is also AX.
708 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
709 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
710 else if (SubIdx)
711 O.setSubReg(SubIdx);
712 // Remove would-be duplicated kill marker.
713 if (O.isKill() && UseMI->killsRegister(DstReg))
714 O.setIsKill(false);
715 O.setReg(DstReg);
716
717 // After updating the operand, check if the machine instruction has
718 // become a copy. If so, update its val# information.
719 const TargetInstrDesc &TID = UseMI->getDesc();
Evan Cheng04ee5a12009-01-20 19:12:24 +0000720 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
Evan Chengee9e1b02008-09-12 18:13:14 +0000721 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +0000722 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
723 CopySrcSubIdx, CopyDstSubIdx) &&
Evan Cheng870e4be2008-09-17 18:36:25 +0000724 CopySrcReg != CopyDstReg &&
725 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
726 allocatableRegs_[CopyDstReg])) {
Evan Chengee9e1b02008-09-12 18:13:14 +0000727 LiveInterval &LI = li_->getInterval(CopyDstReg);
728 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
729 const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
Evan Cheng25f34a32008-09-15 06:28:41 +0000730 if (DLR->valno->def == DefIdx)
731 DLR->valno->copy = UseMI;
Evan Chengc8d044e2008-02-15 18:24:29 +0000732 }
733 }
734}
735
Evan Cheng7e073ba2008-04-09 20:57:25 +0000736/// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
737/// registers due to insert_subreg coalescing. e.g.
738/// r1024 = op
739/// r1025 = implicit_def
740/// r1025 = insert_subreg r1025, r1024
741/// = op r1025
742/// =>
743/// r1025 = op
744/// r1025 = implicit_def
745/// r1025 = insert_subreg r1025, r1025
746/// = op r1025
747void
748SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
749 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
750 E = mri_->reg_end(); I != E; ) {
751 MachineOperand &O = I.getOperand();
752 MachineInstr *DefMI = &*I;
753 ++I;
754 if (!O.isDef())
755 continue;
756 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
757 continue;
758 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
759 continue;
760 li_->RemoveMachineInstrFromMaps(DefMI);
761 DefMI->eraseFromParent();
762 }
763}
764
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000765/// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
766/// due to live range lengthening as the result of coalescing.
767void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
768 LiveInterval &LI) {
769 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
770 UE = mri_->use_end(); UI != UE; ++UI) {
771 MachineOperand &UseMO = UI.getOperand();
772 if (UseMO.isKill()) {
773 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000774 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
775 if (JoinedCopies.count(UseMI))
776 continue;
Evan Chengff7a3e52008-04-16 18:48:43 +0000777 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
Evan Cheng068b4ff2008-08-05 07:10:38 +0000778 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000779 UseMO.setIsKill(false);
780 }
781 }
782}
783
Evan Cheng3c88d742008-03-18 08:26:47 +0000784/// removeIntervalIfEmpty - Check if the live interval of a physical register
785/// is empty, if so remove it and also remove the empty intervals of its
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000786/// sub-registers. Return true if live interval is removed.
787static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
Evan Cheng3c88d742008-03-18 08:26:47 +0000788 const TargetRegisterInfo *tri_) {
789 if (li.empty()) {
Evan Cheng3c88d742008-03-18 08:26:47 +0000790 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
791 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
792 if (!li_->hasInterval(*SR))
793 continue;
794 LiveInterval &sli = li_->getInterval(*SR);
795 if (sli.empty())
796 li_->removeInterval(*SR);
797 }
Evan Chengd94950c2008-04-16 01:22:28 +0000798 li_->removeInterval(li.reg);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000799 return true;
Evan Cheng3c88d742008-03-18 08:26:47 +0000800 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000801 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000802}
803
804/// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000805/// Return true if live interval is removed.
806bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
Evan Chengecb2a8b2008-03-05 22:09:42 +0000807 MachineInstr *CopyMI) {
808 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
809 LiveInterval::iterator MLR =
810 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
Evan Cheng3c88d742008-03-18 08:26:47 +0000811 if (MLR == li.end())
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000812 return false; // Already removed by ShortenDeadCopySrcLiveRange.
Evan Chengecb2a8b2008-03-05 22:09:42 +0000813 unsigned RemoveStart = MLR->start;
814 unsigned RemoveEnd = MLR->end;
Evan Cheng3c88d742008-03-18 08:26:47 +0000815 // Remove the liverange that's defined by this.
816 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
817 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000818 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000819 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000820 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000821}
822
Evan Chengb3990d52008-10-27 23:21:01 +0000823/// RemoveDeadDef - If a def of a live interval is now determined dead, remove
824/// the val# it defines. If the live interval becomes empty, remove it as well.
825bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
826 MachineInstr *DefMI) {
827 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
828 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
829 if (DefIdx != MLR->valno->def)
830 return false;
831 li.removeValNo(MLR->valno);
832 return removeIntervalIfEmpty(li, li_, tri_);
833}
834
Evan Cheng0c284322008-03-26 20:15:49 +0000835/// PropagateDeadness - Propagate the dead marker to the instruction which
836/// defines the val#.
837static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
838 unsigned &LRStart, LiveIntervals *li_,
839 const TargetRegisterInfo* tri_) {
840 MachineInstr *DefMI =
841 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
842 if (DefMI && DefMI != CopyMI) {
843 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
844 if (DeadIdx != -1) {
845 DefMI->getOperand(DeadIdx).setIsDead();
846 // A dead def should have a single cycle interval.
847 ++LRStart;
848 }
849 }
850}
851
Bill Wendlingf2317782008-04-17 05:20:39 +0000852/// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
853/// extended by a dead copy. Mark the last use (if any) of the val# as kill as
854/// ends the live range there. If there isn't another use, then this live range
855/// is dead. Return true if live interval is removed.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000856bool
Evan Cheng3c88d742008-03-18 08:26:47 +0000857SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
858 MachineInstr *CopyMI) {
859 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
860 if (CopyIdx == 0) {
861 // FIXME: special case: function live in. It can be a general case if the
862 // first instruction index starts at > 0 value.
863 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
864 // Live-in to the function but dead. Remove it from entry live-in set.
Evan Chenga971dbd2008-04-24 09:06:33 +0000865 if (mf_->begin()->isLiveIn(li.reg))
866 mf_->begin()->removeLiveIn(li.reg);
Evan Chengff7a3e52008-04-16 18:48:43 +0000867 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000868 removeRange(li, LR->start, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000869 return removeIntervalIfEmpty(li, li_, tri_);
Evan Cheng3c88d742008-03-18 08:26:47 +0000870 }
871
872 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
873 if (LR == li.end())
874 // Livein but defined by a phi.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000875 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000876
877 unsigned RemoveStart = LR->start;
878 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
879 if (LR->end > RemoveEnd)
880 // More uses past this copy? Nothing to do.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000881 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000882
Evan Cheng961154f2009-02-05 08:45:04 +0000883 // If there is a last use in the same bb, we can't remove the live range.
884 // Shorten the live interval and return.
Evan Cheng190424e2009-02-09 08:37:45 +0000885 MachineBasicBlock *CopyMBB = CopyMI->getParent();
886 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000887 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000888
Evan Cheng190424e2009-02-09 08:37:45 +0000889 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
890 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
891 // If the live range starts in another mbb and the copy mbb is not a fall
892 // through mbb, then we can only cut the range from the beginning of the
893 // copy mbb.
894 RemoveStart = li_->getMBBStartIdx(CopyMBB) + 1;
895
Evan Cheng77fde2c2009-02-08 07:48:37 +0000896 if (LR->valno->def == RemoveStart) {
897 // If the def MI defines the val# and this copy is the only kill of the
898 // val#, then propagate the dead marker.
Evan Cheng190424e2009-02-09 08:37:45 +0000899 if (li.isOnlyLROfValNo(LR)) {
Evan Cheng77fde2c2009-02-08 07:48:37 +0000900 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
901 ++numDeadValNo;
Evan Chengf18134a2009-02-08 08:00:36 +0000902 }
Evan Cheng190424e2009-02-09 08:37:45 +0000903 if (li.isKill(LR->valno, RemoveEnd))
904 li.removeKill(LR->valno, RemoveEnd);
Evan Cheng77fde2c2009-02-08 07:48:37 +0000905 }
Evan Cheng0c284322008-03-26 20:15:49 +0000906
Evan Cheng190424e2009-02-09 08:37:45 +0000907 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000908 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000909}
910
Evan Cheng7e073ba2008-04-09 20:57:25 +0000911/// CanCoalesceWithImpDef - Returns true if the specified copy instruction
912/// from an implicit def to another register can be coalesced away.
913bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
914 LiveInterval &li,
915 LiveInterval &ImpLi) const{
916 if (!CopyMI->killsRegister(ImpLi.reg))
917 return false;
918 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
919 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
920 if (LR == li.end())
921 return false;
922 if (LR->valno->hasPHIKill)
923 return false;
924 if (LR->valno->def != CopyIdx)
925 return false;
926 // Make sure all of val# uses are copies.
927 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
928 UE = mri_->use_end(); UI != UE;) {
929 MachineInstr *UseMI = &*UI;
930 ++UI;
931 if (JoinedCopies.count(UseMI))
932 continue;
933 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
934 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000935 if (ULR == li.end() || ULR->valno != LR->valno)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000936 continue;
937 // If the use is not a use, then it's not safe to coalesce the move.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000938 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
939 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +0000940 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
941 UseMI->getOperand(1).getReg() == li.reg)
942 continue;
943 return false;
944 }
945 }
946 return true;
947}
948
949
950/// RemoveCopiesFromValNo - The specified value# is defined by an implicit
951/// def and it is being removed. Turn all copies from this value# into
952/// identity copies so they will be removed.
953void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
954 VNInfo *VNI) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000955 SmallVector<MachineInstr*, 4> ImpDefs;
Evan Chengd2012d02008-04-10 23:48:35 +0000956 MachineOperand *LastUse = NULL;
957 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
958 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
959 RE = mri_->reg_end(); RI != RE;) {
960 MachineOperand *MO = &RI.getOperand();
961 MachineInstr *MI = &*RI;
962 ++RI;
963 if (MO->isDef()) {
964 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000965 ImpDefs.push_back(MI);
Evan Chengd2012d02008-04-10 23:48:35 +0000966 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000967 continue;
Evan Chengd2012d02008-04-10 23:48:35 +0000968 }
969 if (JoinedCopies.count(MI))
970 continue;
971 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
Evan Cheng7e073ba2008-04-09 20:57:25 +0000972 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000973 if (ULR == li.end() || ULR->valno != VNI)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000974 continue;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000975 // If the use is a copy, turn it into an identity copy.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000976 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
977 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
978 SrcReg == li.reg) {
Evan Chengd2012d02008-04-10 23:48:35 +0000979 // Each use MI may have multiple uses of this register. Change them all.
980 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
981 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000982 if (MO.isReg() && MO.getReg() == li.reg)
Evan Chengd2012d02008-04-10 23:48:35 +0000983 MO.setReg(DstReg);
984 }
985 JoinedCopies.insert(MI);
986 } else if (UseIdx > LastUseIdx) {
987 LastUseIdx = UseIdx;
988 LastUse = MO;
Evan Cheng172b70c2008-04-10 18:38:47 +0000989 }
Evan Chengd2012d02008-04-10 23:48:35 +0000990 }
Evan Cheng58207f12009-02-22 08:35:56 +0000991 if (LastUse) {
Evan Chengd2012d02008-04-10 23:48:35 +0000992 LastUse->setIsKill();
Evan Cheng58207f12009-02-22 08:35:56 +0000993 li.addKill(VNI, LastUseIdx+1);
994 } else {
Evan Chengd77d4f92008-05-28 17:40:10 +0000995 // Remove dead implicit_def's.
996 while (!ImpDefs.empty()) {
997 MachineInstr *ImpDef = ImpDefs.back();
998 ImpDefs.pop_back();
999 li_->RemoveMachineInstrFromMaps(ImpDef);
1000 ImpDef->eraseFromParent();
1001 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001002 }
1003}
1004
Evan Cheng8db86682008-09-11 20:07:10 +00001005/// getMatchingSuperReg - Return a super-register of the specified register
1006/// Reg so its sub-register of index SubIdx is Reg.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001007static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
1008 const TargetRegisterClass *RC,
1009 const TargetRegisterInfo* TRI) {
1010 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
1011 unsigned SR = *SRs; ++SRs)
1012 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
1013 return SR;
1014 return 0;
1015}
1016
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001017/// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1018/// two virtual registers from different register classes.
Evan Chenge00f5de2008-06-19 01:39:21 +00001019bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001020SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1021 unsigned SmallReg,
1022 unsigned Threshold) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001023 // Then make sure the intervals are *short*.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001024 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1025 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1026 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1027 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1028 if (SmallSize > Threshold || LargeSize > Threshold)
1029 if ((float)std::distance(mri_->use_begin(SmallReg),
1030 mri_->use_end()) / SmallSize <
1031 (float)std::distance(mri_->use_begin(LargeReg),
1032 mri_->use_end()) / LargeSize)
1033 return false;
1034 return true;
Evan Chenge00f5de2008-06-19 01:39:21 +00001035}
1036
Evan Cheng8db86682008-09-11 20:07:10 +00001037/// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1038/// register with a physical register, check if any of the virtual register
1039/// operand is a sub-register use or def. If so, make sure it won't result
1040/// in an illegal extract_subreg or insert_subreg instruction. e.g.
1041/// vr1024 = extract_subreg vr1025, 1
1042/// ...
1043/// vr1024 = mov8rr AH
1044/// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1045/// AH does not have a super-reg whose sub-register 1 is AH.
1046bool
1047SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1048 unsigned VirtReg,
1049 unsigned PhysReg) {
1050 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1051 E = mri_->reg_end(); I != E; ++I) {
1052 MachineOperand &O = I.getOperand();
1053 MachineInstr *MI = &*I;
1054 if (MI == CopyMI || JoinedCopies.count(MI))
1055 continue;
1056 unsigned SubIdx = O.getSubReg();
1057 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1058 return true;
1059 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1060 SubIdx = MI->getOperand(2).getImm();
1061 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1062 return true;
1063 if (O.isDef()) {
1064 unsigned SrcReg = MI->getOperand(1).getReg();
1065 const TargetRegisterClass *RC =
1066 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1067 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1068 : mri_->getRegClass(SrcReg);
1069 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1070 return true;
1071 }
1072 }
Dan Gohman97121ba2009-04-08 00:15:30 +00001073 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1074 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
Evan Cheng8db86682008-09-11 20:07:10 +00001075 SubIdx = MI->getOperand(3).getImm();
1076 if (VirtReg == MI->getOperand(0).getReg()) {
1077 if (!tri_->getSubReg(PhysReg, SubIdx))
1078 return true;
1079 } else {
1080 unsigned DstReg = MI->getOperand(0).getReg();
1081 const TargetRegisterClass *RC =
1082 TargetRegisterInfo::isPhysicalRegister(DstReg)
1083 ? tri_->getPhysicalRegisterRegClass(DstReg)
1084 : mri_->getRegClass(DstReg);
1085 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1086 return true;
1087 }
1088 }
1089 }
1090 return false;
1091}
1092
Evan Chenge00f5de2008-06-19 01:39:21 +00001093
Evan Chenge08eb9c2009-01-20 06:44:16 +00001094/// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1095/// an extract_subreg where dst is a physical register, e.g.
1096/// cl = EXTRACT_SUBREG reg1024, 1
1097bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001098SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1099 unsigned SrcReg, unsigned SubIdx,
1100 unsigned &RealDstReg) {
Evan Chenge08eb9c2009-01-20 06:44:16 +00001101 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1102 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1103 assert(RealDstReg && "Invalid extract_subreg instruction!");
1104
1105 // For this type of EXTRACT_SUBREG, conservatively
1106 // check if the live interval of the source register interfere with the
1107 // actual super physical register we are trying to coalesce with.
1108 LiveInterval &RHS = li_->getInterval(SrcReg);
1109 if (li_->hasInterval(RealDstReg) &&
1110 RHS.overlaps(li_->getInterval(RealDstReg))) {
1111 DOUT << "Interfere with register ";
1112 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
1113 return false; // Not coalescable
1114 }
1115 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1116 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1117 DOUT << "Interfere with sub-register ";
1118 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1119 return false; // Not coalescable
1120 }
1121 return true;
1122}
1123
1124/// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1125/// an insert_subreg where src is a physical register, e.g.
1126/// reg1024 = INSERT_SUBREG reg1024, c1, 0
1127bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001128SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1129 unsigned SrcReg, unsigned SubIdx,
1130 unsigned &RealSrcReg) {
Evan Chenge08eb9c2009-01-20 06:44:16 +00001131 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1132 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1133 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1134
1135 LiveInterval &RHS = li_->getInterval(DstReg);
1136 if (li_->hasInterval(RealSrcReg) &&
1137 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1138 DOUT << "Interfere with register ";
1139 DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_));
1140 return false; // Not coalescable
1141 }
1142 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1143 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1144 DOUT << "Interfere with sub-register ";
1145 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1146 return false; // Not coalescable
1147 }
1148 return true;
1149}
1150
David Greene25133302007-06-08 17:18:56 +00001151/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1152/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +00001153/// if the copy was successfully coalesced away. If it is not currently
1154/// possible to coalesce this interval, but it may be possible if other
1155/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng70071432008-02-13 03:01:43 +00001156bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001157 MachineInstr *CopyMI = TheCopy.MI;
1158
1159 Again = false;
Evan Chengcd047082008-08-30 09:09:33 +00001160 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
Evan Cheng8fc9a102007-11-06 08:52:21 +00001161 return false; // Already done.
1162
David Greene25133302007-06-08 17:18:56 +00001163 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1164
Evan Cheng04ee5a12009-01-20 19:12:24 +00001165 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Chengc8d044e2008-02-15 18:24:29 +00001166 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001167 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
Dan Gohman97121ba2009-04-08 00:15:30 +00001168 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
Evan Chengc8d044e2008-02-15 18:24:29 +00001169 unsigned SubIdx = 0;
1170 if (isExtSubReg) {
1171 DstReg = CopyMI->getOperand(0).getReg();
1172 SrcReg = CopyMI->getOperand(1).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +00001173 } else if (isInsSubReg || isSubRegToReg) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001174 if (CopyMI->getOperand(2).getSubReg()) {
1175 DOUT << "\tSource of insert_subreg is already coalesced "
1176 << "to another register.\n";
1177 return false; // Not coalescable.
1178 }
1179 DstReg = CopyMI->getOperand(0).getReg();
1180 SrcReg = CopyMI->getOperand(2).getReg();
Evan Cheng04ee5a12009-01-20 19:12:24 +00001181 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
Evan Chengc8d044e2008-02-15 18:24:29 +00001182 assert(0 && "Unrecognized copy instruction!");
1183 return false;
Evan Cheng70071432008-02-13 03:01:43 +00001184 }
1185
David Greene25133302007-06-08 17:18:56 +00001186 // If they are already joined we continue.
Evan Chengc8d044e2008-02-15 18:24:29 +00001187 if (SrcReg == DstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001188 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001189 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001190 }
1191
Evan Chengc8d044e2008-02-15 18:24:29 +00001192 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1193 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
David Greene25133302007-06-08 17:18:56 +00001194
1195 // If they are both physical registers, we cannot join them.
1196 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001197 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001198 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001199 }
1200
1201 // We only join virtual registers with allocatable physical registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001202 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
David Greene25133302007-06-08 17:18:56 +00001203 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001204 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001205 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001206 if (DstIsPhys && !allocatableRegs_[DstReg]) {
David Greene25133302007-06-08 17:18:56 +00001207 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001208 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001209 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001210
Evan Chenge00f5de2008-06-19 01:39:21 +00001211 // Should be non-null only when coalescing to a sub-register class.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001212 bool CrossRC = false;
1213 const TargetRegisterClass *NewRC = NULL;
Evan Chenge00f5de2008-06-19 01:39:21 +00001214 MachineBasicBlock *CopyMBB = CopyMI->getParent();
Evan Cheng32dfbea2007-10-12 08:50:34 +00001215 unsigned RealDstReg = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001216 unsigned RealSrcReg = 0;
Dan Gohman97121ba2009-04-08 00:15:30 +00001217 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001218 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1219 if (SrcIsPhys && isExtSubReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001220 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1221 // coalesced with AX.
Evan Cheng621d1572008-04-17 00:06:42 +00001222 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001223 if (DstSubIdx) {
1224 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1225 // coalesced to a larger register so the subreg indices cancel out.
1226 if (DstSubIdx != SubIdx) {
1227 DOUT << "\t Sub-register indices mismatch.\n";
1228 return false; // Not coalescable.
1229 }
1230 } else
Evan Cheng621d1572008-04-17 00:06:42 +00001231 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +00001232 SubIdx = 0;
Dan Gohman97121ba2009-04-08 00:15:30 +00001233 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001234 // EAX = INSERT_SUBREG EAX, r1024, 0
Evan Cheng621d1572008-04-17 00:06:42 +00001235 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001236 if (SrcSubIdx) {
1237 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1238 // coalesced to a larger register so the subreg indices cancel out.
1239 if (SrcSubIdx != SubIdx) {
1240 DOUT << "\t Sub-register indices mismatch.\n";
1241 return false; // Not coalescable.
1242 }
1243 } else
1244 DstReg = tri_->getSubReg(DstReg, SubIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001245 SubIdx = 0;
Dan Gohman97121ba2009-04-08 00:15:30 +00001246 } else if ((DstIsPhys && isExtSubReg) ||
1247 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1248 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001249 DOUT << "\tSrc of extract_subreg already coalesced with reg"
1250 << " of a super-class.\n";
1251 return false; // Not coalescable.
1252 }
1253
Evan Cheng7e073ba2008-04-09 20:57:25 +00001254 if (isExtSubReg) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001255 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
Evan Cheng0547bab2007-11-01 06:22:48 +00001256 return false; // Not coalescable
Evan Chenge08eb9c2009-01-20 06:44:16 +00001257 } else {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001258 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
Evan Chenge08eb9c2009-01-20 06:44:16 +00001259 return false; // Not coalescable
1260 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001261 SubIdx = 0;
Evan Cheng0547bab2007-11-01 06:22:48 +00001262 } else {
Evan Cheng639f4932008-04-17 07:58:04 +00001263 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1264 : CopyMI->getOperand(2).getSubReg();
1265 if (OldSubIdx) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001266 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
Evan Cheng639f4932008-04-17 07:58:04 +00001267 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1268 // coalesced to a larger register so the subreg indices cancel out.
Evan Cheng8509fcf2008-04-29 01:41:44 +00001269 // Also check if the other larger register is of the same register
1270 // class as the would be resulting register.
Evan Cheng639f4932008-04-17 07:58:04 +00001271 SubIdx = 0;
1272 else {
1273 DOUT << "\t Sub-register indices mismatch.\n";
1274 return false; // Not coalescable.
1275 }
1276 }
1277 if (SubIdx) {
1278 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1279 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001280 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1281 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1282 Again = true; // May be possible to coalesce later.
1283 return false;
Evan Cheng0547bab2007-11-01 06:22:48 +00001284 }
1285 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001286 }
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001287 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1288 if (!CrossClassJoin)
1289 return false;
1290 CrossRC = true;
1291
1292 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
Evan Chengc8d044e2008-02-15 18:24:29 +00001293 // with another? If it's the resulting destination register, then
1294 // the subidx must be propagated to uses (but only those defined
1295 // by the EXTRACT_SUBREG). If it's being coalesced into another
1296 // register, it should be safe because register is assumed to have
1297 // the register class of the super-register.
1298
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001299 // Process moves where one of the registers have a sub-register index.
1300 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001301 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
Dan Gohman97121ba2009-04-08 00:15:30 +00001302 SubIdx = DstMO->getSubReg();
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001303 if (SubIdx) {
Dan Gohman97121ba2009-04-08 00:15:30 +00001304 if (SrcMO->getSubReg())
1305 // FIXME: can we handle this?
1306 return false;
1307 // This is not an insert_subreg but it looks like one.
1308 // e.g. %reg1024:3 = MOV32rr %EAX
1309 isInsSubReg = true;
1310 if (SrcIsPhys) {
1311 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001312 return false; // Not coalescable
1313 SubIdx = 0;
1314 }
Dan Gohman97121ba2009-04-08 00:15:30 +00001315 } else {
1316 SubIdx = SrcMO->getSubReg();
1317 if (SubIdx) {
1318 // This is not a extract_subreg but it looks like one.
1319 // e.g. %cl = MOV16rr %reg1024:2
1320 isExtSubReg = true;
1321 if (DstIsPhys) {
1322 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1323 return false; // Not coalescable
1324 SubIdx = 0;
1325 }
1326 }
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001327 }
1328
1329 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1330 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1331 unsigned LargeReg = SrcReg;
1332 unsigned SmallReg = DstReg;
1333 unsigned Limit = 0;
1334
1335 // Now determine the register class of the joined register.
1336 if (isExtSubReg) {
1337 if (SubIdx && DstRC && DstRC->isASubClass()) {
1338 // This is a move to a sub-register class. However, the source is a
1339 // sub-register of a larger register class. We don't know what should
1340 // the register class be. FIXME.
1341 Again = true;
1342 return false;
1343 }
1344 Limit = allocatableRCRegs_[DstRC].count();
1345 } else if (!SrcIsPhys && !SrcIsPhys) {
1346 unsigned SrcSize = SrcRC->getSize();
1347 unsigned DstSize = DstRC->getSize();
1348 if (SrcSize < DstSize)
1349 // For example X86::MOVSD2PDrr copies from FR64 to VR128.
1350 NewRC = DstRC;
1351 else if (DstSize > SrcSize) {
1352 NewRC = SrcRC;
1353 std::swap(LargeReg, SmallReg);
1354 } else {
1355 unsigned SrcNumRegs = SrcRC->getNumRegs();
1356 unsigned DstNumRegs = DstRC->getNumRegs();
1357 if (DstNumRegs < SrcNumRegs)
1358 // Sub-register class?
1359 NewRC = DstRC;
1360 else if (SrcNumRegs < DstNumRegs) {
1361 NewRC = SrcRC;
1362 std::swap(LargeReg, SmallReg);
1363 } else
1364 // No idea what's the right register class to use.
1365 return false;
1366 }
1367 }
1368
Evan Chengc16d37e2009-01-23 05:48:59 +00001369 // If we are joining two virtual registers and the resulting register
1370 // class is more restrictive (fewer register, smaller size). Check if it's
1371 // worth doing the merge.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001372 if (!SrcIsPhys && !DstIsPhys &&
Evan Chengc16d37e2009-01-23 05:48:59 +00001373 (isExtSubReg || DstRC->isASubClass()) &&
1374 !isWinToJoinCrossClass(LargeReg, SmallReg,
1375 allocatableRCRegs_[NewRC].count())) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001376 DOUT << "\tSrc/Dest are different register classes.\n";
1377 // Allow the coalescer to try again in case either side gets coalesced to
1378 // a physical register that's compatible with the other side. e.g.
1379 // r1024 = MOV32to32_ r1025
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001380 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
Evan Chenge00f5de2008-06-19 01:39:21 +00001381 Again = true; // May be possible to coalesce later.
1382 return false;
1383 }
David Greene25133302007-06-08 17:18:56 +00001384 }
Evan Cheng8db86682008-09-11 20:07:10 +00001385
1386 // Will it create illegal extract_subreg / insert_subreg?
1387 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1388 return false;
1389 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1390 return false;
David Greene25133302007-06-08 17:18:56 +00001391
Evan Chengc8d044e2008-02-15 18:24:29 +00001392 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1393 LiveInterval &DstInt = li_->getInterval(DstReg);
1394 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
David Greene25133302007-06-08 17:18:56 +00001395 "Register mapping is horribly broken!");
1396
Dan Gohman6f0d0242008-02-10 18:45:23 +00001397 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1398 DOUT << " and "; DstInt.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00001399 DOUT << ": ";
1400
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001401 // Save a copy of the virtual register live interval. We'll manually
1402 // merge this into the "real" physical register live interval this is
1403 // coalesced with.
1404 LiveInterval *SavedLI = 0;
1405 if (RealDstReg)
1406 SavedLI = li_->dupInterval(&SrcInt);
1407 else if (RealSrcReg)
1408 SavedLI = li_->dupInterval(&DstInt);
1409
Evan Cheng3c88d742008-03-18 08:26:47 +00001410 // Check if it is necessary to propagate "isDead" property.
Dan Gohman97121ba2009-04-08 00:15:30 +00001411 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001412 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1413 bool isDead = mopd->isDead();
David Greene25133302007-06-08 17:18:56 +00001414
Evan Cheng7e073ba2008-04-09 20:57:25 +00001415 // We need to be careful about coalescing a source physical register with a
1416 // virtual register. Once the coalescing is done, it cannot be broken and
1417 // these are not spillable! If the destination interval uses are far away,
1418 // think twice about coalescing them!
1419 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1420 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1421 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1422 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1423 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1424 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1425 if (TheCopy.isBackEdge)
1426 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +00001427
Evan Cheng7e073ba2008-04-09 20:57:25 +00001428 // If the virtual register live interval is long but it has low use desity,
1429 // do not join them, instead mark the physical register as its allocation
1430 // preference.
Owen Andersona1566f22008-07-22 22:46:49 +00001431 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001432 if (Length > Threshold &&
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001433 (((float)std::distance(mri_->use_begin(JoinVReg), mri_->use_end())
1434 / Length) < (1.0 / Threshold))) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001435 JoinVInt.preference = JoinPReg;
1436 ++numAborts;
1437 DOUT << "\tMay tie down a physical register, abort!\n";
1438 Again = true; // May be possible to coalesce later.
1439 return false;
1440 }
David Greene25133302007-06-08 17:18:56 +00001441 }
1442 }
1443
1444 // Okay, attempt to join these two intervals. On failure, this returns false.
1445 // Otherwise, if one of the intervals being joined is a physreg, this method
1446 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1447 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001448 bool Swapped = false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00001449 // If SrcInt is implicitly defined, it's safe to coalesce.
1450 bool isEmpty = SrcInt.empty();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001451 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
Evan Chengdb9b1c32008-04-03 16:41:54 +00001452 // Only coalesce an empty interval (defined by implicit_def) with
Evan Cheng7e073ba2008-04-09 20:57:25 +00001453 // another interval which has a valno defined by the CopyMI and the CopyMI
1454 // is a kill of the implicit def.
Evan Chengdb9b1c32008-04-03 16:41:54 +00001455 DOUT << "Not profitable!\n";
1456 return false;
1457 }
1458
1459 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001460 // Coalescing failed.
Evan Chengcd047082008-08-30 09:09:33 +00001461
1462 // If definition of source is defined by trivial computation, try
1463 // rematerializing it.
Dan Gohman97121ba2009-04-08 00:15:30 +00001464 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
Evan Chengcd047082008-08-30 09:09:33 +00001465 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1466 return true;
David Greene25133302007-06-08 17:18:56 +00001467
1468 // If we can eliminate the copy without merging the live ranges, do so now.
Dan Gohman97121ba2009-04-08 00:15:30 +00001469 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
Evan Cheng70071432008-02-13 03:01:43 +00001470 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1471 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001472 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +00001473 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001474 }
Evan Cheng70071432008-02-13 03:01:43 +00001475
David Greene25133302007-06-08 17:18:56 +00001476 // Otherwise, we are unable to join the intervals.
1477 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001478 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +00001479 return false;
1480 }
1481
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001482 LiveInterval *ResSrcInt = &SrcInt;
1483 LiveInterval *ResDstInt = &DstInt;
1484 if (Swapped) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001485 std::swap(SrcReg, DstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001486 std::swap(ResSrcInt, ResDstInt);
1487 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001488 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
David Greene25133302007-06-08 17:18:56 +00001489 "LiveInterval::join didn't work right!");
1490
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001491 // If we're about to merge live ranges into a physical register live interval,
David Greene25133302007-06-08 17:18:56 +00001492 // we have to update any aliased register's live ranges to indicate that they
1493 // have clobbered values for this range.
Evan Chengc8d044e2008-02-15 18:24:29 +00001494 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001495 // If this is a extract_subreg where dst is a physical register, e.g.
1496 // cl = EXTRACT_SUBREG reg1024, 1
1497 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001498 if (RealDstReg || RealSrcReg) {
1499 LiveInterval &RealInt =
1500 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001501 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1502 E = SavedLI->vni_end(); I != E; ++I) {
1503 const VNInfo *ValNo = *I;
1504 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->copy,
1505 li_->getVNInfoAllocator());
1506 NewValNo->hasPHIKill = ValNo->hasPHIKill;
1507 NewValNo->redefByEC = ValNo->redefByEC;
1508 RealInt.addKills(NewValNo, ValNo->kills);
1509 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
Evan Cheng34729252007-10-14 10:08:34 +00001510 }
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001511 RealInt.weight += SavedLI->weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001512 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001513 }
1514
David Greene25133302007-06-08 17:18:56 +00001515 // Update the liveintervals of sub-registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001516 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +00001517 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +00001518 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +00001519 }
1520
Evan Chengc8d044e2008-02-15 18:24:29 +00001521 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1522 // larger super-register.
Dan Gohman97121ba2009-04-08 00:15:30 +00001523 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1524 !SrcIsPhys && !DstIsPhys) {
1525 if ((isExtSubReg && !Swapped) ||
1526 ((isInsSubReg || isSubRegToReg) && Swapped)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001527 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
Evan Chengc8d044e2008-02-15 18:24:29 +00001528 std::swap(SrcReg, DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +00001529 std::swap(ResSrcInt, ResDstInt);
1530 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001531 }
1532
Evan Chenge00f5de2008-06-19 01:39:21 +00001533 // Coalescing to a virtual register that is of a sub-register class of the
1534 // other. Make sure the resulting register is set to the right register class.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001535 if (CrossRC) {
1536 ++numCrossRCs;
1537 if (NewRC)
1538 mri_->setRegClass(DstReg, NewRC);
Evan Chenge00f5de2008-06-19 01:39:21 +00001539 }
1540
Evan Cheng8fc9a102007-11-06 08:52:21 +00001541 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001542 // Add all copies that define val# in the source interval into the queue.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001543 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1544 e = ResSrcInt->vni_end(); i != e; ++i) {
1545 const VNInfo *vni = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001546 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1547 continue;
1548 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +00001549 unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
Evan Chengc8d044e2008-02-15 18:24:29 +00001550 if (CopyMI &&
1551 JoinedCopies.count(CopyMI) == 0 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +00001552 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1553 NewSrcSubIdx, NewDstSubIdx)) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001554 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
Evan Chengc8d044e2008-02-15 18:24:29 +00001555 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1556 isBackEdgeCopy(CopyMI, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001557 }
1558 }
1559 }
1560
Evan Chengc8d044e2008-02-15 18:24:29 +00001561 // Remember to delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001562 JoinedCopies.insert(CopyMI);
Evan Chengc8d044e2008-02-15 18:24:29 +00001563
Evan Cheng4ff3f1c2008-03-10 08:11:32 +00001564 // Some live range has been lengthened due to colaescing, eliminate the
1565 // unnecessary kills.
1566 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1567 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1568 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1569
Evan Cheng7e073ba2008-04-09 20:57:25 +00001570 if (isInsSubReg)
1571 // Avoid:
1572 // r1024 = op
1573 // r1024 = implicit_def
1574 // ...
1575 // = r1024
1576 RemoveDeadImpDef(DstReg, *ResDstInt);
Evan Chengc8d044e2008-02-15 18:24:29 +00001577 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1578
Evan Chengcd047082008-08-30 09:09:33 +00001579 // SrcReg is guarateed to be the register whose live interval that is
1580 // being merged.
1581 li_->removeInterval(SrcReg);
1582
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001583 // Manually deleted the live interval copy.
1584 if (SavedLI) {
1585 SavedLI->clear();
1586 delete SavedLI;
1587 }
1588
Evan Chengdb9b1c32008-04-03 16:41:54 +00001589 if (isEmpty) {
1590 // Now the copy is being coalesced away, the val# previously defined
1591 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1592 // length interval. Remove the val#.
1593 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
Evan Chengff7a3e52008-04-16 18:48:43 +00001594 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001595 VNInfo *ImpVal = LR->valno;
1596 assert(ImpVal->def == CopyIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001597 unsigned NextDef = LR->end;
1598 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001599 ResDstInt->removeValNo(ImpVal);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001600 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1601 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1602 // Special case: vr1024 = implicit_def
1603 // vr1024 = insert_subreg vr1024, vr1025, c
1604 // The insert_subreg becomes a "copy" that defines a val# which can itself
1605 // be coalesced away.
1606 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1607 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1608 LR->valno->copy = DefMI;
1609 }
Evan Chengdb9b1c32008-04-03 16:41:54 +00001610 }
1611
Evan Cheng3ef2d602008-09-09 21:44:23 +00001612 // If resulting interval has a preference that no longer fits because of subreg
1613 // coalescing, just clear the preference.
Dan Gohman97121ba2009-04-08 00:15:30 +00001614 if (ResDstInt->preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
Evan Cheng40869062008-09-11 18:40:32 +00001615 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
Evan Cheng3ef2d602008-09-09 21:44:23 +00001616 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1617 if (!RC->contains(ResDstInt->preference))
1618 ResDstInt->preference = 0;
1619 }
1620
Evan Chengdb9b1c32008-04-03 16:41:54 +00001621 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1622 DOUT << "\n";
1623
David Greene25133302007-06-08 17:18:56 +00001624 ++numJoins;
1625 return true;
1626}
1627
1628/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1629/// compute what the resultant value numbers for each value in the input two
1630/// ranges will be. This is complicated by copies between the two which can
1631/// and will commonly cause multiple value numbers to be merged into one.
1632///
1633/// VN is the value number that we're trying to resolve. InstDefiningValue
1634/// keeps track of the new InstDefiningValue assignment for the result
1635/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1636/// whether a value in this or other is a copy from the opposite set.
1637/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1638/// already been assigned.
1639///
1640/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1641/// contains the value number the copy is from.
1642///
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001643static unsigned ComputeUltimateVN(VNInfo *VNI,
1644 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +00001645 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1646 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +00001647 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001648 SmallVector<int, 16> &OtherValNoAssignments) {
1649 unsigned VN = VNI->id;
1650
David Greene25133302007-06-08 17:18:56 +00001651 // If the VN has already been computed, just return it.
1652 if (ThisValNoAssignments[VN] >= 0)
1653 return ThisValNoAssignments[VN];
1654// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001655
David Greene25133302007-06-08 17:18:56 +00001656 // If this val is not a copy from the other val, then it must be a new value
1657 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +00001658 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +00001659 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001660 NewVNInfo.push_back(VNI);
1661 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001662 }
Evan Chengc14b1442007-08-31 08:04:17 +00001663 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +00001664
1665 // Otherwise, this *is* a copy from the RHS. If the other side has already
1666 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001667 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1668 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +00001669
1670 // Mark this value number as currently being computed, then ask what the
1671 // ultimate value # of the other value is.
1672 ThisValNoAssignments[VN] = -2;
1673 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001674 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1675 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001676 return ThisValNoAssignments[VN] = UltimateVN;
1677}
1678
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001679static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +00001680 return std::find(V.begin(), V.end(), Val) != V.end();
1681}
1682
Evan Cheng7e073ba2008-04-09 20:57:25 +00001683/// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1684/// the specified live interval is defined by a copy from the specified
1685/// register.
1686bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1687 LiveRange *LR,
1688 unsigned Reg) {
1689 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1690 if (SrcReg == Reg)
1691 return true;
1692 if (LR->valno->def == ~0U &&
1693 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1694 *tri_->getSuperRegisters(li.reg)) {
1695 // It's a sub-register live interval, we may not have precise information.
1696 // Re-compute it.
1697 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
Evan Cheng04ee5a12009-01-20 19:12:24 +00001698 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1699 if (DefMI &&
1700 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
Evan Cheng7e073ba2008-04-09 20:57:25 +00001701 DstReg == li.reg && SrcReg == Reg) {
1702 // Cache computed info.
1703 LR->valno->def = LR->start;
1704 LR->valno->copy = DefMI;
1705 return true;
1706 }
1707 }
1708 return false;
1709}
1710
David Greene25133302007-06-08 17:18:56 +00001711/// SimpleJoin - Attempt to joint the specified interval into this one. The
1712/// caller of this method must guarantee that the RHS only contains a single
1713/// value number and that the RHS is not defined by a copy from this
1714/// interval. This returns false if the intervals are not joinable, or it
1715/// joins them and returns true.
Bill Wendling2674d712008-01-04 08:59:18 +00001716bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
David Greene25133302007-06-08 17:18:56 +00001717 assert(RHS.containsOneValue());
1718
1719 // Some number (potentially more than one) value numbers in the current
1720 // interval may be defined as copies from the RHS. Scan the overlapping
1721 // portions of the LHS and RHS, keeping track of this and looking for
1722 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001723 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +00001724
1725 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1726 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1727
1728 if (LHSIt->start < RHSIt->start) {
1729 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1730 if (LHSIt != LHS.begin()) --LHSIt;
1731 } else if (RHSIt->start < LHSIt->start) {
1732 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1733 if (RHSIt != RHS.begin()) --RHSIt;
1734 }
1735
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001736 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +00001737
1738 while (1) {
1739 // Determine if these live intervals overlap.
1740 bool Overlaps = false;
1741 if (LHSIt->start <= RHSIt->start)
1742 Overlaps = LHSIt->end > RHSIt->start;
1743 else
1744 Overlaps = RHSIt->end > LHSIt->start;
1745
1746 // If the live intervals overlap, there are two interesting cases: if the
1747 // LHS interval is defined by a copy from the RHS, it's ok and we record
1748 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +00001749 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +00001750 if (Overlaps) {
1751 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001752 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001753 // Copy from the RHS?
Evan Cheng7e073ba2008-04-09 20:57:25 +00001754 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
David Greene25133302007-06-08 17:18:56 +00001755 return false; // Nope, bail out.
Evan Chengf4ea5102008-05-21 22:34:12 +00001756
1757 if (LHSIt->contains(RHSIt->valno->def))
1758 // Here is an interesting situation:
1759 // BB1:
1760 // vr1025 = copy vr1024
1761 // ..
1762 // BB2:
1763 // vr1024 = op
1764 // = vr1025
1765 // Even though vr1025 is copied from vr1024, it's not safe to
Bill Wendling430d4232009-03-30 20:30:02 +00001766 // coalesce them since the live range of vr1025 intersects the
Evan Chengf4ea5102008-05-21 22:34:12 +00001767 // def of vr1024. This happens because vr1025 is assigned the
1768 // value of the previous iteration of vr1024.
1769 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001770 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001771 }
1772
1773 // We know this entire LHS live range is okay, so skip it now.
1774 if (++LHSIt == LHSEnd) break;
1775 continue;
1776 }
1777
1778 if (LHSIt->end < RHSIt->end) {
1779 if (++LHSIt == LHSEnd) break;
1780 } else {
1781 // One interesting case to check here. It's possible that we have
1782 // something like "X3 = Y" which defines a new value number in the LHS,
1783 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001784 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +00001785 // the live ranges don't actually overlap.
1786 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001787 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001788 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +00001789 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +00001790 if (++LHSIt == LHSEnd) break;
1791 } else {
1792 // Otherwise, if this is a copy from the RHS, mark it as being merged
1793 // in.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001794 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
Evan Chengf4ea5102008-05-21 22:34:12 +00001795 if (LHSIt->contains(RHSIt->valno->def))
1796 // Here is an interesting situation:
1797 // BB1:
1798 // vr1025 = copy vr1024
1799 // ..
1800 // BB2:
1801 // vr1024 = op
1802 // = vr1025
1803 // Even though vr1025 is copied from vr1024, it's not safe to
1804 // coalesced them since live range of vr1025 intersects the
1805 // def of vr1024. This happens because vr1025 is assigned the
1806 // value of the previous iteration of vr1024.
1807 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001808 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001809
1810 // We know this entire LHS live range is okay, so skip it now.
1811 if (++LHSIt == LHSEnd) break;
1812 }
1813 }
1814 }
1815
1816 if (++RHSIt == RHSEnd) break;
1817 }
1818 }
1819
Gabor Greife510b3a2007-07-09 12:00:59 +00001820 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +00001821 // the value numbers in EliminatedLHSVals will all be merged together. Since
1822 // the most common case is that EliminatedLHSVals has a single number, we
1823 // optimize for it: if there is more than one value, we merge them all into
1824 // the lowest numbered one, then handle the interval as if we were merging
1825 // with one value number.
Devang Patel8a84e442009-01-05 17:31:22 +00001826 VNInfo *LHSValNo = NULL;
David Greene25133302007-06-08 17:18:56 +00001827 if (EliminatedLHSVals.size() > 1) {
1828 // Loop through all the equal value numbers merging them into the smallest
1829 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001830 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +00001831 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001832 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +00001833 // Merge the current notion of the smallest into the smaller one.
1834 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1835 Smallest = EliminatedLHSVals[i];
1836 } else {
1837 // Merge into the smallest.
1838 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1839 }
1840 }
1841 LHSValNo = Smallest;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001842 } else if (EliminatedLHSVals.empty()) {
1843 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1844 *tri_->getSuperRegisters(LHS.reg))
1845 // Imprecise sub-register information. Can't handle it.
1846 return false;
1847 assert(0 && "No copies from the RHS?");
David Greene25133302007-06-08 17:18:56 +00001848 } else {
David Greene25133302007-06-08 17:18:56 +00001849 LHSValNo = EliminatedLHSVals[0];
1850 }
1851
1852 // Okay, now that there is a single LHS value number that we're merging the
1853 // RHS into, update the value number info for the LHS to indicate that the
1854 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +00001855 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001856 LHSValNo->def = VNI->def;
1857 LHSValNo->copy = VNI->copy;
David Greene25133302007-06-08 17:18:56 +00001858
1859 // Okay, the final step is to loop over the RHS live intervals, adding them to
1860 // the LHS.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001861 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001862 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +00001863 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +00001864 LHS.weight += RHS.weight;
1865 if (RHS.preference && !LHS.preference)
1866 LHS.preference = RHS.preference;
Dan Gohman97121ba2009-04-08 00:15:30 +00001867
1868 // Update the liveintervals of sub-registers.
1869 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
1870 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
1871 li_->getOrCreateInterval(*AS).MergeInClobberRanges(LHS,
1872 li_->getVNInfoAllocator());
1873
David Greene25133302007-06-08 17:18:56 +00001874 return true;
1875}
1876
1877/// JoinIntervals - Attempt to join these two intervals. On failure, this
1878/// returns false. Otherwise, if one of the intervals being joined is a
1879/// physreg, this method always canonicalizes LHS to be it. The output
1880/// "RHS" will not have been modified, so we can use this information
1881/// below to update aliases.
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001882bool
1883SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
1884 bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +00001885 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +00001886 // coalesced.
David Greene25133302007-06-08 17:18:56 +00001887 SmallVector<int, 16> LHSValNoAssignments;
1888 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +00001889 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1890 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001891 SmallVector<VNInfo*, 16> NewVNInfo;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001892
David Greene25133302007-06-08 17:18:56 +00001893 // If a live interval is a physical register, conservatively check if any
1894 // of its sub-registers is overlapping the live interval of the virtual
1895 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001896 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1897 *tri_->getSubRegisters(LHS.reg)) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001898 // If it's coalescing a virtual register to a physical register, estimate
1899 // its live interval length. This is the *cost* of scanning an entire live
1900 // interval. If the cost is low, we'll do an exhaustive check instead.
Evan Cheng1d8a76d2009-01-13 03:57:45 +00001901
1902 // If this is something like this:
1903 // BB1:
1904 // v1024 = op
1905 // ...
1906 // BB2:
1907 // ...
1908 // RAX = v1024
1909 //
1910 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
1911 // less conservative check. It's possible a sub-register is defined before
1912 // v1024 (or live in) and live out of BB1.
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001913 if (RHS.containsOneValue() &&
Evan Cheng167650d2009-01-13 06:08:37 +00001914 li_->intervalIsInOneMBB(RHS) &&
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001915 li_->getApproximateInstructionCount(RHS) <= 10) {
1916 // Perform a more exhaustive check for some common cases.
1917 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
David Greene25133302007-06-08 17:18:56 +00001918 return false;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001919 } else {
1920 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1921 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1922 DOUT << "Interfere with sub-register ";
1923 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1924 return false;
1925 }
1926 }
Dan Gohman6f0d0242008-02-10 18:45:23 +00001927 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1928 *tri_->getSubRegisters(RHS.reg)) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001929 if (LHS.containsOneValue() &&
1930 li_->getApproximateInstructionCount(LHS) <= 10) {
1931 // Perform a more exhaustive check for some common cases.
1932 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
David Greene25133302007-06-08 17:18:56 +00001933 return false;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001934 } else {
1935 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1936 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1937 DOUT << "Interfere with sub-register ";
1938 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1939 return false;
1940 }
1941 }
David Greene25133302007-06-08 17:18:56 +00001942 }
1943
1944 // Compute ultimate value numbers for the LHS and RHS values.
1945 if (RHS.containsOneValue()) {
1946 // Copies from a liveinterval with a single value are simple to handle and
1947 // very common, handle the special case here. This is important, because
1948 // often RHS is small and LHS is large (e.g. a physreg).
1949
1950 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +00001951 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +00001952 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001953 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001954 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001955 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001956 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001957 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +00001958 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +00001959 // can't swap the LHS/RHS intervals though.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001960 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001961 return SimpleJoin(LHS, RHS);
1962 } else {
Evan Chengc14b1442007-08-31 08:04:17 +00001963 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001964 }
1965 } else {
1966 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +00001967 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001968 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001969 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +00001970 }
1971
1972 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1973 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001974 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +00001975
1976 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1977 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001978 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1979 i != e; ++i) {
1980 VNInfo *VNI = *i;
1981 unsigned VN = VNI->id;
Evan Chengc8d044e2008-02-15 18:24:29 +00001982 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1983 if (LHSSrcReg != RHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001984 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +00001985 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001986 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001987 LHSValNoAssignments[VN] = VN;
1988 } else if (RHSValID == -1) {
1989 // Otherwise, it is a copy from the RHS, and we don't already have a
1990 // value# for it. Keep the current value number, but remember it.
1991 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001992 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001993 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001994 } else {
1995 // Otherwise, use the specified value #.
1996 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001997 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1998 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001999 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +00002000 }
David Greene25133302007-06-08 17:18:56 +00002001 }
2002 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002003 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00002004 LHSValNoAssignments[VN] = VN;
2005 }
2006 }
2007
2008 assert(RHSValID != -1 && "Didn't find value #?");
2009 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +00002010 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +00002011 // This path doesn't go through ComputeUltimateVN so just set
2012 // it to anything.
2013 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +00002014 }
David Greene25133302007-06-08 17:18:56 +00002015 } else {
2016 // Loop over the value numbers of the LHS, seeing if any are defined from
2017 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002018 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2019 i != e; ++i) {
2020 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00002021 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00002022 continue;
2023
2024 // DstReg is known to be a register in the LHS interval. If the src is
2025 // from the RHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00002026 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00002027 continue;
2028
2029 // Figure out the value # from the RHS.
Bill Wendling2674d712008-01-04 08:59:18 +00002030 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00002031 }
2032
2033 // Loop over the value numbers of the RHS, seeing if any are defined from
2034 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002035 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2036 i != e; ++i) {
2037 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00002038 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00002039 continue;
2040
2041 // DstReg is known to be a register in the RHS interval. If the src is
2042 // from the LHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00002043 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
David Greene25133302007-06-08 17:18:56 +00002044 continue;
2045
2046 // Figure out the value # from the LHS.
Bill Wendling2674d712008-01-04 08:59:18 +00002047 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00002048 }
2049
2050 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2051 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002052 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +00002053
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002054 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2055 i != e; ++i) {
2056 VNInfo *VNI = *i;
2057 unsigned VN = VNI->id;
2058 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00002059 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002060 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00002061 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002062 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00002063 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002064 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2065 i != e; ++i) {
2066 VNInfo *VNI = *i;
2067 unsigned VN = VNI->id;
2068 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00002069 continue;
2070 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +00002071 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002072 NewVNInfo.push_back(VNI);
2073 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00002074 continue;
2075 }
2076
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002077 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00002078 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002079 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00002080 }
2081 }
2082
2083 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +00002084 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +00002085 LiveInterval::const_iterator I = LHS.begin();
2086 LiveInterval::const_iterator IE = LHS.end();
2087 LiveInterval::const_iterator J = RHS.begin();
2088 LiveInterval::const_iterator JE = RHS.end();
2089
2090 // Skip ahead until the first place of potential sharing.
2091 if (I->start < J->start) {
2092 I = std::upper_bound(I, IE, J->start);
2093 if (I != LHS.begin()) --I;
2094 } else if (J->start < I->start) {
2095 J = std::upper_bound(J, JE, I->start);
2096 if (J != RHS.begin()) --J;
2097 }
2098
2099 while (1) {
2100 // Determine if these two live ranges overlap.
2101 bool Overlaps;
2102 if (I->start < J->start) {
2103 Overlaps = I->end > J->start;
2104 } else {
2105 Overlaps = J->end > I->start;
2106 }
2107
2108 // If so, check value # info to determine if they are really different.
2109 if (Overlaps) {
2110 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +00002111 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002112 if (LHSValNoAssignments[I->valno->id] !=
2113 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +00002114 return false;
2115 }
2116
2117 if (I->end < J->end) {
2118 ++I;
2119 if (I == IE) break;
2120 } else {
2121 ++J;
2122 if (J == JE) break;
2123 }
2124 }
2125
Evan Cheng34729252007-10-14 10:08:34 +00002126 // Update kill info. Some live ranges are extended due to copy coalescing.
2127 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2128 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2129 VNInfo *VNI = I->first;
2130 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2131 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00002132 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00002133 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2134 }
2135
2136 // Update kill info. Some live ranges are extended due to copy coalescing.
2137 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2138 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2139 VNInfo *VNI = I->first;
2140 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2141 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00002142 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00002143 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2144 }
2145
Gabor Greife510b3a2007-07-09 12:00:59 +00002146 // If we get here, we know that we can coalesce the live ranges. Ask the
2147 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002148 if ((RHS.ranges.size() > LHS.ranges.size() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002149 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2150 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002151 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002152 Swapped = true;
2153 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002154 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002155 Swapped = false;
2156 }
David Greene25133302007-06-08 17:18:56 +00002157 return true;
2158}
2159
2160namespace {
2161 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2162 // depth of the basic block (the unsigned), and then on the MBB number.
2163 struct DepthMBBCompare {
2164 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2165 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2166 if (LHS.first > RHS.first) return true; // Deeper loops first
2167 return LHS.first == RHS.first &&
2168 LHS.second->getNumber() < RHS.second->getNumber();
2169 }
2170 };
2171}
2172
Evan Cheng8fc9a102007-11-06 08:52:21 +00002173/// getRepIntervalSize - Returns the size of the interval that represents the
2174/// specified register.
2175template<class SF>
2176unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2177 return Rc->getRepIntervalSize(Reg);
2178}
2179
2180/// CopyRecSort::operator - Join priority queue sorting function.
2181///
2182bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2183 // Inner loops first.
2184 if (left.LoopDepth > right.LoopDepth)
2185 return false;
Evan Chengc8d044e2008-02-15 18:24:29 +00002186 else if (left.LoopDepth == right.LoopDepth)
Evan Cheng8fc9a102007-11-06 08:52:21 +00002187 if (left.isBackEdge && !right.isBackEdge)
2188 return false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002189 return true;
2190}
2191
Gabor Greife510b3a2007-07-09 12:00:59 +00002192void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00002193 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00002194 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00002195
Evan Cheng8b0b8742007-10-16 08:04:24 +00002196 std::vector<CopyRec> VirtCopies;
2197 std::vector<CopyRec> PhysCopies;
Evan Cheng7e073ba2008-04-09 20:57:25 +00002198 std::vector<CopyRec> ImpDefCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002199 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00002200 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2201 MII != E;) {
2202 MachineInstr *Inst = MII++;
2203
Evan Cheng32dfbea2007-10-12 08:50:34 +00002204 // If this isn't a copy nor a extract_subreg, we can't join intervals.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002205 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Cheng32dfbea2007-10-12 08:50:34 +00002206 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2207 DstReg = Inst->getOperand(0).getReg();
2208 SrcReg = Inst->getOperand(1).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +00002209 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2210 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00002211 DstReg = Inst->getOperand(0).getReg();
2212 SrcReg = Inst->getOperand(2).getReg();
Evan Cheng04ee5a12009-01-20 19:12:24 +00002213 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
Evan Cheng32dfbea2007-10-12 08:50:34 +00002214 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00002215
Evan Chengc8d044e2008-02-15 18:24:29 +00002216 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2217 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00002218 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002219 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002220 } else {
Evan Cheng7e073ba2008-04-09 20:57:25 +00002221 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2222 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2223 else if (SrcIsPhys || DstIsPhys)
Evan Chengc8d044e2008-02-15 18:24:29 +00002224 PhysCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002225 else
Evan Chengc8d044e2008-02-15 18:24:29 +00002226 VirtCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002227 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002228 }
2229
Evan Cheng8fc9a102007-11-06 08:52:21 +00002230 if (NewHeuristic)
2231 return;
2232
Evan Cheng7e073ba2008-04-09 20:57:25 +00002233 // Try coalescing implicit copies first, followed by copies to / from
2234 // physical registers, then finally copies from virtual registers to
2235 // virtual registers.
2236 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2237 CopyRec &TheCopy = ImpDefCopies[i];
2238 bool Again = false;
2239 if (!JoinCopy(TheCopy, Again))
2240 if (Again)
2241 TryAgain.push_back(TheCopy);
2242 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002243 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2244 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002245 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002246 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002247 if (Again)
2248 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00002249 }
2250 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2251 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002252 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002253 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002254 if (Again)
2255 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00002256 }
2257}
2258
2259void SimpleRegisterCoalescing::joinIntervals() {
2260 DOUT << "********** JOINING INTERVALS ***********\n";
2261
Evan Cheng8fc9a102007-11-06 08:52:21 +00002262 if (NewHeuristic)
2263 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2264
David Greene25133302007-06-08 17:18:56 +00002265 std::vector<CopyRec> TryAgainList;
Dan Gohmana8c763b2008-08-14 18:13:49 +00002266 if (loopInfo->empty()) {
David Greene25133302007-06-08 17:18:56 +00002267 // If there are no loops in the function, join intervals in function order.
2268 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2269 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002270 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002271 } else {
2272 // Otherwise, join intervals in inner loops before other intervals.
2273 // Unfortunately we can't just iterate over loop hierarchy here because
2274 // there may be more MBB's than BB's. Collect MBB's for sorting.
2275
2276 // Join intervals in the function prolog first. We want to join physical
2277 // registers with virtual registers before the intervals got too long.
2278 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002279 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2280 MachineBasicBlock *MBB = I;
2281 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2282 }
David Greene25133302007-06-08 17:18:56 +00002283
2284 // Sort by loop depth.
2285 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2286
2287 // Finally, join intervals in loop nest order.
2288 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002289 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002290 }
2291
2292 // Joining intervals can allow other intervals to be joined. Iteratively join
2293 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00002294 if (NewHeuristic) {
2295 SmallVector<CopyRec, 16> TryAgain;
2296 bool ProgressMade = true;
2297 while (ProgressMade) {
2298 ProgressMade = false;
2299 while (!JoinQueue->empty()) {
2300 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00002301 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002302 bool Success = JoinCopy(R, Again);
2303 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00002304 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002305 else if (Again)
2306 TryAgain.push_back(R);
2307 }
2308
2309 if (ProgressMade) {
2310 while (!TryAgain.empty()) {
2311 JoinQueue->push(TryAgain.back());
2312 TryAgain.pop_back();
2313 }
2314 }
2315 }
2316 } else {
2317 bool ProgressMade = true;
2318 while (ProgressMade) {
2319 ProgressMade = false;
2320
2321 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2322 CopyRec &TheCopy = TryAgainList[i];
2323 if (TheCopy.MI) {
2324 bool Again = false;
2325 bool Success = JoinCopy(TheCopy, Again);
2326 if (Success || !Again) {
2327 TheCopy.MI = 0; // Mark this one as done.
2328 ProgressMade = true;
2329 }
Evan Cheng0547bab2007-11-01 06:22:48 +00002330 }
David Greene25133302007-06-08 17:18:56 +00002331 }
2332 }
2333 }
2334
Evan Cheng8fc9a102007-11-06 08:52:21 +00002335 if (NewHeuristic)
Evan Chengc8d044e2008-02-15 18:24:29 +00002336 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00002337}
2338
2339/// Return true if the two specified registers belong to different register
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002340/// classes. The registers may be either phys or virt regs.
Evan Chenge00f5de2008-06-19 01:39:21 +00002341bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002342SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2343 unsigned RegB) const {
David Greene25133302007-06-08 17:18:56 +00002344 // Get the register classes for the first reg.
Dan Gohman6f0d0242008-02-10 18:45:23 +00002345 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2346 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
David Greene25133302007-06-08 17:18:56 +00002347 "Shouldn't consider two physregs!");
Evan Chengc8d044e2008-02-15 18:24:29 +00002348 return !mri_->getRegClass(RegB)->contains(RegA);
David Greene25133302007-06-08 17:18:56 +00002349 }
2350
2351 // Compare against the regclass for the second reg.
Evan Chenge00f5de2008-06-19 01:39:21 +00002352 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2353 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2354 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002355 return RegClassA != RegClassB;
Evan Chenge00f5de2008-06-19 01:39:21 +00002356 }
2357 return !RegClassA->contains(RegB);
David Greene25133302007-06-08 17:18:56 +00002358}
2359
2360/// lastRegisterUse - Returns the last use of the specific register between
Evan Chengc8d044e2008-02-15 18:24:29 +00002361/// cycles Start and End or NULL if there are no uses.
2362MachineOperand *
Chris Lattner84bc5422007-12-31 04:13:23 +00002363SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
Evan Chengc8d044e2008-02-15 18:24:29 +00002364 unsigned Reg, unsigned &UseIdx) const{
2365 UseIdx = 0;
2366 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2367 MachineOperand *LastUse = NULL;
2368 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2369 E = mri_->use_end(); I != E; ++I) {
2370 MachineOperand &Use = I.getOperand();
2371 MachineInstr *UseMI = Use.getParent();
Evan Cheng04ee5a12009-01-20 19:12:24 +00002372 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2373 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2374 SrcReg == DstReg)
Evan Chenga2fb6342008-03-25 02:02:19 +00002375 // Ignore identity copies.
2376 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +00002377 unsigned Idx = li_->getInstructionIndex(UseMI);
2378 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2379 LastUse = &Use;
Evan Cheng58207f12009-02-22 08:35:56 +00002380 UseIdx = li_->getUseIndex(Idx);
Evan Chengc8d044e2008-02-15 18:24:29 +00002381 }
2382 }
2383 return LastUse;
2384 }
2385
David Greene25133302007-06-08 17:18:56 +00002386 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2387 int s = Start;
2388 while (e >= s) {
2389 // Skip deleted instructions
2390 MachineInstr *MI = li_->getInstructionFromIndex(e);
2391 while ((e - InstrSlots::NUM) >= s && !MI) {
2392 e -= InstrSlots::NUM;
2393 MI = li_->getInstructionFromIndex(e);
2394 }
2395 if (e < s || MI == NULL)
2396 return NULL;
2397
Evan Chenga2fb6342008-03-25 02:02:19 +00002398 // Ignore identity copies.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002399 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2400 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2401 SrcReg == DstReg))
Evan Chenga2fb6342008-03-25 02:02:19 +00002402 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2403 MachineOperand &Use = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002404 if (Use.isReg() && Use.isUse() && Use.getReg() &&
Evan Chenga2fb6342008-03-25 02:02:19 +00002405 tri_->regsOverlap(Use.getReg(), Reg)) {
Evan Cheng58207f12009-02-22 08:35:56 +00002406 UseIdx = li_->getUseIndex(e);
Evan Chenga2fb6342008-03-25 02:02:19 +00002407 return &Use;
2408 }
David Greene25133302007-06-08 17:18:56 +00002409 }
David Greene25133302007-06-08 17:18:56 +00002410
2411 e -= InstrSlots::NUM;
2412 }
2413
2414 return NULL;
2415}
2416
2417
David Greene25133302007-06-08 17:18:56 +00002418void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +00002419 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +00002420 cerr << tri_->getName(reg);
David Greene25133302007-06-08 17:18:56 +00002421 else
2422 cerr << "%reg" << reg;
2423}
2424
2425void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng8fc9a102007-11-06 08:52:21 +00002426 JoinedCopies.clear();
Evan Chengcd047082008-08-30 09:09:33 +00002427 ReMatCopies.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002428 ReMatDefs.clear();
David Greene25133302007-06-08 17:18:56 +00002429}
2430
2431static bool isZeroLengthInterval(LiveInterval *li) {
2432 for (LiveInterval::Ranges::const_iterator
2433 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2434 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2435 return false;
2436 return true;
2437}
2438
Evan Chengdb9b1c32008-04-03 16:41:54 +00002439/// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2440/// turn the copy into an implicit def.
2441bool
2442SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2443 MachineBasicBlock *MBB,
2444 unsigned DstReg, unsigned SrcReg) {
2445 MachineInstr *CopyMI = &*I;
2446 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2447 if (!li_->hasInterval(SrcReg))
2448 return false;
2449 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2450 if (!SrcInt.empty())
2451 return false;
Evan Chengf20d9432008-04-09 01:30:15 +00002452 if (!li_->hasInterval(DstReg))
2453 return false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002454 LiveInterval &DstInt = li_->getInterval(DstReg);
Evan Chengff7a3e52008-04-16 18:48:43 +00002455 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002456 DstInt.removeValNo(DstLR->valno);
2457 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2458 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2459 CopyMI->RemoveOperand(i);
Dan Gohmana8c763b2008-08-14 18:13:49 +00002460 bool NoUse = mri_->use_empty(SrcReg);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002461 if (NoUse) {
2462 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2463 E = mri_->reg_end(); I != E; ) {
2464 assert(I.getOperand().isDef());
2465 MachineInstr *DefMI = &*I;
2466 ++I;
2467 // The implicit_def source has no other uses, delete it.
2468 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2469 li_->RemoveMachineInstrFromMaps(DefMI);
2470 DefMI->eraseFromParent();
Evan Chengdb9b1c32008-04-03 16:41:54 +00002471 }
2472 }
2473 ++I;
2474 return true;
2475}
2476
2477
David Greene25133302007-06-08 17:18:56 +00002478bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2479 mf_ = &fn;
Evan Cheng70071432008-02-13 03:01:43 +00002480 mri_ = &fn.getRegInfo();
David Greene25133302007-06-08 17:18:56 +00002481 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00002482 tri_ = tm_->getRegisterInfo();
David Greene25133302007-06-08 17:18:56 +00002483 tii_ = tm_->getInstrInfo();
2484 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00002485 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00002486
2487 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2488 << "********** Function: "
2489 << ((Value*)mf_->getFunction())->getName() << '\n';
2490
Dan Gohman6f0d0242008-02-10 18:45:23 +00002491 allocatableRegs_ = tri_->getAllocatableSet(fn);
2492 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2493 E = tri_->regclass_end(); I != E; ++I)
Bill Wendling2674d712008-01-04 08:59:18 +00002494 allocatableRCRegs_.insert(std::make_pair(*I,
Dan Gohman6f0d0242008-02-10 18:45:23 +00002495 tri_->getAllocatableSet(fn, *I)));
David Greene25133302007-06-08 17:18:56 +00002496
Gabor Greife510b3a2007-07-09 12:00:59 +00002497 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00002498 if (EnableJoining) {
2499 joinIntervals();
Bill Wendlingbebbded2008-12-19 02:09:57 +00002500 DEBUG({
2501 DOUT << "********** INTERVALS POST JOINING **********\n";
2502 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2503 I->second->print(DOUT, tri_);
2504 DOUT << "\n";
2505 }
2506 });
David Greene25133302007-06-08 17:18:56 +00002507 }
2508
Evan Chengc8d044e2008-02-15 18:24:29 +00002509 // Perform a final pass over the instructions and compute spill weights
2510 // and remove identity moves.
Evan Chengb3990d52008-10-27 23:21:01 +00002511 SmallVector<unsigned, 4> DeadDefs;
David Greene25133302007-06-08 17:18:56 +00002512 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2513 mbbi != mbbe; ++mbbi) {
2514 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002515 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00002516
2517 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2518 mii != mie; ) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002519 MachineInstr *MI = mii;
Evan Cheng04ee5a12009-01-20 19:12:24 +00002520 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Chenga971dbd2008-04-24 09:06:33 +00002521 if (JoinedCopies.count(MI)) {
2522 // Delete all coalesced copies.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002523 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002524 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +00002525 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2526 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
Evan Chenga971dbd2008-04-24 09:06:33 +00002527 "Unrecognized copy instruction");
2528 DstReg = MI->getOperand(0).getReg();
2529 }
2530 if (MI->registerDefIsDead(DstReg)) {
2531 LiveInterval &li = li_->getInterval(DstReg);
2532 if (!ShortenDeadCopySrcLiveRange(li, MI))
2533 ShortenDeadCopyLiveRange(li, MI);
2534 }
2535 li_->RemoveMachineInstrFromMaps(MI);
2536 mii = mbbi->erase(mii);
2537 ++numPeep;
2538 continue;
2539 }
2540
Evan Cheng20580a12008-09-19 17:38:47 +00002541 // Now check if this is a remat'ed def instruction which is now dead.
2542 if (ReMatDefs.count(MI)) {
2543 bool isDead = true;
2544 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2545 const MachineOperand &MO = MI->getOperand(i);
Evan Chengb3990d52008-10-27 23:21:01 +00002546 if (!MO.isReg())
Evan Cheng20580a12008-09-19 17:38:47 +00002547 continue;
2548 unsigned Reg = MO.getReg();
Evan Cheng6792e902009-02-04 18:18:58 +00002549 if (!Reg)
2550 continue;
Evan Chengb3990d52008-10-27 23:21:01 +00002551 if (TargetRegisterInfo::isVirtualRegister(Reg))
2552 DeadDefs.push_back(Reg);
2553 if (MO.isDead())
2554 continue;
Evan Cheng20580a12008-09-19 17:38:47 +00002555 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2556 !mri_->use_empty(Reg)) {
2557 isDead = false;
2558 break;
2559 }
2560 }
2561 if (isDead) {
Evan Chengb3990d52008-10-27 23:21:01 +00002562 while (!DeadDefs.empty()) {
2563 unsigned DeadDef = DeadDefs.back();
2564 DeadDefs.pop_back();
2565 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2566 }
Evan Cheng20580a12008-09-19 17:38:47 +00002567 li_->RemoveMachineInstrFromMaps(mii);
2568 mii = mbbi->erase(mii);
Evan Chengfee2d692008-09-19 22:49:39 +00002569 continue;
Evan Chengb3990d52008-10-27 23:21:01 +00002570 } else
2571 DeadDefs.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002572 }
2573
Evan Chenga971dbd2008-04-24 09:06:33 +00002574 // If the move will be an identity move delete it
Evan Cheng04ee5a12009-01-20 19:12:24 +00002575 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
Evan Chenga971dbd2008-04-24 09:06:33 +00002576 if (isMove && SrcReg == DstReg) {
2577 if (li_->hasInterval(SrcReg)) {
2578 LiveInterval &RegInt = li_->getInterval(SrcReg);
Evan Cheng3c88d742008-03-18 08:26:47 +00002579 // If def of this move instruction is dead, remove its live range
2580 // from the dstination register's live interval.
Evan Cheng20580a12008-09-19 17:38:47 +00002581 if (MI->registerDefIsDead(DstReg)) {
2582 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2583 ShortenDeadCopyLiveRange(RegInt, MI);
Evan Cheng3c88d742008-03-18 08:26:47 +00002584 }
2585 }
Evan Cheng20580a12008-09-19 17:38:47 +00002586 li_->RemoveMachineInstrFromMaps(MI);
David Greene25133302007-06-08 17:18:56 +00002587 mii = mbbi->erase(mii);
2588 ++numPeep;
Evan Chenga971dbd2008-04-24 09:06:33 +00002589 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
David Greene25133302007-06-08 17:18:56 +00002590 SmallSet<unsigned, 4> UniqueUses;
Evan Cheng20580a12008-09-19 17:38:47 +00002591 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2592 const MachineOperand &mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002593 if (mop.isReg() && mop.getReg() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002594 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002595 unsigned reg = mop.getReg();
David Greene25133302007-06-08 17:18:56 +00002596 // Multiple uses of reg by the same instruction. It should not
2597 // contribute to spill weight again.
2598 if (UniqueUses.count(reg) != 0)
2599 continue;
2600 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002601 RegInt.weight +=
Evan Chengc3417602008-06-21 06:45:54 +00002602 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00002603 UniqueUses.insert(reg);
2604 }
2605 }
2606 ++mii;
2607 }
2608 }
2609 }
2610
2611 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +00002612 LiveInterval &LI = *I->second;
Dan Gohman6f0d0242008-02-10 18:45:23 +00002613 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
David Greene25133302007-06-08 17:18:56 +00002614 // If the live interval length is essentially zero, i.e. in every live
2615 // range the use follows def immediately, it doesn't make sense to spill
2616 // it and hope it will be easier to allocate for this li.
2617 if (isZeroLengthInterval(&LI))
2618 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002619 else {
2620 bool isLoad = false;
Evan Chengdc377862008-09-30 15:44:16 +00002621 SmallVector<LiveInterval*, 4> SpillIs;
2622 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00002623 // If all of the definitions of the interval are re-materializable,
2624 // it is a preferred candidate for spilling. If non of the defs are
2625 // loads, then it's potentially very cheap to re-materialize.
2626 // FIXME: this gets much more complicated once we support non-trivial
2627 // re-materialization.
2628 if (isLoad)
2629 LI.weight *= 0.9F;
2630 else
2631 LI.weight *= 0.5F;
2632 }
2633 }
David Greene25133302007-06-08 17:18:56 +00002634
2635 // Slightly prefer live interval that has been assigned a preferred reg.
2636 if (LI.preference)
2637 LI.weight *= 1.01F;
2638
2639 // Divide the weight of the interval by its size. This encourages
2640 // spilling of intervals that are large and have few uses, and
2641 // discourages spilling of small intervals with many uses.
Owen Anderson496bac52008-07-23 19:47:27 +00002642 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
David Greene25133302007-06-08 17:18:56 +00002643 }
2644 }
2645
2646 DEBUG(dump());
2647 return true;
2648}
2649
2650/// print - Implement the dump method.
2651void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2652 li_->print(O, m);
2653}
David Greene2c17c4d2007-09-06 16:18:45 +00002654
2655RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2656 return new SimpleRegisterCoalescing();
2657}
2658
2659// Make sure that anything that uses RegisterCoalescer pulls in this file...
2660DEFINING_FILE_FOR(SimpleRegisterCoalescing)