blob: cb5d3f0daa5a53577b8b2fb6089f8623121479f4 [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"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
David Greene25133302007-06-08 17:18:56 +000032#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
35#include <algorithm>
36#include <cmath>
37using namespace llvm;
38
39STATISTIC(numJoins , "Number of interval joins performed");
Evan Cheng8c08d8c2009-01-23 02:15:19 +000040STATISTIC(numCrossRCs , "Number of cross class joins performed");
Evan Cheng70071432008-02-13 03:01:43 +000041STATISTIC(numCommutes , "Number of instruction commuting performed");
42STATISTIC(numExtends , "Number of copies extended");
Evan Chengcd047082008-08-30 09:09:33 +000043STATISTIC(NumReMats , "Number of instructions re-materialized");
David Greene25133302007-06-08 17:18:56 +000044STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
45STATISTIC(numAborts , "Number of times interval joining aborted");
Evan Cheng77fde2c2009-02-08 07:48:37 +000046STATISTIC(numDeadValNo, "Number of valno def marked dead");
David Greene25133302007-06-08 17:18:56 +000047
48char SimpleRegisterCoalescing::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000049static cl::opt<bool>
50EnableJoining("join-liveintervals",
51 cl::desc("Coalesce copies (default=true)"),
52 cl::init(true));
David Greene25133302007-06-08 17:18:56 +000053
Dan Gohman844731a2008-05-13 00:00:25 +000054static cl::opt<bool>
55NewHeuristic("new-coalescer-heuristic",
Evan Chenge00f5de2008-06-19 01:39:21 +000056 cl::desc("Use new coalescer heuristic"),
57 cl::init(false), cl::Hidden);
58
59static cl::opt<bool>
Evan Cheng8c08d8c2009-01-23 02:15:19 +000060CrossClassJoin("join-cross-class-copies",
61 cl::desc("Coalesce cross register class copies"),
Evan Chenge00f5de2008-06-19 01:39:21 +000062 cl::init(false), cl::Hidden);
Evan Cheng8fc9a102007-11-06 08:52:21 +000063
Evan Cheng0490dcb2009-04-30 18:39:57 +000064static cl::opt<bool>
65PhysJoinTweak("tweak-phys-join-heuristics",
66 cl::desc("Tweak heuristics for joining phys reg with vr"),
67 cl::init(false), cl::Hidden);
68
Dan Gohman844731a2008-05-13 00:00:25 +000069static RegisterPass<SimpleRegisterCoalescing>
70X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000071
Dan Gohman844731a2008-05-13 00:00:25 +000072// Declare that we implement the RegisterCoalescer interface
73static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000074
Dan Gohman6ddba2b2008-05-13 02:05:11 +000075const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
David Greene25133302007-06-08 17:18:56 +000076
77void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
Evan Chengbbeeb2a2008-09-22 20:58:04 +000078 AU.addRequired<LiveIntervals>();
David Greene25133302007-06-08 17:18:56 +000079 AU.addPreserved<LiveIntervals>();
Evan Chengbbeeb2a2008-09-22 20:58:04 +000080 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000081 AU.addPreserved<MachineLoopInfo>();
82 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000083 if (StrongPHIElim)
84 AU.addPreservedID(StrongPHIEliminationID);
85 else
86 AU.addPreservedID(PHIEliminationID);
David Greene25133302007-06-08 17:18:56 +000087 AU.addPreservedID(TwoAddressInstructionPassID);
David Greene25133302007-06-08 17:18:56 +000088 MachineFunctionPass::getAnalysisUsage(AU);
89}
90
Gabor Greife510b3a2007-07-09 12:00:59 +000091/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000092/// being the source and IntB being the dest, thus this defines a value number
93/// in IntB. If the source value number (in IntA) is defined by a copy from B,
94/// see if we can merge these two pieces of B into a single value number,
95/// eliminating a copy. For example:
96///
97/// A3 = B0
98/// ...
99/// B1 = A3 <- this copy
100///
101/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
102/// value number to be replaced with B0 (which simplifies the B liveinterval).
103///
104/// This returns true if an interval was modified.
105///
Bill Wendling2674d712008-01-04 08:59:18 +0000106bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
107 LiveInterval &IntB,
108 MachineInstr *CopyMI) {
David Greene25133302007-06-08 17:18:56 +0000109 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
110
111 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
112 // the example above.
113 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000114 assert(BLR != IntB.end() && "Live range not found!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000115 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000116
117 // Get the location that B is defined at. Two options: either this value has
118 // an unknown definition point or it is defined at CopyIdx. If unknown, we
119 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000120 if (!BValNo->copy) return false;
121 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
David Greene25133302007-06-08 17:18:56 +0000122
Evan Cheng70071432008-02-13 03:01:43 +0000123 // AValNo is the value number in A that defines the copy, A3 in the example.
124 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000125 assert(ALR != IntA.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000126 VNInfo *AValNo = ALR->valno;
Evan Cheng5379f412008-12-19 20:58:01 +0000127 // If it's re-defined by an early clobber somewhere in the live range, then
128 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
129 // See PR3149:
130 // 172 %ECX<def> = MOV32rr %reg1039<kill>
131 // 180 INLINEASM <es:subl $5,$1
132 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
133 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
134 // 188 %EAX<def> = MOV32rr %EAX<kill>
135 // 196 %ECX<def> = MOV32rr %ECX<kill>
136 // 204 %ECX<def> = MOV32rr %ECX<kill>
137 // 212 %EAX<def> = MOV32rr %EAX<kill>
138 // 220 %EAX<def> = MOV32rr %EAX
139 // 228 %reg1039<def> = MOV32rr %ECX<kill>
140 // The early clobber operand ties ECX input to the ECX def.
141 //
142 // The live interval of ECX is represented as this:
143 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
144 // The coalescer has no idea there was a def in the middle of [174,230].
Lang Hames857c4e02009-06-17 21:01:20 +0000145 if (AValNo->hasRedefByEC())
Evan Cheng5379f412008-12-19 20:58:01 +0000146 return false;
David Greene25133302007-06-08 17:18:56 +0000147
Evan Cheng70071432008-02-13 03:01:43 +0000148 // If AValNo is defined as a copy from IntB, we can potentially process this.
David Greene25133302007-06-08 17:18:56 +0000149 // Get the instruction that defines this value number.
Evan Chengc8d044e2008-02-15 18:24:29 +0000150 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
David Greene25133302007-06-08 17:18:56 +0000151 if (!SrcReg) return false; // Not defined by a copy.
152
153 // If the value number is not defined by a copy instruction, ignore it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000154
David Greene25133302007-06-08 17:18:56 +0000155 // If the source register comes from an interval other than IntB, we can't
156 // handle this.
Evan Chengc8d044e2008-02-15 18:24:29 +0000157 if (SrcReg != IntB.reg) return false;
David Greene25133302007-06-08 17:18:56 +0000158
159 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000160 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000161 assert(ValLR != IntB.end() && "Live range not found!");
David Greene25133302007-06-08 17:18:56 +0000162
163 // Make sure that the end of the live range is inside the same block as
164 // CopyMI.
165 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
166 if (!ValLREndInst ||
167 ValLREndInst->getParent() != CopyMI->getParent()) return false;
168
169 // Okay, we now know that ValLR ends in the same block that the CopyMI
170 // live-range starts. If there are no intervening live ranges between them in
171 // IntB, we can merge them.
172 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000173
174 // If a live interval is a physical register, conservatively check if any
175 // of its sub-registers is overlapping the live interval of the virtual
176 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000177 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
178 *tri_->getSubRegisters(IntB.reg)) {
179 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
Evan Chengdc5294f2007-08-14 23:19:28 +0000180 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
181 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000182 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Chengdc5294f2007-08-14 23:19:28 +0000183 return false;
184 }
185 }
David Greene25133302007-06-08 17:18:56 +0000186
Dan Gohman6f0d0242008-02-10 18:45:23 +0000187 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000188
Evan Chenga8d94f12007-08-07 23:49:57 +0000189 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000190 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000191 // that defines this value #'. Update the the valnum with the new defining
192 // instruction #.
Evan Chengc8d044e2008-02-15 18:24:29 +0000193 BValNo->def = FillerStart;
194 BValNo->copy = NULL;
David Greene25133302007-06-08 17:18:56 +0000195
196 // Okay, we can merge them. We need to insert a new liverange:
197 // [ValLR.end, BLR.begin) of either value number, then we merge the
198 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000199 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
200
201 // If the IntB live range is assigned to a physical register, and if that
Evan Chenga2e64352009-03-11 00:03:21 +0000202 // physreg has sub-registers, update their live intervals as well.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000203 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
Evan Chenga2e64352009-03-11 00:03:21 +0000204 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
205 LiveInterval &SRLI = li_->getInterval(*SR);
206 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
Lang Hames857c4e02009-06-17 21:01:20 +0000207 SRLI.getNextValue(FillerStart, 0, true,
208 li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000209 }
210 }
211
212 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng25f34a32008-09-15 06:28:41 +0000213 if (BValNo != ValLR->valno) {
214 IntB.addKills(ValLR->valno, BValNo->kills);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000215 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
Evan Cheng25f34a32008-09-15 06:28:41 +0000216 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000217 DOUT << " result = "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000218 DOUT << "\n";
219
220 // If the source instruction was killing the source register before the
221 // merge, unset the isKill marker given the live range has been extended.
222 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
Evan Cheng25f34a32008-09-15 06:28:41 +0000223 if (UIdx != -1) {
Chris Lattnerf7382302007-12-30 21:56:09 +0000224 ValLREndInst->getOperand(UIdx).setIsKill(false);
Evan Cheng25f34a32008-09-15 06:28:41 +0000225 IntB.removeKill(ValLR->valno, FillerStart);
226 }
Evan Cheng70071432008-02-13 03:01:43 +0000227
228 ++numExtends;
229 return true;
230}
231
Evan Cheng559f4222008-02-16 02:32:17 +0000232/// HasOtherReachingDefs - Return true if there are definitions of IntB
233/// other than BValNo val# that can reach uses of AValno val# of IntA.
234bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
235 LiveInterval &IntB,
236 VNInfo *AValNo,
237 VNInfo *BValNo) {
238 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
239 AI != AE; ++AI) {
240 if (AI->valno != AValNo) continue;
241 LiveInterval::Ranges::iterator BI =
242 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
243 if (BI != IntB.ranges.begin())
244 --BI;
245 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
246 if (BI->valno == BValNo)
247 continue;
248 if (BI->start <= AI->start && BI->end > AI->start)
249 return true;
250 if (BI->start > AI->start && BI->start < AI->end)
251 return true;
252 }
253 }
254 return false;
255}
256
Evan Cheng70071432008-02-13 03:01:43 +0000257/// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
258/// being the source and IntB being the dest, thus this defines a value number
259/// in IntB. If the source value number (in IntA) is defined by a commutable
260/// instruction and its other operand is coalesced to the copy dest register,
261/// see if we can transform the copy into a noop by commuting the definition. For
262/// example,
263///
264/// A3 = op A2 B0<kill>
265/// ...
266/// B1 = A3 <- this copy
267/// ...
268/// = op A3 <- more uses
269///
270/// ==>
271///
272/// B2 = op B0 A2<kill>
273/// ...
274/// B1 = B2 <- now an identify copy
275/// ...
276/// = op B2 <- more uses
277///
278/// This returns true if an interval was modified.
279///
280bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
281 LiveInterval &IntB,
282 MachineInstr *CopyMI) {
Evan Cheng70071432008-02-13 03:01:43 +0000283 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
284
Evan Chenga9407f52008-02-18 18:56:31 +0000285 // FIXME: For now, only eliminate the copy by commuting its def when the
286 // source register is a virtual register. We want to guard against cases
287 // where the copy is a back edge copy and commuting the def lengthen the
288 // live interval of the source register to the entire loop.
289 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
Evan Cheng96cfff02008-02-18 08:40:53 +0000290 return false;
291
Evan Chengc8d044e2008-02-15 18:24:29 +0000292 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
Evan Cheng70071432008-02-13 03:01:43 +0000293 // the example above.
294 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000295 assert(BLR != IntB.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000296 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000297
Evan Cheng70071432008-02-13 03:01:43 +0000298 // Get the location that B is defined at. Two options: either this value has
299 // an unknown definition point or it is defined at CopyIdx. If unknown, we
300 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000301 if (!BValNo->copy) return false;
Evan Cheng70071432008-02-13 03:01:43 +0000302 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
303
304 // AValNo is the value number in A that defines the copy, A3 in the example.
305 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000306 assert(ALR != IntA.end() && "Live range not found!");
Evan Cheng70071432008-02-13 03:01:43 +0000307 VNInfo *AValNo = ALR->valno;
Evan Chenge35a6d12008-02-13 08:41:08 +0000308 // If other defs can reach uses of this def, then it's not safe to perform
Lang Hames857c4e02009-06-17 21:01:20 +0000309 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
310 // tested?
311 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
312 AValNo->isUnused() || AValNo->hasPHIKill())
Evan Cheng70071432008-02-13 03:01:43 +0000313 return false;
314 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
315 const TargetInstrDesc &TID = DefMI->getDesc();
Evan Cheng261ce1d2009-07-10 19:15:51 +0000316 if (!TID.isCommutable())
317 return false;
318 // If DefMI is a two-address instruction then commuting it will change the
319 // destination register.
320 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
321 assert(DefIdx != -1);
322 unsigned UseOpIdx;
323 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
324 return false;
325 unsigned Op1, Op2, NewDstIdx;
326 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
327 return false;
328 if (Op1 == UseOpIdx)
329 NewDstIdx = Op2;
330 else if (Op2 == UseOpIdx)
331 NewDstIdx = Op1;
332 else
Evan Cheng70071432008-02-13 03:01:43 +0000333 return false;
334
Evan Chengc8d044e2008-02-15 18:24:29 +0000335 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
336 unsigned NewReg = NewDstMO.getReg();
337 if (NewReg != IntB.reg || !NewDstMO.isKill())
Evan Cheng70071432008-02-13 03:01:43 +0000338 return false;
339
340 // Make sure there are no other definitions of IntB that would reach the
341 // uses which the new definition can reach.
Evan Cheng559f4222008-02-16 02:32:17 +0000342 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
343 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000344
Evan Chenged70cbb32008-03-26 19:03:01 +0000345 // If some of the uses of IntA.reg is already coalesced away, return false.
346 // It's not possible to determine whether it's safe to perform the coalescing.
347 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
348 UE = mri_->use_end(); UI != UE; ++UI) {
349 MachineInstr *UseMI = &*UI;
350 unsigned UseIdx = li_->getInstructionIndex(UseMI);
351 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000352 if (ULR == IntA.end())
353 continue;
Evan Chenged70cbb32008-03-26 19:03:01 +0000354 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
355 return false;
356 }
357
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000358 // At this point we have decided that it is legal to do this
359 // transformation. Start by commuting the instruction.
Evan Cheng70071432008-02-13 03:01:43 +0000360 MachineBasicBlock *MBB = DefMI->getParent();
361 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
Evan Cheng559f4222008-02-16 02:32:17 +0000362 if (!NewMI)
363 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000364 if (NewMI != DefMI) {
365 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
366 MBB->insert(DefMI, NewMI);
367 MBB->erase(DefMI);
368 }
Evan Cheng6130f662008-03-05 00:59:57 +0000369 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
Evan Cheng70071432008-02-13 03:01:43 +0000370 NewMI->getOperand(OpIdx).setIsKill();
371
Lang Hames857c4e02009-06-17 21:01:20 +0000372 bool BHasPHIKill = BValNo->hasPHIKill();
Evan Cheng70071432008-02-13 03:01:43 +0000373 SmallVector<VNInfo*, 4> BDeadValNos;
Lang Hamesffd13262009-07-09 03:57:02 +0000374 VNInfo::KillSet BKills;
Evan Cheng70071432008-02-13 03:01:43 +0000375 std::map<unsigned, unsigned> BExtend;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000376
377 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
378 // A = or A, B
379 // ...
380 // B = A
381 // ...
382 // C = A<kill>
383 // ...
384 // = B
385 //
386 // then do not add kills of A to the newly created B interval.
387 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
388 if (Extended)
389 BExtend[ALR->end] = BLR->end;
390
391 // Update uses of IntA of the specific Val# with IntB.
Evan Chenga2e64352009-03-11 00:03:21 +0000392 bool BHasSubRegs = false;
393 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
394 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
Evan Cheng70071432008-02-13 03:01:43 +0000395 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
396 UE = mri_->use_end(); UI != UE;) {
397 MachineOperand &UseMO = UI.getOperand();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000398 MachineInstr *UseMI = &*UI;
Evan Cheng70071432008-02-13 03:01:43 +0000399 ++UI;
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000400 if (JoinedCopies.count(UseMI))
Evan Chenged70cbb32008-03-26 19:03:01 +0000401 continue;
Evan Cheng70071432008-02-13 03:01:43 +0000402 unsigned UseIdx = li_->getInstructionIndex(UseMI);
403 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000404 if (ULR == IntA.end() || ULR->valno != AValNo)
Evan Cheng70071432008-02-13 03:01:43 +0000405 continue;
406 UseMO.setReg(NewReg);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000407 if (UseMI == CopyMI)
408 continue;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000409 if (UseMO.isKill()) {
410 if (Extended)
411 UseMO.setIsKill(false);
412 else
Lang Hamesffd13262009-07-09 03:57:02 +0000413 BKills.push_back(VNInfo::KillInfo(false, li_->getUseIndex(UseIdx)+1));
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000414 }
Evan Cheng04ee5a12009-01-20 19:12:24 +0000415 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
416 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000417 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +0000418 if (DstReg == IntB.reg) {
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000419 // This copy will become a noop. If it's defining a new val#,
420 // remove that val# as well. However this live range is being
421 // extended to the end of the existing live range defined by the copy.
422 unsigned DefIdx = li_->getDefIndex(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000423 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
Lang Hames857c4e02009-06-17 21:01:20 +0000424 BHasPHIKill |= DLR->valno->hasPHIKill();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000425 assert(DLR->valno->def == DefIdx);
426 BDeadValNos.push_back(DLR->valno);
427 BExtend[DLR->start] = DLR->end;
428 JoinedCopies.insert(UseMI);
429 // If this is a kill but it's going to be removed, the last use
430 // of the same val# is the new kill.
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000431 if (UseMO.isKill())
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000432 BKills.pop_back();
Evan Cheng70071432008-02-13 03:01:43 +0000433 }
434 }
435
436 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
437 // simply extend BLR if CopyMI doesn't end the range.
438 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
439
Evan Cheng739583b2008-06-17 20:11:16 +0000440 // Remove val#'s defined by copies that will be coalesced away.
Evan Chenga597a972009-03-11 22:18:44 +0000441 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
442 VNInfo *DeadVNI = BDeadValNos[i];
443 if (BHasSubRegs) {
444 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
445 LiveInterval &SRLI = li_->getInterval(*SR);
446 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
447 SRLI.removeValNo(SRLR->valno);
448 }
449 }
Evan Cheng70071432008-02-13 03:01:43 +0000450 IntB.removeValNo(BDeadValNos[i]);
Evan Chenga597a972009-03-11 22:18:44 +0000451 }
Evan Cheng739583b2008-06-17 20:11:16 +0000452
453 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
454 // is updated. Kills are also updated.
455 VNInfo *ValNo = BValNo;
456 ValNo->def = AValNo->def;
457 ValNo->copy = NULL;
458 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
Lang Hamesffd13262009-07-09 03:57:02 +0000459 unsigned Kill = ValNo->kills[j].killIdx;
Evan Cheng739583b2008-06-17 20:11:16 +0000460 if (Kill != BLR->end)
Lang Hamesffd13262009-07-09 03:57:02 +0000461 BKills.push_back(VNInfo::KillInfo(ValNo->kills[j].isPHIKill, Kill));
Evan Cheng739583b2008-06-17 20:11:16 +0000462 }
463 ValNo->kills.clear();
Evan Cheng70071432008-02-13 03:01:43 +0000464 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
465 AI != AE; ++AI) {
466 if (AI->valno != AValNo) continue;
467 unsigned End = AI->end;
468 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
469 if (EI != BExtend.end())
470 End = EI->second;
471 IntB.addRange(LiveRange(AI->start, End, ValNo));
Evan Chenga2e64352009-03-11 00:03:21 +0000472
473 // If the IntB live range is assigned to a physical register, and if that
474 // physreg has sub-registers, update their live intervals as well.
Evan Chenga597a972009-03-11 22:18:44 +0000475 if (BHasSubRegs) {
Evan Chenga2e64352009-03-11 00:03:21 +0000476 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
477 LiveInterval &SRLI = li_->getInterval(*SR);
478 SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
479 }
480 }
Evan Cheng70071432008-02-13 03:01:43 +0000481 }
482 IntB.addKills(ValNo, BKills);
Lang Hames857c4e02009-06-17 21:01:20 +0000483 ValNo->setHasPHIKill(BHasPHIKill);
Evan Cheng70071432008-02-13 03:01:43 +0000484
485 DOUT << " result = "; IntB.print(DOUT, tri_);
486 DOUT << "\n";
487
488 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
489 IntA.removeValNo(AValNo);
490 DOUT << " result = "; IntA.print(DOUT, tri_);
491 DOUT << "\n";
492
493 ++numCommutes;
David Greene25133302007-06-08 17:18:56 +0000494 return true;
495}
496
Evan Cheng961154f2009-02-05 08:45:04 +0000497/// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
498/// fallthoughs to SuccMBB.
499static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
500 MachineBasicBlock *SuccMBB,
501 const TargetInstrInfo *tii_) {
502 if (MBB == SuccMBB)
503 return true;
504 MachineBasicBlock *TBB = 0, *FBB = 0;
505 SmallVector<MachineOperand, 4> Cond;
506 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
507 MBB->isSuccessor(SuccMBB);
508}
509
510/// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
511/// from a physical register live interval as well as from the live intervals
512/// of its sub-registers.
513static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
514 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
515 li.removeRange(Start, End, true);
516 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
517 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
518 if (!li_->hasInterval(*SR))
519 continue;
520 LiveInterval &sli = li_->getInterval(*SR);
521 unsigned RemoveEnd = Start;
522 while (RemoveEnd != End) {
523 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
524 if (LR == sli.end())
525 break;
526 RemoveEnd = (LR->end < End) ? LR->end : End;
527 sli.removeRange(Start, RemoveEnd, true);
528 Start = RemoveEnd;
529 }
530 }
531 }
532}
533
534/// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
Evan Cheng86fb9fd2009-02-08 08:24:28 +0000535/// as the copy instruction, trim the live interval to the last use and return
Evan Cheng961154f2009-02-05 08:45:04 +0000536/// true.
537bool
538SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(unsigned CopyIdx,
539 MachineBasicBlock *CopyMBB,
540 LiveInterval &li,
541 const LiveRange *LR) {
542 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
543 unsigned LastUseIdx;
544 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
545 LastUseIdx);
546 if (LastUse) {
547 MachineInstr *LastUseMI = LastUse->getParent();
548 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
549 // r1024 = op
550 // ...
551 // BB1:
552 // = r1024
553 //
554 // BB2:
555 // r1025<dead> = r1024<kill>
556 if (MBBStart < LR->end)
557 removeRange(li, MBBStart, LR->end, li_, tri_);
558 return true;
559 }
560
561 // There are uses before the copy, just shorten the live range to the end
562 // of last use.
563 LastUse->setIsKill();
564 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
Lang Hamesffd13262009-07-09 03:57:02 +0000565 li.addKill(LR->valno, LastUseIdx+1, false);
Evan Cheng961154f2009-02-05 08:45:04 +0000566 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
567 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
568 DstReg == li.reg) {
569 // Last use is itself an identity code.
570 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
571 LastUseMI->getOperand(DeadIdx).setIsDead();
572 }
573 return true;
574 }
575
576 // Is it livein?
577 if (LR->start <= MBBStart && LR->end > MBBStart) {
578 if (LR->start == 0) {
579 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
580 // Live-in to the function but dead. Remove it from entry live-in set.
581 mf_->begin()->removeLiveIn(li.reg);
582 }
583 // FIXME: Shorten intervals in BBs that reaches this BB.
584 }
585
586 return false;
587}
588
Evan Chengcd047082008-08-30 09:09:33 +0000589/// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
590/// computation, replace the copy by rematerialize the definition.
591bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
592 unsigned DstReg,
593 MachineInstr *CopyMI) {
594 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
595 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
Dan Gohmanfd246e52009-01-13 20:25:24 +0000596 assert(SrcLR != SrcInt.end() && "Live range not found!");
Evan Chengcd047082008-08-30 09:09:33 +0000597 VNInfo *ValNo = SrcLR->valno;
598 // If other defs can reach uses of this def, then it's not safe to perform
Lang Hames857c4e02009-06-17 21:01:20 +0000599 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
600 // tested?
601 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
602 ValNo->isUnused() || ValNo->hasPHIKill())
Evan Chengcd047082008-08-30 09:09:33 +0000603 return false;
604 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
605 const TargetInstrDesc &TID = DefMI->getDesc();
606 if (!TID.isAsCheapAsAMove())
607 return false;
Evan Cheng54801f782009-02-05 22:24:17 +0000608 if (!DefMI->getDesc().isRematerializable() ||
609 !tii_->isTriviallyReMaterializable(DefMI))
610 return false;
Evan Chengcd047082008-08-30 09:09:33 +0000611 bool SawStore = false;
612 if (!DefMI->isSafeToMove(tii_, SawStore))
613 return false;
Evan Cheng5ad14722009-07-14 00:51:06 +0000614 if (TID.getNumDefs() != 1)
615 return false;
616 // Make sure the copy destination register class fits the instruction
617 // definition register class. The mismatch can happen as a result of earlier
618 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
619 const TargetRegisterClass *RC = getInstrOperandRegClass(tri_, TID, 0);
620 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
621 if (mri_->getRegClass(DstReg) != RC)
622 return false;
623 } else if (!RC->contains(DstReg))
624 return false;
Evan Chengcd047082008-08-30 09:09:33 +0000625
626 unsigned DefIdx = li_->getDefIndex(CopyIdx);
627 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
628 DLR->valno->copy = NULL;
Evan Cheng195cd3a2008-10-13 18:35:52 +0000629 // Don't forget to update sub-register intervals.
630 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
631 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
632 if (!li_->hasInterval(*SR))
633 continue;
634 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
635 if (DLR && DLR->valno->copy == CopyMI)
636 DLR->valno->copy = NULL;
637 }
638 }
Evan Chengcd047082008-08-30 09:09:33 +0000639
Evan Cheng961154f2009-02-05 08:45:04 +0000640 // If copy kills the source register, find the last use and propagate
641 // kill.
Lang Hames9c992f12009-05-11 23:14:13 +0000642 bool checkForDeadDef = false;
Evan Chengcd047082008-08-30 09:09:33 +0000643 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng961154f2009-02-05 08:45:04 +0000644 if (CopyMI->killsRegister(SrcInt.reg))
Lang Hames9c992f12009-05-11 23:14:13 +0000645 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
646 checkForDeadDef = true;
647 }
Evan Cheng961154f2009-02-05 08:45:04 +0000648
Dan Gohman3afda6e2008-10-21 03:24:31 +0000649 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
Evan Chengcd047082008-08-30 09:09:33 +0000650 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
651 MachineInstr *NewMI = prior(MII);
Lang Hames9c992f12009-05-11 23:14:13 +0000652
653 if (checkForDeadDef) {
Evan Cheng67fcf562009-06-16 07:12:58 +0000654 // PR4090 fix: Trim interval failed because there was no use of the
655 // source interval in this MBB. If the def is in this MBB too then we
656 // should mark it dead:
657 if (DefMI->getParent() == MBB) {
658 DefMI->addRegisterDead(SrcInt.reg, tri_);
659 SrcLR->end = SrcLR->start + 1;
660 }
Lang Hames9c992f12009-05-11 23:14:13 +0000661 }
662
Chris Lattner99cbdff2008-10-11 23:59:03 +0000663 // CopyMI may have implicit operands, transfer them over to the newly
Evan Chengcd047082008-08-30 09:09:33 +0000664 // rematerialized instruction. And update implicit def interval valnos.
665 for (unsigned i = CopyMI->getDesc().getNumOperands(),
666 e = CopyMI->getNumOperands(); i != e; ++i) {
667 MachineOperand &MO = CopyMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000668 if (MO.isReg() && MO.isImplicit())
Evan Chengcd047082008-08-30 09:09:33 +0000669 NewMI->addOperand(MO);
Owen Anderson369e9872008-09-10 20:41:13 +0000670 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
Evan Chengcd047082008-08-30 09:09:33 +0000671 unsigned Reg = MO.getReg();
672 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
673 if (DLR && DLR->valno->copy == CopyMI)
674 DLR->valno->copy = NULL;
675 }
676 }
677
678 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
Evan Cheng67fcf562009-06-16 07:12:58 +0000679 CopyMI->eraseFromParent();
Evan Chengcd047082008-08-30 09:09:33 +0000680 ReMatCopies.insert(CopyMI);
Evan Cheng20580a12008-09-19 17:38:47 +0000681 ReMatDefs.insert(DefMI);
Evan Chengcd047082008-08-30 09:09:33 +0000682 ++NumReMats;
683 return true;
684}
685
Evan Cheng8fc9a102007-11-06 08:52:21 +0000686/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
687///
688bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
Evan Cheng7e073ba2008-04-09 20:57:25 +0000689 unsigned DstReg) const {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000690 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000691 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000692 if (!L)
693 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000694 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000695 return false;
696
Evan Cheng8fc9a102007-11-06 08:52:21 +0000697 LiveInterval &LI = li_->getInterval(DstReg);
698 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
699 LiveInterval::const_iterator DstLR =
700 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
701 if (DstLR == LI.end())
702 return false;
Lang Hamesffd13262009-07-09 03:57:02 +0000703 if (DstLR->valno->kills.size() == 1 && DstLR->valno->kills[0].isPHIKill)
Evan Cheng8fc9a102007-11-06 08:52:21 +0000704 return true;
705 return false;
706}
707
Evan Chengc8d044e2008-02-15 18:24:29 +0000708/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
709/// update the subregister number if it is not zero. If DstReg is a
710/// physical register and the existing subregister number of the def / use
711/// being updated is not zero, make sure to set it to the correct physical
712/// subregister.
713void
714SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
715 unsigned SubIdx) {
716 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
717 if (DstIsPhys && SubIdx) {
718 // Figure out the real physical register we are updating with.
719 DstReg = tri_->getSubReg(DstReg, SubIdx);
720 SubIdx = 0;
721 }
722
723 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
724 E = mri_->reg_end(); I != E; ) {
725 MachineOperand &O = I.getOperand();
Evan Cheng70366b92008-03-21 19:09:30 +0000726 MachineInstr *UseMI = &*I;
Evan Chengc8d044e2008-02-15 18:24:29 +0000727 ++I;
Evan Cheng621d1572008-04-17 00:06:42 +0000728 unsigned OldSubIdx = O.getSubReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000729 if (DstIsPhys) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000730 unsigned UseDstReg = DstReg;
Evan Cheng621d1572008-04-17 00:06:42 +0000731 if (OldSubIdx)
732 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
Evan Chengcd047082008-08-30 09:09:33 +0000733
Evan Cheng04ee5a12009-01-20 19:12:24 +0000734 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
735 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
736 CopySrcSubIdx, CopyDstSubIdx) &&
Evan Chengcd047082008-08-30 09:09:33 +0000737 CopySrcReg != CopyDstReg &&
738 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
739 // If the use is a copy and it won't be coalesced away, and its source
740 // is defined by a trivial computation, try to rematerialize it instead.
741 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
742 continue;
743 }
744
Evan Chengc8d044e2008-02-15 18:24:29 +0000745 O.setReg(UseDstReg);
746 O.setSubReg(0);
Evan Chengee9e1b02008-09-12 18:13:14 +0000747 continue;
748 }
749
750 // Sub-register indexes goes from small to large. e.g.
751 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
752 // EAX: 1 -> AL, 2 -> AX
753 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
754 // sub-register 2 is also AX.
755 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
756 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
757 else if (SubIdx)
758 O.setSubReg(SubIdx);
759 // Remove would-be duplicated kill marker.
760 if (O.isKill() && UseMI->killsRegister(DstReg))
761 O.setIsKill(false);
762 O.setReg(DstReg);
763
764 // After updating the operand, check if the machine instruction has
765 // become a copy. If so, update its val# information.
Evan Cheng81909b72009-06-22 20:49:32 +0000766 if (JoinedCopies.count(UseMI))
767 continue;
768
Evan Chengee9e1b02008-09-12 18:13:14 +0000769 const TargetInstrDesc &TID = UseMI->getDesc();
Evan Cheng04ee5a12009-01-20 19:12:24 +0000770 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
Evan Chengee9e1b02008-09-12 18:13:14 +0000771 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +0000772 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
773 CopySrcSubIdx, CopyDstSubIdx) &&
Evan Cheng870e4be2008-09-17 18:36:25 +0000774 CopySrcReg != CopyDstReg &&
775 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
776 allocatableRegs_[CopyDstReg])) {
Evan Chengee9e1b02008-09-12 18:13:14 +0000777 LiveInterval &LI = li_->getInterval(CopyDstReg);
778 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
Evan Cheng81909b72009-06-22 20:49:32 +0000779 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
780 if (DLR->valno->def == DefIdx)
781 DLR->valno->copy = UseMI;
782 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000783 }
784 }
785}
786
Evan Cheng7e073ba2008-04-09 20:57:25 +0000787/// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
788/// registers due to insert_subreg coalescing. e.g.
789/// r1024 = op
790/// r1025 = implicit_def
791/// r1025 = insert_subreg r1025, r1024
792/// = op r1025
793/// =>
794/// r1025 = op
795/// r1025 = implicit_def
796/// r1025 = insert_subreg r1025, r1025
797/// = op r1025
798void
799SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
800 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
801 E = mri_->reg_end(); I != E; ) {
802 MachineOperand &O = I.getOperand();
803 MachineInstr *DefMI = &*I;
804 ++I;
805 if (!O.isDef())
806 continue;
807 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
808 continue;
809 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
810 continue;
811 li_->RemoveMachineInstrFromMaps(DefMI);
812 DefMI->eraseFromParent();
813 }
814}
815
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000816/// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
817/// due to live range lengthening as the result of coalescing.
818void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
819 LiveInterval &LI) {
820 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
821 UE = mri_->use_end(); UI != UE; ++UI) {
822 MachineOperand &UseMO = UI.getOperand();
823 if (UseMO.isKill()) {
824 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000825 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
Evan Chengff7a3e52008-04-16 18:48:43 +0000826 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
Evan Cheng068b4ff2008-08-05 07:10:38 +0000827 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000828 UseMO.setIsKill(false);
829 }
830 }
831}
832
Evan Cheng3c88d742008-03-18 08:26:47 +0000833/// removeIntervalIfEmpty - Check if the live interval of a physical register
834/// is empty, if so remove it and also remove the empty intervals of its
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000835/// sub-registers. Return true if live interval is removed.
836static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
Evan Cheng3c88d742008-03-18 08:26:47 +0000837 const TargetRegisterInfo *tri_) {
838 if (li.empty()) {
Evan Cheng3c88d742008-03-18 08:26:47 +0000839 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
840 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
841 if (!li_->hasInterval(*SR))
842 continue;
843 LiveInterval &sli = li_->getInterval(*SR);
844 if (sli.empty())
845 li_->removeInterval(*SR);
846 }
Evan Chengd94950c2008-04-16 01:22:28 +0000847 li_->removeInterval(li.reg);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000848 return true;
Evan Cheng3c88d742008-03-18 08:26:47 +0000849 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000850 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000851}
852
853/// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000854/// Return true if live interval is removed.
855bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
Evan Chengecb2a8b2008-03-05 22:09:42 +0000856 MachineInstr *CopyMI) {
857 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
858 LiveInterval::iterator MLR =
859 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
Evan Cheng3c88d742008-03-18 08:26:47 +0000860 if (MLR == li.end())
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000861 return false; // Already removed by ShortenDeadCopySrcLiveRange.
Evan Chengecb2a8b2008-03-05 22:09:42 +0000862 unsigned RemoveStart = MLR->start;
863 unsigned RemoveEnd = MLR->end;
Evan Cheng3c88d742008-03-18 08:26:47 +0000864 // Remove the liverange that's defined by this.
865 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
866 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000867 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000868 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000869 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000870}
871
Evan Chengb3990d52008-10-27 23:21:01 +0000872/// RemoveDeadDef - If a def of a live interval is now determined dead, remove
873/// the val# it defines. If the live interval becomes empty, remove it as well.
874bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
875 MachineInstr *DefMI) {
876 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
877 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
878 if (DefIdx != MLR->valno->def)
879 return false;
880 li.removeValNo(MLR->valno);
881 return removeIntervalIfEmpty(li, li_, tri_);
882}
883
Evan Cheng0c284322008-03-26 20:15:49 +0000884/// PropagateDeadness - Propagate the dead marker to the instruction which
885/// defines the val#.
886static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
887 unsigned &LRStart, LiveIntervals *li_,
888 const TargetRegisterInfo* tri_) {
889 MachineInstr *DefMI =
890 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
891 if (DefMI && DefMI != CopyMI) {
892 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
893 if (DeadIdx != -1) {
894 DefMI->getOperand(DeadIdx).setIsDead();
895 // A dead def should have a single cycle interval.
896 ++LRStart;
897 }
898 }
899}
900
Bill Wendlingf2317782008-04-17 05:20:39 +0000901/// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
902/// extended by a dead copy. Mark the last use (if any) of the val# as kill as
903/// ends the live range there. If there isn't another use, then this live range
904/// is dead. Return true if live interval is removed.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000905bool
Evan Cheng3c88d742008-03-18 08:26:47 +0000906SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
907 MachineInstr *CopyMI) {
908 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
909 if (CopyIdx == 0) {
910 // FIXME: special case: function live in. It can be a general case if the
911 // first instruction index starts at > 0 value.
912 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
913 // Live-in to the function but dead. Remove it from entry live-in set.
Evan Chenga971dbd2008-04-24 09:06:33 +0000914 if (mf_->begin()->isLiveIn(li.reg))
915 mf_->begin()->removeLiveIn(li.reg);
Evan Chengff7a3e52008-04-16 18:48:43 +0000916 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000917 removeRange(li, LR->start, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000918 return removeIntervalIfEmpty(li, li_, tri_);
Evan Cheng3c88d742008-03-18 08:26:47 +0000919 }
920
921 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
922 if (LR == li.end())
923 // Livein but defined by a phi.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000924 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000925
926 unsigned RemoveStart = LR->start;
927 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
928 if (LR->end > RemoveEnd)
929 // More uses past this copy? Nothing to do.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000930 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000931
Evan Cheng961154f2009-02-05 08:45:04 +0000932 // If there is a last use in the same bb, we can't remove the live range.
933 // Shorten the live interval and return.
Evan Cheng190424e2009-02-09 08:37:45 +0000934 MachineBasicBlock *CopyMBB = CopyMI->getParent();
935 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000936 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000937
Evan Cheng190424e2009-02-09 08:37:45 +0000938 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
939 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
940 // If the live range starts in another mbb and the copy mbb is not a fall
941 // through mbb, then we can only cut the range from the beginning of the
942 // copy mbb.
943 RemoveStart = li_->getMBBStartIdx(CopyMBB) + 1;
944
Evan Cheng77fde2c2009-02-08 07:48:37 +0000945 if (LR->valno->def == RemoveStart) {
946 // If the def MI defines the val# and this copy is the only kill of the
947 // val#, then propagate the dead marker.
Evan Cheng190424e2009-02-09 08:37:45 +0000948 if (li.isOnlyLROfValNo(LR)) {
Evan Cheng77fde2c2009-02-08 07:48:37 +0000949 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
950 ++numDeadValNo;
Evan Chengf18134a2009-02-08 08:00:36 +0000951 }
Evan Cheng190424e2009-02-09 08:37:45 +0000952 if (li.isKill(LR->valno, RemoveEnd))
953 li.removeKill(LR->valno, RemoveEnd);
Evan Cheng77fde2c2009-02-08 07:48:37 +0000954 }
Evan Cheng0c284322008-03-26 20:15:49 +0000955
Evan Cheng190424e2009-02-09 08:37:45 +0000956 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000957 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000958}
959
Evan Cheng7e073ba2008-04-09 20:57:25 +0000960/// CanCoalesceWithImpDef - Returns true if the specified copy instruction
961/// from an implicit def to another register can be coalesced away.
962bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
963 LiveInterval &li,
964 LiveInterval &ImpLi) const{
965 if (!CopyMI->killsRegister(ImpLi.reg))
966 return false;
967 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
968 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
969 if (LR == li.end())
970 return false;
Lang Hames857c4e02009-06-17 21:01:20 +0000971 if (LR->valno->hasPHIKill())
Evan Cheng7e073ba2008-04-09 20:57:25 +0000972 return false;
973 if (LR->valno->def != CopyIdx)
974 return false;
975 // Make sure all of val# uses are copies.
976 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
977 UE = mri_->use_end(); UI != UE;) {
978 MachineInstr *UseMI = &*UI;
979 ++UI;
980 if (JoinedCopies.count(UseMI))
981 continue;
982 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
983 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000984 if (ULR == li.end() || ULR->valno != LR->valno)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000985 continue;
986 // If the use is not a use, then it's not safe to coalesce the move.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000987 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
988 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +0000989 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
990 UseMI->getOperand(1).getReg() == li.reg)
991 continue;
992 return false;
993 }
994 }
995 return true;
996}
997
998
Evan Cheng7b113652009-06-16 07:15:05 +0000999/// TurnCopiesFromValNoToImpDefs - The specified value# is defined by an
1000/// implicit_def and it is being removed. Turn all copies from this value#
1001/// into implicit_defs.
1002void SimpleRegisterCoalescing::TurnCopiesFromValNoToImpDefs(LiveInterval &li,
1003 VNInfo *VNI) {
Evan Chengd77d4f92008-05-28 17:40:10 +00001004 SmallVector<MachineInstr*, 4> ImpDefs;
Evan Chengd2012d02008-04-10 23:48:35 +00001005 MachineOperand *LastUse = NULL;
1006 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
1007 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
1008 RE = mri_->reg_end(); RI != RE;) {
1009 MachineOperand *MO = &RI.getOperand();
1010 MachineInstr *MI = &*RI;
1011 ++RI;
1012 if (MO->isDef()) {
Evan Cheng67fcf562009-06-16 07:12:58 +00001013 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd77d4f92008-05-28 17:40:10 +00001014 ImpDefs.push_back(MI);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001015 continue;
Evan Chengd2012d02008-04-10 23:48:35 +00001016 }
1017 if (JoinedCopies.count(MI))
1018 continue;
1019 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
Evan Cheng7e073ba2008-04-09 20:57:25 +00001020 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +00001021 if (ULR == li.end() || ULR->valno != VNI)
Evan Cheng7e073ba2008-04-09 20:57:25 +00001022 continue;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001023 // If the use is a copy, turn it into an identity copy.
Evan Cheng04ee5a12009-01-20 19:12:24 +00001024 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1025 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1026 SrcReg == li.reg) {
Evan Cheng67fcf562009-06-16 07:12:58 +00001027 // Change it to an implicit_def.
1028 MI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
1029 for (int i = MI->getNumOperands() - 1, e = 0; i > e; --i)
1030 MI->RemoveOperand(i);
1031 // It's no longer a copy, update the valno it defines.
1032 unsigned DefIdx = li_->getDefIndex(UseIdx);
1033 LiveInterval &DstInt = li_->getInterval(DstReg);
1034 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(DefIdx);
1035 assert(DLR != DstInt.end() && "Live range not found!");
1036 assert(DLR->valno->copy == MI);
1037 DLR->valno->copy = NULL;
1038 ReMatCopies.insert(MI);
Evan Chengd2012d02008-04-10 23:48:35 +00001039 } else if (UseIdx > LastUseIdx) {
1040 LastUseIdx = UseIdx;
1041 LastUse = MO;
Evan Cheng172b70c2008-04-10 18:38:47 +00001042 }
Evan Chengd2012d02008-04-10 23:48:35 +00001043 }
Evan Cheng58207f12009-02-22 08:35:56 +00001044 if (LastUse) {
Evan Chengd2012d02008-04-10 23:48:35 +00001045 LastUse->setIsKill();
Lang Hamesffd13262009-07-09 03:57:02 +00001046 li.addKill(VNI, LastUseIdx+1, false);
Evan Cheng58207f12009-02-22 08:35:56 +00001047 } else {
Evan Chengd77d4f92008-05-28 17:40:10 +00001048 // Remove dead implicit_def's.
1049 while (!ImpDefs.empty()) {
1050 MachineInstr *ImpDef = ImpDefs.back();
1051 ImpDefs.pop_back();
1052 li_->RemoveMachineInstrFromMaps(ImpDef);
1053 ImpDef->eraseFromParent();
1054 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001055 }
1056}
1057
Evan Cheng0490dcb2009-04-30 18:39:57 +00001058/// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1059/// a virtual destination register with physical source register.
1060bool
1061SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1062 MachineBasicBlock *CopyMBB,
1063 LiveInterval &DstInt,
1064 LiveInterval &SrcInt) {
1065 // If the virtual register live interval is long but it has low use desity,
1066 // do not join them, instead mark the physical register as its allocation
1067 // preference.
1068 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1069 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1070 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1071 if (Length > Threshold &&
1072 (((float)std::distance(mri_->use_begin(DstInt.reg),
1073 mri_->use_end()) / Length) < (1.0 / Threshold)))
1074 return false;
1075
1076 // If the virtual register live interval extends into a loop, turn down
1077 // aggressiveness.
1078 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1079 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1080 if (!L) {
1081 // Let's see if the virtual register live interval extends into the loop.
1082 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1083 assert(DLR != DstInt.end() && "Live range not found!");
1084 DLR = DstInt.FindLiveRangeContaining(DLR->end+1);
1085 if (DLR != DstInt.end()) {
1086 CopyMBB = li_->getMBBFromIndex(DLR->start);
1087 L = loopInfo->getLoopFor(CopyMBB);
1088 }
1089 }
1090
1091 if (!L || Length <= Threshold)
1092 return true;
1093
1094 unsigned UseIdx = li_->getUseIndex(CopyIdx);
1095 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1096 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1097 if (loopInfo->getLoopFor(SMBB) != L) {
1098 if (!loopInfo->isLoopHeader(CopyMBB))
1099 return false;
1100 // If vr's live interval extends pass the loop header, do not join.
1101 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1102 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1103 MachineBasicBlock *SuccMBB = *SI;
1104 if (SuccMBB == CopyMBB)
1105 continue;
1106 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1107 li_->getMBBEndIdx(SuccMBB)+1))
1108 return false;
1109 }
1110 }
1111 return true;
1112}
1113
1114/// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1115/// copy from a virtual source register to a physical destination register.
1116bool
1117SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1118 MachineBasicBlock *CopyMBB,
1119 LiveInterval &DstInt,
1120 LiveInterval &SrcInt) {
1121 // If the virtual register live interval is long but it has low use desity,
1122 // do not join them, instead mark the physical register as its allocation
1123 // preference.
1124 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1125 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1126 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1127 if (Length > Threshold &&
1128 (((float)std::distance(mri_->use_begin(SrcInt.reg),
1129 mri_->use_end()) / Length) < (1.0 / Threshold)))
1130 return false;
1131
1132 if (SrcInt.empty())
1133 // Must be implicit_def.
1134 return false;
1135
1136 // If the virtual register live interval is defined or cross a loop, turn
1137 // down aggressiveness.
1138 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1139 unsigned UseIdx = li_->getUseIndex(CopyIdx);
1140 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1141 assert(SLR != SrcInt.end() && "Live range not found!");
1142 SLR = SrcInt.FindLiveRangeContaining(SLR->start-1);
1143 if (SLR == SrcInt.end())
1144 return true;
1145 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1146 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1147
1148 if (!L || Length <= Threshold)
1149 return true;
1150
1151 if (loopInfo->getLoopFor(CopyMBB) != L) {
1152 if (SMBB != L->getLoopLatch())
1153 return false;
1154 // If vr's live interval is extended from before the loop latch, do not
1155 // join.
1156 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1157 PE = SMBB->pred_end(); PI != PE; ++PI) {
1158 MachineBasicBlock *PredMBB = *PI;
1159 if (PredMBB == SMBB)
1160 continue;
1161 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1162 li_->getMBBEndIdx(PredMBB)+1))
1163 return false;
1164 }
1165 }
1166 return true;
1167}
1168
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001169/// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1170/// two virtual registers from different register classes.
Evan Chenge00f5de2008-06-19 01:39:21 +00001171bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001172SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1173 unsigned SmallReg,
1174 unsigned Threshold) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001175 // Then make sure the intervals are *short*.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001176 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1177 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1178 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1179 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1180 if (SmallSize > Threshold || LargeSize > Threshold)
1181 if ((float)std::distance(mri_->use_begin(SmallReg),
1182 mri_->use_end()) / SmallSize <
1183 (float)std::distance(mri_->use_begin(LargeReg),
1184 mri_->use_end()) / LargeSize)
1185 return false;
1186 return true;
Evan Chenge00f5de2008-06-19 01:39:21 +00001187}
1188
Evan Cheng8db86682008-09-11 20:07:10 +00001189/// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1190/// register with a physical register, check if any of the virtual register
1191/// operand is a sub-register use or def. If so, make sure it won't result
1192/// in an illegal extract_subreg or insert_subreg instruction. e.g.
1193/// vr1024 = extract_subreg vr1025, 1
1194/// ...
1195/// vr1024 = mov8rr AH
1196/// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1197/// AH does not have a super-reg whose sub-register 1 is AH.
1198bool
1199SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1200 unsigned VirtReg,
1201 unsigned PhysReg) {
1202 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1203 E = mri_->reg_end(); I != E; ++I) {
1204 MachineOperand &O = I.getOperand();
1205 MachineInstr *MI = &*I;
1206 if (MI == CopyMI || JoinedCopies.count(MI))
1207 continue;
1208 unsigned SubIdx = O.getSubReg();
1209 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1210 return true;
1211 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1212 SubIdx = MI->getOperand(2).getImm();
1213 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1214 return true;
1215 if (O.isDef()) {
1216 unsigned SrcReg = MI->getOperand(1).getReg();
1217 const TargetRegisterClass *RC =
1218 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1219 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1220 : mri_->getRegClass(SrcReg);
Evan Cheng8a8a0df2009-04-28 18:29:27 +00001221 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
Evan Cheng8db86682008-09-11 20:07:10 +00001222 return true;
1223 }
1224 }
Dan Gohman97121ba2009-04-08 00:15:30 +00001225 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1226 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
Evan Cheng8db86682008-09-11 20:07:10 +00001227 SubIdx = MI->getOperand(3).getImm();
1228 if (VirtReg == MI->getOperand(0).getReg()) {
1229 if (!tri_->getSubReg(PhysReg, SubIdx))
1230 return true;
1231 } else {
1232 unsigned DstReg = MI->getOperand(0).getReg();
1233 const TargetRegisterClass *RC =
1234 TargetRegisterInfo::isPhysicalRegister(DstReg)
1235 ? tri_->getPhysicalRegisterRegClass(DstReg)
1236 : mri_->getRegClass(DstReg);
Evan Cheng8a8a0df2009-04-28 18:29:27 +00001237 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
Evan Cheng8db86682008-09-11 20:07:10 +00001238 return true;
1239 }
1240 }
1241 }
1242 return false;
1243}
1244
Evan Chenge00f5de2008-06-19 01:39:21 +00001245
Evan Chenge08eb9c2009-01-20 06:44:16 +00001246/// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1247/// an extract_subreg where dst is a physical register, e.g.
1248/// cl = EXTRACT_SUBREG reg1024, 1
1249bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001250SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1251 unsigned SrcReg, unsigned SubIdx,
1252 unsigned &RealDstReg) {
Evan Chenge08eb9c2009-01-20 06:44:16 +00001253 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
Evan Cheng8a8a0df2009-04-28 18:29:27 +00001254 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
Evan Chenge08eb9c2009-01-20 06:44:16 +00001255 assert(RealDstReg && "Invalid extract_subreg instruction!");
1256
1257 // For this type of EXTRACT_SUBREG, conservatively
1258 // check if the live interval of the source register interfere with the
1259 // actual super physical register we are trying to coalesce with.
1260 LiveInterval &RHS = li_->getInterval(SrcReg);
1261 if (li_->hasInterval(RealDstReg) &&
1262 RHS.overlaps(li_->getInterval(RealDstReg))) {
1263 DOUT << "Interfere with register ";
1264 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
1265 return false; // Not coalescable
1266 }
1267 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1268 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1269 DOUT << "Interfere with sub-register ";
1270 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1271 return false; // Not coalescable
1272 }
1273 return true;
1274}
1275
1276/// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1277/// an insert_subreg where src is a physical register, e.g.
1278/// reg1024 = INSERT_SUBREG reg1024, c1, 0
1279bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001280SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1281 unsigned SrcReg, unsigned SubIdx,
1282 unsigned &RealSrcReg) {
Evan Chenge08eb9c2009-01-20 06:44:16 +00001283 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
Evan Cheng8a8a0df2009-04-28 18:29:27 +00001284 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
Evan Chenge08eb9c2009-01-20 06:44:16 +00001285 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1286
1287 LiveInterval &RHS = li_->getInterval(DstReg);
1288 if (li_->hasInterval(RealSrcReg) &&
1289 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1290 DOUT << "Interfere with register ";
1291 DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_));
1292 return false; // Not coalescable
1293 }
1294 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1295 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1296 DOUT << "Interfere with sub-register ";
1297 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1298 return false; // Not coalescable
1299 }
1300 return true;
1301}
1302
Evan Cheng90f95f82009-06-14 20:22:55 +00001303/// getRegAllocPreference - Return register allocation preference register.
1304///
1305static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1306 MachineRegisterInfo *MRI,
1307 const TargetRegisterInfo *TRI) {
1308 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1309 return 0;
Evan Cheng358dec52009-06-15 08:28:29 +00001310 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1311 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
Evan Cheng90f95f82009-06-14 20:22:55 +00001312}
1313
David Greene25133302007-06-08 17:18:56 +00001314/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1315/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +00001316/// if the copy was successfully coalesced away. If it is not currently
1317/// possible to coalesce this interval, but it may be possible if other
1318/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng70071432008-02-13 03:01:43 +00001319bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001320 MachineInstr *CopyMI = TheCopy.MI;
1321
1322 Again = false;
Evan Chengcd047082008-08-30 09:09:33 +00001323 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
Evan Cheng8fc9a102007-11-06 08:52:21 +00001324 return false; // Already done.
1325
David Greene25133302007-06-08 17:18:56 +00001326 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1327
Jakob Stoklund Olesen08e791f2009-04-28 16:34:35 +00001328 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
Evan Chengc8d044e2008-02-15 18:24:29 +00001329 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001330 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
Dan Gohman97121ba2009-04-08 00:15:30 +00001331 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
Evan Chengc8d044e2008-02-15 18:24:29 +00001332 unsigned SubIdx = 0;
1333 if (isExtSubReg) {
Jakob Stoklund Olesen08e791f2009-04-28 16:34:35 +00001334 DstReg = CopyMI->getOperand(0).getReg();
1335 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1336 SrcReg = CopyMI->getOperand(1).getReg();
1337 SrcSubIdx = CopyMI->getOperand(2).getImm();
Dan Gohman97121ba2009-04-08 00:15:30 +00001338 } else if (isInsSubReg || isSubRegToReg) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001339 if (CopyMI->getOperand(2).getSubReg()) {
1340 DOUT << "\tSource of insert_subreg is already coalesced "
1341 << "to another register.\n";
1342 return false; // Not coalescable.
1343 }
Jakob Stoklund Olesen08e791f2009-04-28 16:34:35 +00001344 DstReg = CopyMI->getOperand(0).getReg();
1345 DstSubIdx = CopyMI->getOperand(3).getImm();
1346 SrcReg = CopyMI->getOperand(2).getReg();
Evan Cheng04ee5a12009-01-20 19:12:24 +00001347 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
Torok Edwinc25e7582009-07-11 20:10:48 +00001348 LLVM_UNREACHABLE("Unrecognized copy instruction!");
Evan Cheng70071432008-02-13 03:01:43 +00001349 }
1350
David Greene25133302007-06-08 17:18:56 +00001351 // If they are already joined we continue.
Evan Chengc8d044e2008-02-15 18:24:29 +00001352 if (SrcReg == DstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001353 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001354 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001355 }
1356
Evan Chengc8d044e2008-02-15 18:24:29 +00001357 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1358 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
David Greene25133302007-06-08 17:18:56 +00001359
1360 // If they are both physical registers, we cannot join them.
1361 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001362 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001363 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001364 }
1365
1366 // We only join virtual registers with allocatable physical registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001367 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
David Greene25133302007-06-08 17:18:56 +00001368 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001369 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001370 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001371 if (DstIsPhys && !allocatableRegs_[DstReg]) {
David Greene25133302007-06-08 17:18:56 +00001372 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001373 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +00001374 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001375
Jakob Stoklund Olesen08e791f2009-04-28 16:34:35 +00001376 // Check that a physical source register is compatible with dst regclass
1377 if (SrcIsPhys) {
1378 unsigned SrcSubReg = SrcSubIdx ?
1379 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1380 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1381 const TargetRegisterClass *DstSubRC = DstRC;
1382 if (DstSubIdx)
1383 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1384 assert(DstSubRC && "Illegal subregister index");
1385 if (!DstSubRC->contains(SrcSubReg)) {
1386 DOUT << "\tIncompatible destination regclass: "
1387 << tri_->getName(SrcSubReg) << " not in " << DstSubRC->getName()
1388 << ".\n";
1389 return false; // Not coalescable.
1390 }
1391 }
1392
1393 // Check that a physical dst register is compatible with source regclass
1394 if (DstIsPhys) {
1395 unsigned DstSubReg = DstSubIdx ?
1396 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1397 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1398 const TargetRegisterClass *SrcSubRC = SrcRC;
1399 if (SrcSubIdx)
1400 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1401 assert(SrcSubRC && "Illegal subregister index");
1402 if (!SrcSubRC->contains(DstReg)) {
1403 DOUT << "\tIncompatible source regclass: "
1404 << tri_->getName(DstSubReg) << " not in " << SrcSubRC->getName()
1405 << ".\n";
1406 return false; // Not coalescable.
1407 }
1408 }
1409
Evan Chenge00f5de2008-06-19 01:39:21 +00001410 // Should be non-null only when coalescing to a sub-register class.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001411 bool CrossRC = false;
1412 const TargetRegisterClass *NewRC = NULL;
Evan Chenge00f5de2008-06-19 01:39:21 +00001413 MachineBasicBlock *CopyMBB = CopyMI->getParent();
Evan Cheng32dfbea2007-10-12 08:50:34 +00001414 unsigned RealDstReg = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001415 unsigned RealSrcReg = 0;
Dan Gohman97121ba2009-04-08 00:15:30 +00001416 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001417 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1418 if (SrcIsPhys && isExtSubReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001419 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1420 // coalesced with AX.
Evan Cheng621d1572008-04-17 00:06:42 +00001421 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001422 if (DstSubIdx) {
1423 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1424 // coalesced to a larger register so the subreg indices cancel out.
1425 if (DstSubIdx != SubIdx) {
1426 DOUT << "\t Sub-register indices mismatch.\n";
1427 return false; // Not coalescable.
1428 }
1429 } else
Evan Cheng621d1572008-04-17 00:06:42 +00001430 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +00001431 SubIdx = 0;
Dan Gohman97121ba2009-04-08 00:15:30 +00001432 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001433 // EAX = INSERT_SUBREG EAX, r1024, 0
Evan Cheng621d1572008-04-17 00:06:42 +00001434 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +00001435 if (SrcSubIdx) {
1436 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1437 // coalesced to a larger register so the subreg indices cancel out.
1438 if (SrcSubIdx != SubIdx) {
1439 DOUT << "\t Sub-register indices mismatch.\n";
1440 return false; // Not coalescable.
1441 }
1442 } else
1443 DstReg = tri_->getSubReg(DstReg, SubIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001444 SubIdx = 0;
Dan Gohman97121ba2009-04-08 00:15:30 +00001445 } else if ((DstIsPhys && isExtSubReg) ||
1446 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1447 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001448 DOUT << "\tSrc of extract_subreg already coalesced with reg"
1449 << " of a super-class.\n";
1450 return false; // Not coalescable.
1451 }
1452
Evan Cheng7e073ba2008-04-09 20:57:25 +00001453 if (isExtSubReg) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001454 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
Evan Cheng0547bab2007-11-01 06:22:48 +00001455 return false; // Not coalescable
Evan Chenge08eb9c2009-01-20 06:44:16 +00001456 } else {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001457 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
Evan Chenge08eb9c2009-01-20 06:44:16 +00001458 return false; // Not coalescable
1459 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001460 SubIdx = 0;
Evan Cheng0547bab2007-11-01 06:22:48 +00001461 } else {
Evan Cheng639f4932008-04-17 07:58:04 +00001462 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1463 : CopyMI->getOperand(2).getSubReg();
1464 if (OldSubIdx) {
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001465 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
Evan Cheng639f4932008-04-17 07:58:04 +00001466 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1467 // coalesced to a larger register so the subreg indices cancel out.
Evan Cheng8509fcf2008-04-29 01:41:44 +00001468 // Also check if the other larger register is of the same register
1469 // class as the would be resulting register.
Evan Cheng639f4932008-04-17 07:58:04 +00001470 SubIdx = 0;
1471 else {
1472 DOUT << "\t Sub-register indices mismatch.\n";
1473 return false; // Not coalescable.
1474 }
1475 }
1476 if (SubIdx) {
1477 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1478 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001479 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1480 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1481 Again = true; // May be possible to coalesce later.
1482 return false;
Evan Cheng0547bab2007-11-01 06:22:48 +00001483 }
1484 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001485 }
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001486 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1487 if (!CrossClassJoin)
1488 return false;
1489 CrossRC = true;
1490
1491 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
Evan Chengc8d044e2008-02-15 18:24:29 +00001492 // with another? If it's the resulting destination register, then
1493 // the subidx must be propagated to uses (but only those defined
1494 // by the EXTRACT_SUBREG). If it's being coalesced into another
1495 // register, it should be safe because register is assumed to have
1496 // the register class of the super-register.
1497
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001498 // Process moves where one of the registers have a sub-register index.
1499 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001500 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
Dan Gohman97121ba2009-04-08 00:15:30 +00001501 SubIdx = DstMO->getSubReg();
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001502 if (SubIdx) {
Dan Gohman97121ba2009-04-08 00:15:30 +00001503 if (SrcMO->getSubReg())
1504 // FIXME: can we handle this?
1505 return false;
1506 // This is not an insert_subreg but it looks like one.
Evan Chengaa809fb2009-04-23 20:39:31 +00001507 // e.g. %reg1024:4 = MOV32rr %EAX
Dan Gohman97121ba2009-04-08 00:15:30 +00001508 isInsSubReg = true;
1509 if (SrcIsPhys) {
1510 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001511 return false; // Not coalescable
1512 SubIdx = 0;
1513 }
Dan Gohman97121ba2009-04-08 00:15:30 +00001514 } else {
1515 SubIdx = SrcMO->getSubReg();
1516 if (SubIdx) {
1517 // This is not a extract_subreg but it looks like one.
Evan Chengaa809fb2009-04-23 20:39:31 +00001518 // e.g. %cl = MOV16rr %reg1024:1
Dan Gohman97121ba2009-04-08 00:15:30 +00001519 isExtSubReg = true;
1520 if (DstIsPhys) {
1521 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1522 return false; // Not coalescable
1523 SubIdx = 0;
1524 }
1525 }
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001526 }
1527
1528 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1529 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1530 unsigned LargeReg = SrcReg;
1531 unsigned SmallReg = DstReg;
1532 unsigned Limit = 0;
1533
1534 // Now determine the register class of the joined register.
1535 if (isExtSubReg) {
1536 if (SubIdx && DstRC && DstRC->isASubClass()) {
1537 // This is a move to a sub-register class. However, the source is a
1538 // sub-register of a larger register class. We don't know what should
1539 // the register class be. FIXME.
1540 Again = true;
1541 return false;
1542 }
1543 Limit = allocatableRCRegs_[DstRC].count();
Evan Chengc2cee142009-04-23 20:18:13 +00001544 } else if (!SrcIsPhys && !DstIsPhys) {
Jakob Stoklund Olesen3a155f02009-04-30 21:24:03 +00001545 NewRC = getCommonSubClass(SrcRC, DstRC);
1546 if (!NewRC) {
1547 DOUT << "\tDisjoint regclasses: "
1548 << SrcRC->getName() << ", "
1549 << DstRC->getName() << ".\n";
1550 return false; // Not coalescable.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001551 }
Jakob Stoklund Olesen3a155f02009-04-30 21:24:03 +00001552 if (DstRC->getSize() > SrcRC->getSize())
1553 std::swap(LargeReg, SmallReg);
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001554 }
1555
Evan Chengc16d37e2009-01-23 05:48:59 +00001556 // If we are joining two virtual registers and the resulting register
1557 // class is more restrictive (fewer register, smaller size). Check if it's
1558 // worth doing the merge.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001559 if (!SrcIsPhys && !DstIsPhys &&
Evan Chengc16d37e2009-01-23 05:48:59 +00001560 (isExtSubReg || DstRC->isASubClass()) &&
1561 !isWinToJoinCrossClass(LargeReg, SmallReg,
1562 allocatableRCRegs_[NewRC].count())) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001563 DOUT << "\tSrc/Dest are different register classes.\n";
1564 // Allow the coalescer to try again in case either side gets coalesced to
1565 // a physical register that's compatible with the other side. e.g.
1566 // r1024 = MOV32to32_ r1025
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001567 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
Evan Chenge00f5de2008-06-19 01:39:21 +00001568 Again = true; // May be possible to coalesce later.
1569 return false;
1570 }
David Greene25133302007-06-08 17:18:56 +00001571 }
Evan Cheng8db86682008-09-11 20:07:10 +00001572
1573 // Will it create illegal extract_subreg / insert_subreg?
1574 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1575 return false;
1576 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1577 return false;
David Greene25133302007-06-08 17:18:56 +00001578
Evan Chengc8d044e2008-02-15 18:24:29 +00001579 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1580 LiveInterval &DstInt = li_->getInterval(DstReg);
1581 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
David Greene25133302007-06-08 17:18:56 +00001582 "Register mapping is horribly broken!");
1583
Dan Gohman6f0d0242008-02-10 18:45:23 +00001584 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1585 DOUT << " and "; DstInt.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00001586 DOUT << ": ";
1587
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001588 // Save a copy of the virtual register live interval. We'll manually
1589 // merge this into the "real" physical register live interval this is
1590 // coalesced with.
1591 LiveInterval *SavedLI = 0;
1592 if (RealDstReg)
1593 SavedLI = li_->dupInterval(&SrcInt);
1594 else if (RealSrcReg)
1595 SavedLI = li_->dupInterval(&DstInt);
1596
Evan Cheng3c88d742008-03-18 08:26:47 +00001597 // Check if it is necessary to propagate "isDead" property.
Dan Gohman97121ba2009-04-08 00:15:30 +00001598 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001599 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1600 bool isDead = mopd->isDead();
David Greene25133302007-06-08 17:18:56 +00001601
Evan Cheng7e073ba2008-04-09 20:57:25 +00001602 // We need to be careful about coalescing a source physical register with a
1603 // virtual register. Once the coalescing is done, it cannot be broken and
1604 // these are not spillable! If the destination interval uses are far away,
1605 // think twice about coalescing them!
1606 if (!isDead && (SrcIsPhys || DstIsPhys)) {
Evan Cheng0490dcb2009-04-30 18:39:57 +00001607 // If the copy is in a loop, take care not to coalesce aggressively if the
1608 // src is coming in from outside the loop (or the dst is out of the loop).
1609 // If it's not in a loop, then determine whether to join them base purely
1610 // by the length of the interval.
1611 if (PhysJoinTweak) {
1612 if (SrcIsPhys) {
1613 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
Evan Cheng358dec52009-06-15 08:28:29 +00001614 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
Evan Cheng0490dcb2009-04-30 18:39:57 +00001615 ++numAborts;
1616 DOUT << "\tMay tie down a physical register, abort!\n";
1617 Again = true; // May be possible to coalesce later.
1618 return false;
1619 }
1620 } else {
1621 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
Evan Cheng358dec52009-06-15 08:28:29 +00001622 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
Evan Cheng0490dcb2009-04-30 18:39:57 +00001623 ++numAborts;
1624 DOUT << "\tMay tie down a physical register, abort!\n";
1625 Again = true; // May be possible to coalesce later.
1626 return false;
1627 }
1628 }
1629 } else {
1630 // If the virtual register live interval is long but it has low use desity,
1631 // do not join them, instead mark the physical register as its allocation
1632 // preference.
1633 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1634 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1635 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1636 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1637 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1638 if (TheCopy.isBackEdge)
1639 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +00001640
Evan Cheng0490dcb2009-04-30 18:39:57 +00001641 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1642 float Ratio = 1.0 / Threshold;
1643 if (Length > Threshold &&
1644 (((float)std::distance(mri_->use_begin(JoinVReg),
1645 mri_->use_end()) / Length) < Ratio)) {
Evan Cheng358dec52009-06-15 08:28:29 +00001646 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
Evan Cheng0490dcb2009-04-30 18:39:57 +00001647 ++numAborts;
1648 DOUT << "\tMay tie down a physical register, abort!\n";
1649 Again = true; // May be possible to coalesce later.
1650 return false;
1651 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001652 }
David Greene25133302007-06-08 17:18:56 +00001653 }
1654 }
1655
1656 // Okay, attempt to join these two intervals. On failure, this returns false.
1657 // Otherwise, if one of the intervals being joined is a physreg, this method
1658 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1659 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001660 bool Swapped = false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00001661 // If SrcInt is implicitly defined, it's safe to coalesce.
1662 bool isEmpty = SrcInt.empty();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001663 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
Evan Chengdb9b1c32008-04-03 16:41:54 +00001664 // Only coalesce an empty interval (defined by implicit_def) with
Evan Cheng7e073ba2008-04-09 20:57:25 +00001665 // another interval which has a valno defined by the CopyMI and the CopyMI
1666 // is a kill of the implicit def.
Evan Chengdb9b1c32008-04-03 16:41:54 +00001667 DOUT << "Not profitable!\n";
1668 return false;
1669 }
1670
1671 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001672 // Coalescing failed.
Evan Chengcd047082008-08-30 09:09:33 +00001673
1674 // If definition of source is defined by trivial computation, try
1675 // rematerializing it.
Dan Gohman97121ba2009-04-08 00:15:30 +00001676 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
Evan Chengcd047082008-08-30 09:09:33 +00001677 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1678 return true;
David Greene25133302007-06-08 17:18:56 +00001679
1680 // If we can eliminate the copy without merging the live ranges, do so now.
Dan Gohman97121ba2009-04-08 00:15:30 +00001681 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
Evan Cheng70071432008-02-13 03:01:43 +00001682 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1683 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001684 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +00001685 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001686 }
Evan Cheng70071432008-02-13 03:01:43 +00001687
David Greene25133302007-06-08 17:18:56 +00001688 // Otherwise, we are unable to join the intervals.
1689 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001690 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +00001691 return false;
1692 }
1693
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001694 LiveInterval *ResSrcInt = &SrcInt;
1695 LiveInterval *ResDstInt = &DstInt;
1696 if (Swapped) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001697 std::swap(SrcReg, DstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001698 std::swap(ResSrcInt, ResDstInt);
1699 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001700 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
David Greene25133302007-06-08 17:18:56 +00001701 "LiveInterval::join didn't work right!");
1702
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001703 // If we're about to merge live ranges into a physical register live interval,
David Greene25133302007-06-08 17:18:56 +00001704 // we have to update any aliased register's live ranges to indicate that they
1705 // have clobbered values for this range.
Evan Chengc8d044e2008-02-15 18:24:29 +00001706 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001707 // If this is a extract_subreg where dst is a physical register, e.g.
1708 // cl = EXTRACT_SUBREG reg1024, 1
1709 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001710 if (RealDstReg || RealSrcReg) {
1711 LiveInterval &RealInt =
1712 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001713 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1714 E = SavedLI->vni_end(); I != E; ++I) {
1715 const VNInfo *ValNo = *I;
1716 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->copy,
Lang Hames857c4e02009-06-17 21:01:20 +00001717 false, // updated at *
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001718 li_->getVNInfoAllocator());
Lang Hames857c4e02009-06-17 21:01:20 +00001719 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001720 RealInt.addKills(NewValNo, ValNo->kills);
1721 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
Evan Cheng34729252007-10-14 10:08:34 +00001722 }
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001723 RealInt.weight += SavedLI->weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001724 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001725 }
1726
David Greene25133302007-06-08 17:18:56 +00001727 // Update the liveintervals of sub-registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001728 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +00001729 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +00001730 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +00001731 }
1732
Evan Chengc8d044e2008-02-15 18:24:29 +00001733 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1734 // larger super-register.
Dan Gohman97121ba2009-04-08 00:15:30 +00001735 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1736 !SrcIsPhys && !DstIsPhys) {
1737 if ((isExtSubReg && !Swapped) ||
1738 ((isInsSubReg || isSubRegToReg) && Swapped)) {
Evan Cheng90f95f82009-06-14 20:22:55 +00001739 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
Evan Chengc8d044e2008-02-15 18:24:29 +00001740 std::swap(SrcReg, DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +00001741 std::swap(ResSrcInt, ResDstInt);
1742 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001743 }
1744
Evan Chenge00f5de2008-06-19 01:39:21 +00001745 // Coalescing to a virtual register that is of a sub-register class of the
1746 // other. Make sure the resulting register is set to the right register class.
Evan Cheng8c08d8c2009-01-23 02:15:19 +00001747 if (CrossRC) {
1748 ++numCrossRCs;
1749 if (NewRC)
1750 mri_->setRegClass(DstReg, NewRC);
Evan Chenge00f5de2008-06-19 01:39:21 +00001751 }
1752
Evan Cheng8fc9a102007-11-06 08:52:21 +00001753 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001754 // Add all copies that define val# in the source interval into the queue.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001755 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1756 e = ResSrcInt->vni_end(); i != e; ++i) {
1757 const VNInfo *vni = *i;
Lang Hames857c4e02009-06-17 21:01:20 +00001758 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1759 if (!vni->def || vni->isUnused() || vni->isPHIDef() || !vni->isDefAccurate())
Evan Chengc8d044e2008-02-15 18:24:29 +00001760 continue;
1761 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +00001762 unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
Evan Chengc8d044e2008-02-15 18:24:29 +00001763 if (CopyMI &&
1764 JoinedCopies.count(CopyMI) == 0 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +00001765 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1766 NewSrcSubIdx, NewDstSubIdx)) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001767 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
Evan Chengc8d044e2008-02-15 18:24:29 +00001768 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1769 isBackEdgeCopy(CopyMI, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001770 }
1771 }
1772 }
1773
Evan Chengc8d044e2008-02-15 18:24:29 +00001774 // Remember to delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001775 JoinedCopies.insert(CopyMI);
Evan Chengc8d044e2008-02-15 18:24:29 +00001776
Evan Cheng4ff3f1c2008-03-10 08:11:32 +00001777 // Some live range has been lengthened due to colaescing, eliminate the
1778 // unnecessary kills.
1779 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1780 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1781 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1782
Evan Cheng7e073ba2008-04-09 20:57:25 +00001783 if (isInsSubReg)
1784 // Avoid:
1785 // r1024 = op
1786 // r1024 = implicit_def
1787 // ...
1788 // = r1024
1789 RemoveDeadImpDef(DstReg, *ResDstInt);
Evan Chengc8d044e2008-02-15 18:24:29 +00001790 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1791
Evan Chengcd047082008-08-30 09:09:33 +00001792 // SrcReg is guarateed to be the register whose live interval that is
1793 // being merged.
1794 li_->removeInterval(SrcReg);
1795
Evan Chengf9f1da12009-06-18 02:04:01 +00001796 // Update regalloc hint.
1797 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1798
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001799 // Manually deleted the live interval copy.
1800 if (SavedLI) {
1801 SavedLI->clear();
1802 delete SavedLI;
1803 }
1804
Evan Chengdb9b1c32008-04-03 16:41:54 +00001805 if (isEmpty) {
1806 // Now the copy is being coalesced away, the val# previously defined
1807 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1808 // length interval. Remove the val#.
1809 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
Evan Chengff7a3e52008-04-16 18:48:43 +00001810 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001811 VNInfo *ImpVal = LR->valno;
1812 assert(ImpVal->def == CopyIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001813 unsigned NextDef = LR->end;
Evan Cheng7b113652009-06-16 07:15:05 +00001814 TurnCopiesFromValNoToImpDefs(*ResDstInt, ImpVal);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001815 ResDstInt->removeValNo(ImpVal);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001816 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1817 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1818 // Special case: vr1024 = implicit_def
1819 // vr1024 = insert_subreg vr1024, vr1025, c
1820 // The insert_subreg becomes a "copy" that defines a val# which can itself
1821 // be coalesced away.
1822 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1823 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1824 LR->valno->copy = DefMI;
1825 }
Evan Chengdb9b1c32008-04-03 16:41:54 +00001826 }
1827
Evan Cheng3ef2d602008-09-09 21:44:23 +00001828 // If resulting interval has a preference that no longer fits because of subreg
1829 // coalescing, just clear the preference.
Evan Cheng90f95f82009-06-14 20:22:55 +00001830 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1831 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
Evan Cheng40869062008-09-11 18:40:32 +00001832 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
Evan Cheng3ef2d602008-09-09 21:44:23 +00001833 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
Evan Cheng90f95f82009-06-14 20:22:55 +00001834 if (!RC->contains(Preference))
Evan Cheng358dec52009-06-15 08:28:29 +00001835 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
Evan Cheng3ef2d602008-09-09 21:44:23 +00001836 }
1837
Evan Chengdb9b1c32008-04-03 16:41:54 +00001838 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1839 DOUT << "\n";
1840
David Greene25133302007-06-08 17:18:56 +00001841 ++numJoins;
1842 return true;
1843}
1844
1845/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1846/// compute what the resultant value numbers for each value in the input two
1847/// ranges will be. This is complicated by copies between the two which can
1848/// and will commonly cause multiple value numbers to be merged into one.
1849///
1850/// VN is the value number that we're trying to resolve. InstDefiningValue
1851/// keeps track of the new InstDefiningValue assignment for the result
1852/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1853/// whether a value in this or other is a copy from the opposite set.
1854/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1855/// already been assigned.
1856///
1857/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1858/// contains the value number the copy is from.
1859///
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001860static unsigned ComputeUltimateVN(VNInfo *VNI,
1861 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +00001862 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1863 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +00001864 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001865 SmallVector<int, 16> &OtherValNoAssignments) {
1866 unsigned VN = VNI->id;
1867
David Greene25133302007-06-08 17:18:56 +00001868 // If the VN has already been computed, just return it.
1869 if (ThisValNoAssignments[VN] >= 0)
1870 return ThisValNoAssignments[VN];
1871// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001872
David Greene25133302007-06-08 17:18:56 +00001873 // If this val is not a copy from the other val, then it must be a new value
1874 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +00001875 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +00001876 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001877 NewVNInfo.push_back(VNI);
1878 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001879 }
Evan Chengc14b1442007-08-31 08:04:17 +00001880 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +00001881
1882 // Otherwise, this *is* a copy from the RHS. If the other side has already
1883 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001884 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1885 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +00001886
1887 // Mark this value number as currently being computed, then ask what the
1888 // ultimate value # of the other value is.
1889 ThisValNoAssignments[VN] = -2;
1890 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001891 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1892 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001893 return ThisValNoAssignments[VN] = UltimateVN;
1894}
1895
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001896static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +00001897 return std::find(V.begin(), V.end(), Val) != V.end();
1898}
1899
Evan Cheng7e073ba2008-04-09 20:57:25 +00001900/// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1901/// the specified live interval is defined by a copy from the specified
1902/// register.
1903bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1904 LiveRange *LR,
1905 unsigned Reg) {
1906 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1907 if (SrcReg == Reg)
1908 return true;
Lang Hames857c4e02009-06-17 21:01:20 +00001909 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1910 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
Evan Cheng7e073ba2008-04-09 20:57:25 +00001911 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1912 *tri_->getSuperRegisters(li.reg)) {
1913 // It's a sub-register live interval, we may not have precise information.
1914 // Re-compute it.
1915 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
Evan Cheng04ee5a12009-01-20 19:12:24 +00001916 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1917 if (DefMI &&
1918 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
Evan Cheng7e073ba2008-04-09 20:57:25 +00001919 DstReg == li.reg && SrcReg == Reg) {
1920 // Cache computed info.
1921 LR->valno->def = LR->start;
1922 LR->valno->copy = DefMI;
1923 return true;
1924 }
1925 }
1926 return false;
1927}
1928
David Greene25133302007-06-08 17:18:56 +00001929/// SimpleJoin - Attempt to joint the specified interval into this one. The
1930/// caller of this method must guarantee that the RHS only contains a single
1931/// value number and that the RHS is not defined by a copy from this
1932/// interval. This returns false if the intervals are not joinable, or it
1933/// joins them and returns true.
Bill Wendling2674d712008-01-04 08:59:18 +00001934bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
David Greene25133302007-06-08 17:18:56 +00001935 assert(RHS.containsOneValue());
1936
1937 // Some number (potentially more than one) value numbers in the current
1938 // interval may be defined as copies from the RHS. Scan the overlapping
1939 // portions of the LHS and RHS, keeping track of this and looking for
1940 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001941 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +00001942
1943 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1944 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1945
1946 if (LHSIt->start < RHSIt->start) {
1947 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1948 if (LHSIt != LHS.begin()) --LHSIt;
1949 } else if (RHSIt->start < LHSIt->start) {
1950 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1951 if (RHSIt != RHS.begin()) --RHSIt;
1952 }
1953
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001954 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +00001955
1956 while (1) {
1957 // Determine if these live intervals overlap.
1958 bool Overlaps = false;
1959 if (LHSIt->start <= RHSIt->start)
1960 Overlaps = LHSIt->end > RHSIt->start;
1961 else
1962 Overlaps = RHSIt->end > LHSIt->start;
1963
1964 // If the live intervals overlap, there are two interesting cases: if the
1965 // LHS interval is defined by a copy from the RHS, it's ok and we record
1966 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +00001967 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +00001968 if (Overlaps) {
1969 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001970 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001971 // Copy from the RHS?
Evan Cheng7e073ba2008-04-09 20:57:25 +00001972 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
David Greene25133302007-06-08 17:18:56 +00001973 return false; // Nope, bail out.
Evan Chengf4ea5102008-05-21 22:34:12 +00001974
1975 if (LHSIt->contains(RHSIt->valno->def))
1976 // Here is an interesting situation:
1977 // BB1:
1978 // vr1025 = copy vr1024
1979 // ..
1980 // BB2:
1981 // vr1024 = op
1982 // = vr1025
1983 // Even though vr1025 is copied from vr1024, it's not safe to
Bill Wendling430d4232009-03-30 20:30:02 +00001984 // coalesce them since the live range of vr1025 intersects the
Evan Chengf4ea5102008-05-21 22:34:12 +00001985 // def of vr1024. This happens because vr1025 is assigned the
1986 // value of the previous iteration of vr1024.
1987 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001988 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001989 }
1990
1991 // We know this entire LHS live range is okay, so skip it now.
1992 if (++LHSIt == LHSEnd) break;
1993 continue;
1994 }
1995
1996 if (LHSIt->end < RHSIt->end) {
1997 if (++LHSIt == LHSEnd) break;
1998 } else {
1999 // One interesting case to check here. It's possible that we have
2000 // something like "X3 = Y" which defines a new value number in the LHS,
2001 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +00002002 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +00002003 // the live ranges don't actually overlap.
2004 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002005 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00002006 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +00002007 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +00002008 if (++LHSIt == LHSEnd) break;
2009 } else {
2010 // Otherwise, if this is a copy from the RHS, mark it as being merged
2011 // in.
Evan Cheng7e073ba2008-04-09 20:57:25 +00002012 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
Evan Chengf4ea5102008-05-21 22:34:12 +00002013 if (LHSIt->contains(RHSIt->valno->def))
2014 // Here is an interesting situation:
2015 // BB1:
2016 // vr1025 = copy vr1024
2017 // ..
2018 // BB2:
2019 // vr1024 = op
2020 // = vr1025
2021 // Even though vr1025 is copied from vr1024, it's not safe to
2022 // coalesced them since live range of vr1025 intersects the
2023 // def of vr1024. This happens because vr1025 is assigned the
2024 // value of the previous iteration of vr1024.
2025 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002026 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00002027
2028 // We know this entire LHS live range is okay, so skip it now.
2029 if (++LHSIt == LHSEnd) break;
2030 }
2031 }
2032 }
2033
2034 if (++RHSIt == RHSEnd) break;
2035 }
2036 }
2037
Gabor Greife510b3a2007-07-09 12:00:59 +00002038 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +00002039 // the value numbers in EliminatedLHSVals will all be merged together. Since
2040 // the most common case is that EliminatedLHSVals has a single number, we
2041 // optimize for it: if there is more than one value, we merge them all into
2042 // the lowest numbered one, then handle the interval as if we were merging
2043 // with one value number.
Devang Patel8a84e442009-01-05 17:31:22 +00002044 VNInfo *LHSValNo = NULL;
David Greene25133302007-06-08 17:18:56 +00002045 if (EliminatedLHSVals.size() > 1) {
2046 // Loop through all the equal value numbers merging them into the smallest
2047 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002048 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +00002049 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002050 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +00002051 // Merge the current notion of the smallest into the smaller one.
2052 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2053 Smallest = EliminatedLHSVals[i];
2054 } else {
2055 // Merge into the smallest.
2056 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2057 }
2058 }
2059 LHSValNo = Smallest;
Evan Cheng7e073ba2008-04-09 20:57:25 +00002060 } else if (EliminatedLHSVals.empty()) {
2061 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2062 *tri_->getSuperRegisters(LHS.reg))
2063 // Imprecise sub-register information. Can't handle it.
2064 return false;
Torok Edwinc25e7582009-07-11 20:10:48 +00002065 LLVM_UNREACHABLE("No copies from the RHS?");
David Greene25133302007-06-08 17:18:56 +00002066 } else {
David Greene25133302007-06-08 17:18:56 +00002067 LHSValNo = EliminatedLHSVals[0];
2068 }
2069
2070 // Okay, now that there is a single LHS value number that we're merging the
2071 // RHS into, update the value number info for the LHS to indicate that the
2072 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +00002073 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00002074 LHSValNo->def = VNI->def;
2075 LHSValNo->copy = VNI->copy;
David Greene25133302007-06-08 17:18:56 +00002076
2077 // Okay, the final step is to loop over the RHS live intervals, adding them to
2078 // the LHS.
Lang Hames857c4e02009-06-17 21:01:20 +00002079 if (VNI->hasPHIKill())
2080 LHSValNo->setHasPHIKill(true);
Evan Chengf3bb2e62007-09-05 21:46:51 +00002081 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +00002082 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +00002083 LHS.weight += RHS.weight;
Evan Cheng90f95f82009-06-14 20:22:55 +00002084
2085 // Update regalloc hint if both are virtual registers.
2086 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2087 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
Evan Cheng358dec52009-06-15 08:28:29 +00002088 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2089 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2090 if (RHSPref != LHSPref)
Evan Cheng90f95f82009-06-14 20:22:55 +00002091 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2092 }
Dan Gohman97121ba2009-04-08 00:15:30 +00002093
2094 // Update the liveintervals of sub-registers.
2095 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2096 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2097 li_->getOrCreateInterval(*AS).MergeInClobberRanges(LHS,
2098 li_->getVNInfoAllocator());
2099
David Greene25133302007-06-08 17:18:56 +00002100 return true;
2101}
2102
2103/// JoinIntervals - Attempt to join these two intervals. On failure, this
2104/// returns false. Otherwise, if one of the intervals being joined is a
2105/// physreg, this method always canonicalizes LHS to be it. The output
2106/// "RHS" will not have been modified, so we can use this information
2107/// below to update aliases.
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002108bool
2109SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2110 bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +00002111 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +00002112 // coalesced.
David Greene25133302007-06-08 17:18:56 +00002113 SmallVector<int, 16> LHSValNoAssignments;
2114 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +00002115 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2116 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002117 SmallVector<VNInfo*, 16> NewVNInfo;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002118
David Greene25133302007-06-08 17:18:56 +00002119 // If a live interval is a physical register, conservatively check if any
2120 // of its sub-registers is overlapping the live interval of the virtual
2121 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +00002122 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2123 *tri_->getSubRegisters(LHS.reg)) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002124 // If it's coalescing a virtual register to a physical register, estimate
2125 // its live interval length. This is the *cost* of scanning an entire live
2126 // interval. If the cost is low, we'll do an exhaustive check instead.
Evan Cheng1d8a76d2009-01-13 03:57:45 +00002127
2128 // If this is something like this:
2129 // BB1:
2130 // v1024 = op
2131 // ...
2132 // BB2:
2133 // ...
2134 // RAX = v1024
2135 //
2136 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2137 // less conservative check. It's possible a sub-register is defined before
2138 // v1024 (or live in) and live out of BB1.
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002139 if (RHS.containsOneValue() &&
Evan Cheng167650d2009-01-13 06:08:37 +00002140 li_->intervalIsInOneMBB(RHS) &&
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002141 li_->getApproximateInstructionCount(RHS) <= 10) {
2142 // Perform a more exhaustive check for some common cases.
2143 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
David Greene25133302007-06-08 17:18:56 +00002144 return false;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002145 } else {
2146 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2147 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2148 DOUT << "Interfere with sub-register ";
2149 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
2150 return false;
2151 }
2152 }
Dan Gohman6f0d0242008-02-10 18:45:23 +00002153 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2154 *tri_->getSubRegisters(RHS.reg)) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002155 if (LHS.containsOneValue() &&
2156 li_->getApproximateInstructionCount(LHS) <= 10) {
2157 // Perform a more exhaustive check for some common cases.
2158 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
David Greene25133302007-06-08 17:18:56 +00002159 return false;
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002160 } else {
2161 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2162 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2163 DOUT << "Interfere with sub-register ";
2164 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
2165 return false;
2166 }
2167 }
David Greene25133302007-06-08 17:18:56 +00002168 }
2169
2170 // Compute ultimate value numbers for the LHS and RHS values.
2171 if (RHS.containsOneValue()) {
2172 // Copies from a liveinterval with a single value are simple to handle and
2173 // very common, handle the special case here. This is important, because
2174 // often RHS is small and LHS is large (e.g. a physreg).
2175
2176 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +00002177 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +00002178 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002179 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +00002180 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00002181 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
Evan Cheng8f90b6e2009-01-07 02:08:57 +00002182 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
David Greene25133302007-06-08 17:18:56 +00002183 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +00002184 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +00002185 // can't swap the LHS/RHS intervals though.
Dan Gohman6f0d0242008-02-10 18:45:23 +00002186 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00002187 return SimpleJoin(LHS, RHS);
2188 } else {
Evan Chengc14b1442007-08-31 08:04:17 +00002189 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00002190 }
2191 } else {
2192 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +00002193 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002194 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +00002195 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +00002196 }
2197
2198 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2199 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002200 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +00002201
2202 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2203 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002204 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2205 i != e; ++i) {
2206 VNInfo *VNI = *i;
2207 unsigned VN = VNI->id;
Evan Chengc8d044e2008-02-15 18:24:29 +00002208 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2209 if (LHSSrcReg != RHS.reg) {
David Greene25133302007-06-08 17:18:56 +00002210 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +00002211 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002212 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00002213 LHSValNoAssignments[VN] = VN;
2214 } else if (RHSValID == -1) {
2215 // Otherwise, it is a copy from the RHS, and we don't already have a
2216 // value# for it. Keep the current value number, but remember it.
2217 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002218 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00002219 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00002220 } else {
2221 // Otherwise, use the specified value #.
2222 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002223 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2224 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00002225 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +00002226 }
David Greene25133302007-06-08 17:18:56 +00002227 }
2228 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002229 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00002230 LHSValNoAssignments[VN] = VN;
2231 }
2232 }
2233
2234 assert(RHSValID != -1 && "Didn't find value #?");
2235 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +00002236 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +00002237 // This path doesn't go through ComputeUltimateVN so just set
2238 // it to anything.
2239 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +00002240 }
David Greene25133302007-06-08 17:18:56 +00002241 } else {
2242 // Loop over the value numbers of the LHS, seeing if any are defined from
2243 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002244 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2245 i != e; ++i) {
2246 VNInfo *VNI = *i;
Lang Hames857c4e02009-06-17 21:01:20 +00002247 if (VNI->isUnused() || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00002248 continue;
2249
2250 // DstReg is known to be a register in the LHS interval. If the src is
2251 // from the RHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00002252 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00002253 continue;
2254
2255 // Figure out the value # from the RHS.
Bill Wendling2674d712008-01-04 08:59:18 +00002256 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00002257 }
2258
2259 // Loop over the value numbers of the RHS, seeing if any are defined from
2260 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002261 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2262 i != e; ++i) {
2263 VNInfo *VNI = *i;
Lang Hames857c4e02009-06-17 21:01:20 +00002264 if (VNI->isUnused() || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00002265 continue;
2266
2267 // DstReg is known to be a register in the RHS interval. If the src is
2268 // from the LHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00002269 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
David Greene25133302007-06-08 17:18:56 +00002270 continue;
2271
2272 // Figure out the value # from the LHS.
Bill Wendling2674d712008-01-04 08:59:18 +00002273 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00002274 }
2275
2276 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2277 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002278 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +00002279
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002280 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2281 i != e; ++i) {
2282 VNInfo *VNI = *i;
2283 unsigned VN = VNI->id;
Lang Hames857c4e02009-06-17 21:01:20 +00002284 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
David Greene25133302007-06-08 17:18:56 +00002285 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002286 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00002287 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002288 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00002289 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002290 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2291 i != e; ++i) {
2292 VNInfo *VNI = *i;
2293 unsigned VN = VNI->id;
Lang Hames857c4e02009-06-17 21:01:20 +00002294 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
David Greene25133302007-06-08 17:18:56 +00002295 continue;
2296 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +00002297 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002298 NewVNInfo.push_back(VNI);
2299 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00002300 continue;
2301 }
2302
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002303 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00002304 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002305 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00002306 }
2307 }
2308
2309 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +00002310 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +00002311 LiveInterval::const_iterator I = LHS.begin();
2312 LiveInterval::const_iterator IE = LHS.end();
2313 LiveInterval::const_iterator J = RHS.begin();
2314 LiveInterval::const_iterator JE = RHS.end();
2315
2316 // Skip ahead until the first place of potential sharing.
2317 if (I->start < J->start) {
2318 I = std::upper_bound(I, IE, J->start);
2319 if (I != LHS.begin()) --I;
2320 } else if (J->start < I->start) {
2321 J = std::upper_bound(J, JE, I->start);
2322 if (J != RHS.begin()) --J;
2323 }
2324
2325 while (1) {
2326 // Determine if these two live ranges overlap.
2327 bool Overlaps;
2328 if (I->start < J->start) {
2329 Overlaps = I->end > J->start;
2330 } else {
2331 Overlaps = J->end > I->start;
2332 }
2333
2334 // If so, check value # info to determine if they are really different.
2335 if (Overlaps) {
2336 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +00002337 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00002338 if (LHSValNoAssignments[I->valno->id] !=
2339 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +00002340 return false;
2341 }
2342
2343 if (I->end < J->end) {
2344 ++I;
2345 if (I == IE) break;
2346 } else {
2347 ++J;
2348 if (J == JE) break;
2349 }
2350 }
2351
Evan Cheng34729252007-10-14 10:08:34 +00002352 // Update kill info. Some live ranges are extended due to copy coalescing.
2353 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2354 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2355 VNInfo *VNI = I->first;
2356 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2357 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Lang Hames857c4e02009-06-17 21:01:20 +00002358 if (VNI->hasPHIKill())
2359 NewVNInfo[LHSValID]->setHasPHIKill(true);
Evan Cheng34729252007-10-14 10:08:34 +00002360 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2361 }
2362
2363 // Update kill info. Some live ranges are extended due to copy coalescing.
2364 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2365 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2366 VNInfo *VNI = I->first;
2367 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2368 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Lang Hames857c4e02009-06-17 21:01:20 +00002369 if (VNI->hasPHIKill())
2370 NewVNInfo[RHSValID]->setHasPHIKill(true);
Evan Cheng34729252007-10-14 10:08:34 +00002371 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2372 }
2373
Gabor Greife510b3a2007-07-09 12:00:59 +00002374 // If we get here, we know that we can coalesce the live ranges. Ask the
2375 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002376 if ((RHS.ranges.size() > LHS.ranges.size() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002377 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2378 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng90f95f82009-06-14 20:22:55 +00002379 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2380 mri_);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002381 Swapped = true;
2382 } else {
Evan Cheng90f95f82009-06-14 20:22:55 +00002383 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2384 mri_);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00002385 Swapped = false;
2386 }
David Greene25133302007-06-08 17:18:56 +00002387 return true;
2388}
2389
2390namespace {
2391 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2392 // depth of the basic block (the unsigned), and then on the MBB number.
2393 struct DepthMBBCompare {
2394 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2395 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2396 if (LHS.first > RHS.first) return true; // Deeper loops first
2397 return LHS.first == RHS.first &&
2398 LHS.second->getNumber() < RHS.second->getNumber();
2399 }
2400 };
2401}
2402
Evan Cheng8fc9a102007-11-06 08:52:21 +00002403/// getRepIntervalSize - Returns the size of the interval that represents the
2404/// specified register.
2405template<class SF>
2406unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2407 return Rc->getRepIntervalSize(Reg);
2408}
2409
2410/// CopyRecSort::operator - Join priority queue sorting function.
2411///
2412bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2413 // Inner loops first.
2414 if (left.LoopDepth > right.LoopDepth)
2415 return false;
Evan Chengc8d044e2008-02-15 18:24:29 +00002416 else if (left.LoopDepth == right.LoopDepth)
Evan Cheng8fc9a102007-11-06 08:52:21 +00002417 if (left.isBackEdge && !right.isBackEdge)
2418 return false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002419 return true;
2420}
2421
Gabor Greife510b3a2007-07-09 12:00:59 +00002422void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00002423 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00002424 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00002425
Evan Cheng8b0b8742007-10-16 08:04:24 +00002426 std::vector<CopyRec> VirtCopies;
2427 std::vector<CopyRec> PhysCopies;
Evan Cheng7e073ba2008-04-09 20:57:25 +00002428 std::vector<CopyRec> ImpDefCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002429 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00002430 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2431 MII != E;) {
2432 MachineInstr *Inst = MII++;
2433
Evan Cheng32dfbea2007-10-12 08:50:34 +00002434 // If this isn't a copy nor a extract_subreg, we can't join intervals.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002435 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Cheng32dfbea2007-10-12 08:50:34 +00002436 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2437 DstReg = Inst->getOperand(0).getReg();
2438 SrcReg = Inst->getOperand(1).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +00002439 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2440 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00002441 DstReg = Inst->getOperand(0).getReg();
2442 SrcReg = Inst->getOperand(2).getReg();
Evan Cheng04ee5a12009-01-20 19:12:24 +00002443 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
Evan Cheng32dfbea2007-10-12 08:50:34 +00002444 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00002445
Evan Chengc8d044e2008-02-15 18:24:29 +00002446 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2447 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00002448 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002449 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002450 } else {
Evan Cheng7e073ba2008-04-09 20:57:25 +00002451 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2452 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2453 else if (SrcIsPhys || DstIsPhys)
Evan Chengc8d044e2008-02-15 18:24:29 +00002454 PhysCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002455 else
Evan Chengc8d044e2008-02-15 18:24:29 +00002456 VirtCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00002457 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002458 }
2459
Evan Cheng8fc9a102007-11-06 08:52:21 +00002460 if (NewHeuristic)
2461 return;
2462
Evan Cheng7e073ba2008-04-09 20:57:25 +00002463 // Try coalescing implicit copies first, followed by copies to / from
2464 // physical registers, then finally copies from virtual registers to
2465 // virtual registers.
2466 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2467 CopyRec &TheCopy = ImpDefCopies[i];
2468 bool Again = false;
2469 if (!JoinCopy(TheCopy, Again))
2470 if (Again)
2471 TryAgain.push_back(TheCopy);
2472 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00002473 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2474 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002475 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002476 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002477 if (Again)
2478 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00002479 }
2480 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2481 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00002482 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002483 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00002484 if (Again)
2485 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00002486 }
2487}
2488
2489void SimpleRegisterCoalescing::joinIntervals() {
2490 DOUT << "********** JOINING INTERVALS ***********\n";
2491
Evan Cheng8fc9a102007-11-06 08:52:21 +00002492 if (NewHeuristic)
2493 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2494
David Greene25133302007-06-08 17:18:56 +00002495 std::vector<CopyRec> TryAgainList;
Dan Gohmana8c763b2008-08-14 18:13:49 +00002496 if (loopInfo->empty()) {
David Greene25133302007-06-08 17:18:56 +00002497 // If there are no loops in the function, join intervals in function order.
2498 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2499 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002500 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002501 } else {
2502 // Otherwise, join intervals in inner loops before other intervals.
2503 // Unfortunately we can't just iterate over loop hierarchy here because
2504 // there may be more MBB's than BB's. Collect MBB's for sorting.
2505
2506 // Join intervals in the function prolog first. We want to join physical
2507 // registers with virtual registers before the intervals got too long.
2508 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002509 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2510 MachineBasicBlock *MBB = I;
2511 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2512 }
David Greene25133302007-06-08 17:18:56 +00002513
2514 // Sort by loop depth.
2515 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2516
2517 // Finally, join intervals in loop nest order.
2518 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00002519 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00002520 }
2521
2522 // Joining intervals can allow other intervals to be joined. Iteratively join
2523 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00002524 if (NewHeuristic) {
2525 SmallVector<CopyRec, 16> TryAgain;
2526 bool ProgressMade = true;
2527 while (ProgressMade) {
2528 ProgressMade = false;
2529 while (!JoinQueue->empty()) {
2530 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00002531 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002532 bool Success = JoinCopy(R, Again);
2533 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00002534 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002535 else if (Again)
2536 TryAgain.push_back(R);
2537 }
2538
2539 if (ProgressMade) {
2540 while (!TryAgain.empty()) {
2541 JoinQueue->push(TryAgain.back());
2542 TryAgain.pop_back();
2543 }
2544 }
2545 }
2546 } else {
2547 bool ProgressMade = true;
2548 while (ProgressMade) {
2549 ProgressMade = false;
2550
2551 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2552 CopyRec &TheCopy = TryAgainList[i];
2553 if (TheCopy.MI) {
2554 bool Again = false;
2555 bool Success = JoinCopy(TheCopy, Again);
2556 if (Success || !Again) {
2557 TheCopy.MI = 0; // Mark this one as done.
2558 ProgressMade = true;
2559 }
Evan Cheng0547bab2007-11-01 06:22:48 +00002560 }
David Greene25133302007-06-08 17:18:56 +00002561 }
2562 }
2563 }
2564
Evan Cheng8fc9a102007-11-06 08:52:21 +00002565 if (NewHeuristic)
Evan Chengc8d044e2008-02-15 18:24:29 +00002566 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00002567}
2568
2569/// Return true if the two specified registers belong to different register
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002570/// classes. The registers may be either phys or virt regs.
Evan Chenge00f5de2008-06-19 01:39:21 +00002571bool
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002572SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2573 unsigned RegB) const {
David Greene25133302007-06-08 17:18:56 +00002574 // Get the register classes for the first reg.
Dan Gohman6f0d0242008-02-10 18:45:23 +00002575 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2576 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
David Greene25133302007-06-08 17:18:56 +00002577 "Shouldn't consider two physregs!");
Evan Chengc8d044e2008-02-15 18:24:29 +00002578 return !mri_->getRegClass(RegB)->contains(RegA);
David Greene25133302007-06-08 17:18:56 +00002579 }
2580
2581 // Compare against the regclass for the second reg.
Evan Chenge00f5de2008-06-19 01:39:21 +00002582 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2583 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2584 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
Evan Cheng8c08d8c2009-01-23 02:15:19 +00002585 return RegClassA != RegClassB;
Evan Chenge00f5de2008-06-19 01:39:21 +00002586 }
2587 return !RegClassA->contains(RegB);
David Greene25133302007-06-08 17:18:56 +00002588}
2589
2590/// lastRegisterUse - Returns the last use of the specific register between
Evan Chengc8d044e2008-02-15 18:24:29 +00002591/// cycles Start and End or NULL if there are no uses.
2592MachineOperand *
Chris Lattner84bc5422007-12-31 04:13:23 +00002593SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
Evan Chengc8d044e2008-02-15 18:24:29 +00002594 unsigned Reg, unsigned &UseIdx) const{
2595 UseIdx = 0;
2596 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2597 MachineOperand *LastUse = NULL;
2598 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2599 E = mri_->use_end(); I != E; ++I) {
2600 MachineOperand &Use = I.getOperand();
2601 MachineInstr *UseMI = Use.getParent();
Evan Cheng04ee5a12009-01-20 19:12:24 +00002602 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2603 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2604 SrcReg == DstReg)
Evan Chenga2fb6342008-03-25 02:02:19 +00002605 // Ignore identity copies.
2606 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +00002607 unsigned Idx = li_->getInstructionIndex(UseMI);
2608 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2609 LastUse = &Use;
Evan Cheng58207f12009-02-22 08:35:56 +00002610 UseIdx = li_->getUseIndex(Idx);
Evan Chengc8d044e2008-02-15 18:24:29 +00002611 }
2612 }
2613 return LastUse;
2614 }
2615
David Greene25133302007-06-08 17:18:56 +00002616 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2617 int s = Start;
2618 while (e >= s) {
2619 // Skip deleted instructions
2620 MachineInstr *MI = li_->getInstructionFromIndex(e);
2621 while ((e - InstrSlots::NUM) >= s && !MI) {
2622 e -= InstrSlots::NUM;
2623 MI = li_->getInstructionFromIndex(e);
2624 }
2625 if (e < s || MI == NULL)
2626 return NULL;
2627
Evan Chenga2fb6342008-03-25 02:02:19 +00002628 // Ignore identity copies.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002629 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2630 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2631 SrcReg == DstReg))
Evan Chenga2fb6342008-03-25 02:02:19 +00002632 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2633 MachineOperand &Use = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002634 if (Use.isReg() && Use.isUse() && Use.getReg() &&
Evan Chenga2fb6342008-03-25 02:02:19 +00002635 tri_->regsOverlap(Use.getReg(), Reg)) {
Evan Cheng58207f12009-02-22 08:35:56 +00002636 UseIdx = li_->getUseIndex(e);
Evan Chenga2fb6342008-03-25 02:02:19 +00002637 return &Use;
2638 }
David Greene25133302007-06-08 17:18:56 +00002639 }
David Greene25133302007-06-08 17:18:56 +00002640
2641 e -= InstrSlots::NUM;
2642 }
2643
2644 return NULL;
2645}
2646
2647
David Greene25133302007-06-08 17:18:56 +00002648void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +00002649 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +00002650 cerr << tri_->getName(reg);
David Greene25133302007-06-08 17:18:56 +00002651 else
2652 cerr << "%reg" << reg;
2653}
2654
2655void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng8fc9a102007-11-06 08:52:21 +00002656 JoinedCopies.clear();
Evan Chengcd047082008-08-30 09:09:33 +00002657 ReMatCopies.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002658 ReMatDefs.clear();
David Greene25133302007-06-08 17:18:56 +00002659}
2660
2661static bool isZeroLengthInterval(LiveInterval *li) {
2662 for (LiveInterval::Ranges::const_iterator
2663 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
Lang Hamesf41538d2009-06-02 16:53:25 +00002664 if (i->end - i->start > LiveInterval::InstrSlots::NUM)
David Greene25133302007-06-08 17:18:56 +00002665 return false;
2666 return true;
2667}
2668
Evan Chengdb9b1c32008-04-03 16:41:54 +00002669/// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2670/// turn the copy into an implicit def.
2671bool
2672SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2673 MachineBasicBlock *MBB,
2674 unsigned DstReg, unsigned SrcReg) {
2675 MachineInstr *CopyMI = &*I;
2676 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2677 if (!li_->hasInterval(SrcReg))
2678 return false;
2679 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2680 if (!SrcInt.empty())
2681 return false;
Evan Chengf20d9432008-04-09 01:30:15 +00002682 if (!li_->hasInterval(DstReg))
2683 return false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002684 LiveInterval &DstInt = li_->getInterval(DstReg);
Evan Chengff7a3e52008-04-16 18:48:43 +00002685 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
Evan Cheng67fcf562009-06-16 07:12:58 +00002686 // If the valno extends beyond this basic block, then it's not safe to delete
2687 // the val# or else livein information won't be correct.
2688 MachineBasicBlock *EndMBB = li_->getMBBFromIndex(DstLR->end);
2689 if (EndMBB != MBB)
2690 return false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002691 DstInt.removeValNo(DstLR->valno);
2692 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2693 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2694 CopyMI->RemoveOperand(i);
Evan Cheng459a7c62009-07-01 08:19:36 +00002695 CopyMI->getOperand(0).setIsUndef();
Dan Gohmana8c763b2008-08-14 18:13:49 +00002696 bool NoUse = mri_->use_empty(SrcReg);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002697 if (NoUse) {
Evan Cheng459a7c62009-07-01 08:19:36 +00002698 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
2699 RE = mri_->reg_end(); RI != RE; ) {
2700 assert(RI.getOperand().isDef());
2701 MachineInstr *DefMI = &*RI;
2702 ++RI;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002703 // The implicit_def source has no other uses, delete it.
2704 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2705 li_->RemoveMachineInstrFromMaps(DefMI);
2706 DefMI->eraseFromParent();
Evan Chengdb9b1c32008-04-03 16:41:54 +00002707 }
2708 }
Evan Cheng459a7c62009-07-01 08:19:36 +00002709
2710 // Mark uses of implicit_def isUndef.
2711 for (MachineRegisterInfo::use_iterator RI = mri_->use_begin(DstReg),
2712 RE = mri_->use_end(); RI != RE; ++RI) {
2713 assert((*RI).getParent() == MBB);
2714 RI.getOperand().setIsUndef();
2715 }
2716
Evan Chengdb9b1c32008-04-03 16:41:54 +00002717 ++I;
2718 return true;
2719}
2720
2721
David Greene25133302007-06-08 17:18:56 +00002722bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2723 mf_ = &fn;
Evan Cheng70071432008-02-13 03:01:43 +00002724 mri_ = &fn.getRegInfo();
David Greene25133302007-06-08 17:18:56 +00002725 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00002726 tri_ = tm_->getRegisterInfo();
David Greene25133302007-06-08 17:18:56 +00002727 tii_ = tm_->getInstrInfo();
2728 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00002729 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00002730
2731 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2732 << "********** Function: "
2733 << ((Value*)mf_->getFunction())->getName() << '\n';
2734
Dan Gohman6f0d0242008-02-10 18:45:23 +00002735 allocatableRegs_ = tri_->getAllocatableSet(fn);
2736 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2737 E = tri_->regclass_end(); I != E; ++I)
Bill Wendling2674d712008-01-04 08:59:18 +00002738 allocatableRCRegs_.insert(std::make_pair(*I,
Dan Gohman6f0d0242008-02-10 18:45:23 +00002739 tri_->getAllocatableSet(fn, *I)));
David Greene25133302007-06-08 17:18:56 +00002740
Gabor Greife510b3a2007-07-09 12:00:59 +00002741 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00002742 if (EnableJoining) {
2743 joinIntervals();
Bill Wendlingbebbded2008-12-19 02:09:57 +00002744 DEBUG({
2745 DOUT << "********** INTERVALS POST JOINING **********\n";
2746 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2747 I->second->print(DOUT, tri_);
2748 DOUT << "\n";
2749 }
2750 });
David Greene25133302007-06-08 17:18:56 +00002751 }
2752
Evan Chengc8d044e2008-02-15 18:24:29 +00002753 // Perform a final pass over the instructions and compute spill weights
2754 // and remove identity moves.
Evan Chengb3990d52008-10-27 23:21:01 +00002755 SmallVector<unsigned, 4> DeadDefs;
David Greene25133302007-06-08 17:18:56 +00002756 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2757 mbbi != mbbe; ++mbbi) {
2758 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002759 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00002760
2761 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2762 mii != mie; ) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002763 MachineInstr *MI = mii;
Evan Cheng04ee5a12009-01-20 19:12:24 +00002764 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
Evan Chenga971dbd2008-04-24 09:06:33 +00002765 if (JoinedCopies.count(MI)) {
2766 // Delete all coalesced copies.
Evan Cheng04ee5a12009-01-20 19:12:24 +00002767 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002768 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +00002769 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2770 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
Evan Chenga971dbd2008-04-24 09:06:33 +00002771 "Unrecognized copy instruction");
2772 DstReg = MI->getOperand(0).getReg();
2773 }
2774 if (MI->registerDefIsDead(DstReg)) {
2775 LiveInterval &li = li_->getInterval(DstReg);
2776 if (!ShortenDeadCopySrcLiveRange(li, MI))
2777 ShortenDeadCopyLiveRange(li, MI);
2778 }
2779 li_->RemoveMachineInstrFromMaps(MI);
2780 mii = mbbi->erase(mii);
2781 ++numPeep;
2782 continue;
2783 }
2784
Evan Cheng20580a12008-09-19 17:38:47 +00002785 // Now check if this is a remat'ed def instruction which is now dead.
2786 if (ReMatDefs.count(MI)) {
2787 bool isDead = true;
2788 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2789 const MachineOperand &MO = MI->getOperand(i);
Evan Chengb3990d52008-10-27 23:21:01 +00002790 if (!MO.isReg())
Evan Cheng20580a12008-09-19 17:38:47 +00002791 continue;
2792 unsigned Reg = MO.getReg();
Evan Cheng6792e902009-02-04 18:18:58 +00002793 if (!Reg)
2794 continue;
Evan Chengb3990d52008-10-27 23:21:01 +00002795 if (TargetRegisterInfo::isVirtualRegister(Reg))
2796 DeadDefs.push_back(Reg);
2797 if (MO.isDead())
2798 continue;
Evan Cheng20580a12008-09-19 17:38:47 +00002799 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2800 !mri_->use_empty(Reg)) {
2801 isDead = false;
2802 break;
2803 }
2804 }
2805 if (isDead) {
Evan Chengb3990d52008-10-27 23:21:01 +00002806 while (!DeadDefs.empty()) {
2807 unsigned DeadDef = DeadDefs.back();
2808 DeadDefs.pop_back();
2809 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2810 }
Evan Cheng20580a12008-09-19 17:38:47 +00002811 li_->RemoveMachineInstrFromMaps(mii);
2812 mii = mbbi->erase(mii);
Evan Chengfee2d692008-09-19 22:49:39 +00002813 continue;
Evan Chengb3990d52008-10-27 23:21:01 +00002814 } else
2815 DeadDefs.clear();
Evan Cheng20580a12008-09-19 17:38:47 +00002816 }
2817
Evan Chenga971dbd2008-04-24 09:06:33 +00002818 // If the move will be an identity move delete it
Evan Cheng04ee5a12009-01-20 19:12:24 +00002819 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
Evan Chenga971dbd2008-04-24 09:06:33 +00002820 if (isMove && SrcReg == DstReg) {
2821 if (li_->hasInterval(SrcReg)) {
2822 LiveInterval &RegInt = li_->getInterval(SrcReg);
Evan Cheng3c88d742008-03-18 08:26:47 +00002823 // If def of this move instruction is dead, remove its live range
2824 // from the dstination register's live interval.
Evan Cheng20580a12008-09-19 17:38:47 +00002825 if (MI->registerDefIsDead(DstReg)) {
2826 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2827 ShortenDeadCopyLiveRange(RegInt, MI);
Evan Cheng3c88d742008-03-18 08:26:47 +00002828 }
2829 }
Evan Cheng20580a12008-09-19 17:38:47 +00002830 li_->RemoveMachineInstrFromMaps(MI);
David Greene25133302007-06-08 17:18:56 +00002831 mii = mbbi->erase(mii);
2832 ++numPeep;
Evan Chenga971dbd2008-04-24 09:06:33 +00002833 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
David Greene25133302007-06-08 17:18:56 +00002834 SmallSet<unsigned, 4> UniqueUses;
Evan Cheng20580a12008-09-19 17:38:47 +00002835 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2836 const MachineOperand &mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002837 if (mop.isReg() && mop.getReg() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002838 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002839 unsigned reg = mop.getReg();
David Greene25133302007-06-08 17:18:56 +00002840 // Multiple uses of reg by the same instruction. It should not
2841 // contribute to spill weight again.
2842 if (UniqueUses.count(reg) != 0)
2843 continue;
2844 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002845 RegInt.weight +=
Evan Chengc3417602008-06-21 06:45:54 +00002846 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00002847 UniqueUses.insert(reg);
2848 }
2849 }
2850 ++mii;
2851 }
2852 }
2853 }
2854
2855 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +00002856 LiveInterval &LI = *I->second;
Dan Gohman6f0d0242008-02-10 18:45:23 +00002857 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
David Greene25133302007-06-08 17:18:56 +00002858 // If the live interval length is essentially zero, i.e. in every live
2859 // range the use follows def immediately, it doesn't make sense to spill
2860 // it and hope it will be easier to allocate for this li.
2861 if (isZeroLengthInterval(&LI))
2862 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002863 else {
2864 bool isLoad = false;
Evan Chengdc377862008-09-30 15:44:16 +00002865 SmallVector<LiveInterval*, 4> SpillIs;
2866 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00002867 // If all of the definitions of the interval are re-materializable,
2868 // it is a preferred candidate for spilling. If non of the defs are
2869 // loads, then it's potentially very cheap to re-materialize.
2870 // FIXME: this gets much more complicated once we support non-trivial
2871 // re-materialization.
2872 if (isLoad)
2873 LI.weight *= 0.9F;
2874 else
2875 LI.weight *= 0.5F;
2876 }
2877 }
David Greene25133302007-06-08 17:18:56 +00002878
2879 // Slightly prefer live interval that has been assigned a preferred reg.
Evan Cheng358dec52009-06-15 08:28:29 +00002880 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2881 if (Hint.first || Hint.second)
David Greene25133302007-06-08 17:18:56 +00002882 LI.weight *= 1.01F;
2883
2884 // Divide the weight of the interval by its size. This encourages
2885 // spilling of intervals that are large and have few uses, and
2886 // discourages spilling of small intervals with many uses.
Owen Anderson496bac52008-07-23 19:47:27 +00002887 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
David Greene25133302007-06-08 17:18:56 +00002888 }
2889 }
2890
2891 DEBUG(dump());
2892 return true;
2893}
2894
2895/// print - Implement the dump method.
2896void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2897 li_->print(O, m);
2898}
David Greene2c17c4d2007-09-06 16:18:45 +00002899
2900RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2901 return new SimpleRegisterCoalescing();
2902}
2903
2904// Make sure that anything that uses RegisterCoalescer pulls in this file...
2905DEFINING_FILE_FOR(SimpleRegisterCoalescing)