blob: 32a86047c52ed8a0b47161f988ce306612382202 [file] [log] [blame]
Chris Lattner179cdfb2002-08-09 20:08:03 +00001//===-- PhyRegAlloc.cpp ---------------------------------------------------===//
Vikram S. Adve12af1642001-11-08 04:48:50 +00002//
Chris Lattner179cdfb2002-08-09 20:08:03 +00003// Register allocation for LLVM.
4//
5//===----------------------------------------------------------------------===//
Ruchira Sasanka8e604792001-09-14 21:18:34 +00006
Chris Lattner70b2f562003-09-01 20:09:04 +00007#include "PhyRegAlloc.h"
Chris Lattner4309e732003-01-15 19:57:07 +00008#include "RegAllocCommon.h"
Chris Lattner9d4ed152003-01-15 21:14:01 +00009#include "RegClass.h"
Chris Lattnerc083dcc2003-09-01 20:05:47 +000010#include "IGNode.h"
Brian Gaeke874f4232003-09-21 02:50:21 +000011#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerf6ee49f2003-01-15 18:08:07 +000012#include "llvm/CodeGen/MachineInstrBuilder.h"
Vikram S. Advedabb41d2002-05-19 15:29:31 +000013#include "llvm/CodeGen/MachineInstrAnnot.h"
Misha Brukmanfce11432002-10-28 00:28:31 +000014#include "llvm/CodeGen/MachineFunction.h"
Chris Lattnere90fcb72002-12-28 20:35:34 +000015#include "llvm/CodeGen/MachineFunctionInfo.h"
Chris Lattner92ba2aa2003-01-14 23:05:08 +000016#include "llvm/CodeGen/FunctionLiveVarInfo.h"
Vikram S. Adve814030a2003-07-29 19:49:21 +000017#include "llvm/CodeGen/InstrSelection.h"
Chris Lattner14ab1ce2002-02-04 17:48:00 +000018#include "llvm/Analysis/LoopInfo.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000019#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000020#include "llvm/Function.h"
Chris Lattner37730942002-02-05 03:52:29 +000021#include "llvm/Type.h"
Vikram S. Advedabb41d2002-05-19 15:29:31 +000022#include "llvm/iOther.h"
Vikram S. Advef5af6362002-07-08 23:15:32 +000023#include "Support/STLExtras.h"
Vikram S. Advefeb32982003-08-12 22:22:24 +000024#include "Support/SetOperations.h"
Chris Lattner4bc23482002-09-15 07:07:55 +000025#include "Support/CommandLine.h"
Brian Gaekebd353fb2003-09-21 03:57:37 +000026#include <cmath>
Vikram S. Adve12af1642001-11-08 04:48:50 +000027
Chris Lattner70e60cb2002-05-22 17:08:27 +000028RegAllocDebugLevel_t DEBUG_RA;
Vikram S. Adve39c94e12002-09-14 23:05:33 +000029
Chris Lattner5ff62e92002-07-22 02:10:13 +000030static cl::opt<RegAllocDebugLevel_t, true>
31DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
32 cl::desc("enable register allocation debugging information"),
33 cl::values(
Vikram S. Adve39c94e12002-09-14 23:05:33 +000034 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
35 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
36 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
37 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
38 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
39 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
Chris Lattner5ff62e92002-07-22 02:10:13 +000040 0));
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000041
Brian Gaeke59b1c562003-09-24 17:50:28 +000042static cl::opt<bool>
43SaveRegAllocState("save-ra-state", cl::Hidden,
44 cl::desc("write reg. allocator state into module"));
45
Brian Gaekebf3c4cf2003-08-14 06:09:32 +000046FunctionPass *getRegisterAllocator(TargetMachine &T) {
Brian Gaeke4efe3422003-09-21 01:23:46 +000047 return new PhyRegAlloc (T);
Chris Lattner2f9b28e2002-02-04 15:54:09 +000048}
Chris Lattner6dd98a62002-02-04 00:33:08 +000049
Chris Lattner8474f6f2003-09-23 15:13:04 +000050void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<LoopInfo> ();
52 AU.addRequired<FunctionLiveVarInfo> ();
53}
54
55
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +000056
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000057//----------------------------------------------------------------------------
Misha Brukman37f92e22003-09-11 22:34:13 +000058// This method initially creates interference graphs (one in each reg class)
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000059// and IGNodeList (one in each IG). The actual nodes will be pushed later.
60//----------------------------------------------------------------------------
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000061void PhyRegAlloc::createIGNodeListsAndIGs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +000062 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000063
64 // hash map iterator
Brian Gaeke4efe3422003-09-21 01:23:46 +000065 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000066
67 // hash map end
Brian Gaeke4efe3422003-09-21 01:23:46 +000068 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000069
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000070 for (; HMI != HMIEnd ; ++HMI ) {
71 if (HMI->first) {
72 LiveRange *L = HMI->second; // get the LiveRange
73 if (!L) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +000074 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +000075 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
Vikram S. Adve39c94e12002-09-14 23:05:33 +000076 << RAV(HMI->first) << "****\n";
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000077 continue;
78 }
Vikram S. Adve39c94e12002-09-14 23:05:33 +000079
80 // if the Value * is not null, and LR is not yet written to the IGNodeList
Chris Lattner7e708292002-06-25 16:13:24 +000081 if (!(L->getUserIGNode()) ) {
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000082 RegClass *const RC = // RegClass of first value in the LR
Brian Gaeke59b1c562003-09-24 17:50:28 +000083 RegClassList[ L->getRegClassID() ];
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000084 RC->addLRToIG(L); // add this LR to an IG
85 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +000086 }
87 }
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000088
89 // init RegClassList
Chris Lattner7e708292002-06-25 16:13:24 +000090 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000091 RegClassList[rc]->createInterferenceGraph();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000092
Chris Lattnerc083dcc2003-09-01 20:05:47 +000093 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000094}
95
96
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000097//----------------------------------------------------------------------------
98// This method will add all interferences at for a given instruction.
Misha Brukman37f92e22003-09-11 22:34:13 +000099// Interference occurs only if the LR of Def (Inst or Arg) is of the same reg
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000100// class as that of live var. The live var passed to this function is the
101// LVset AFTER the instruction
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000102//----------------------------------------------------------------------------
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000103
Chris Lattner296b7732002-02-05 02:52:05 +0000104void PhyRegAlloc::addInterference(const Value *Def,
105 const ValueSet *LVSet,
106 bool isCallInst) {
Chris Lattner296b7732002-02-05 02:52:05 +0000107 ValueSet::const_iterator LIt = LVSet->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000108
109 // get the live range of instruction
Brian Gaeke4efe3422003-09-21 01:23:46 +0000110 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000111
112 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
113 assert( IGNodeOfDef );
114
115 RegClass *const RCOfDef = LROfDef->getRegClass();
116
117 // for each live var in live variable set
Chris Lattner7e708292002-06-25 16:13:24 +0000118 for ( ; LIt != LVSet->end(); ++LIt) {
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000119
Vikram S. Advef5af6362002-07-08 23:15:32 +0000120 if (DEBUG_RA >= RA_DEBUG_Verbose)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000121 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000122
123 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000124 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000125
126 // LROfVar can be null if it is a const since a const
127 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000128 if (LROfVar)
129 if (LROfDef != LROfVar) // do not set interf for same LR
130 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
131 RCOfDef->setInterference( LROfDef, LROfVar);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000132 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000133}
134
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000135
136//----------------------------------------------------------------------------
137// For a call instruction, this method sets the CallInterference flag in
138// the LR of each variable live int the Live Variable Set live after the
139// call instruction (except the return value of the call instruction - since
140// the return value does not interfere with that call itself).
141//----------------------------------------------------------------------------
142
143void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
Chris Lattner296b7732002-02-05 02:52:05 +0000144 const ValueSet *LVSetAft) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000145 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000146 std::cerr << "\n For call inst: " << *MInst;
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000147
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000148 // for each live var in live variable set after machine inst
Vikram S. Adve65b2f402003-07-02 01:24:00 +0000149 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
150 LIt != LEnd; ++LIt) {
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000151
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000152 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000153 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000154
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000155 // LR can be null if it is a const since a const
156 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000157 if (LR ) {
158 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000159 std::cerr << "\n\tLR after Call: ";
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000160 printSet(*LR);
161 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000162 LR->setCallInterference();
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000163 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000164 std::cerr << "\n ++After adding call interference for LR: " ;
Chris Lattner296b7732002-02-05 02:52:05 +0000165 printSet(*LR);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000166 }
167 }
168
169 }
170
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000171 // Now find the LR of the return value of the call
172 // We do this because, we look at the LV set *after* the instruction
173 // to determine, which LRs must be saved across calls. The return value
174 // of the call is live in this set - but it does not interfere with call
175 // (i.e., we can allocate a volatile register to the return value)
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000176 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
177
178 if (const Value *RetVal = argDesc->getReturnValue()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000179 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000180 assert( RetValLR && "No LR for RetValue of call");
181 RetValLR->clearCallInterference();
182 }
183
184 // If the CALL is an indirect call, find the LR of the function pointer.
185 // That has a call interference because it conflicts with outgoing args.
Chris Lattner7e708292002-06-25 16:13:24 +0000186 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000187 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000188 assert( AddrValLR && "No LR for indirect addr val of call");
189 AddrValLR->setCallInterference();
190 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000191}
192
193
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000194//----------------------------------------------------------------------------
195// This method will walk thru code and create interferences in the IG of
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000196// each RegClass. Also, this method calculates the spill cost of each
197// Live Range (it is done in this method to save another pass over the code).
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000198//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000199
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000200void PhyRegAlloc::buildInterferenceGraphs()
201{
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000202 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000203 std::cerr << "Creating interference graphs ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000204
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000205 unsigned BBLoopDepthCost;
Brian Gaeke4efe3422003-09-21 01:23:46 +0000206 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000207 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000208 const MachineBasicBlock &MBB = *BBI;
209 const BasicBlock *BB = MBB.getBasicBlock();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000210
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000211 // find the 10^(loop_depth) of this BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000212 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000213
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000214 // get the iterator for machine instructions
Chris Lattnerf726e772002-10-28 19:22:04 +0000215 MachineBasicBlock::const_iterator MII = MBB.begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000216
217 // iterate over all the machine instructions in BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000218 for ( ; MII != MBB.end(); ++MII) {
219 const MachineInstr *MInst = *MII;
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000220
221 // get the LV set after the instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000222 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
223 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000224
Chris Lattner7e708292002-06-25 16:13:24 +0000225 if (isCallInst ) {
Misha Brukman37f92e22003-09-11 22:34:13 +0000226 // set the isCallInterference flag of each live range which extends
227 // across this call instruction. This information is used by graph
228 // coloring algorithm to avoid allocating volatile colors to live ranges
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000229 // that span across calls (since they have to be saved/restored)
Chris Lattner748697d2002-02-05 04:20:12 +0000230 setCallInterferences(MInst, &LVSetAI);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000231 }
232
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000233 // iterate over all MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000234 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
235 OpE = MInst->end(); OpI != OpE; ++OpI) {
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000236 if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
Chris Lattner748697d2002-02-05 04:20:12 +0000237 addInterference(*OpI, &LVSetAI, isCallInst);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000238
239 // Calculate the spill cost of each live range
Brian Gaeke4efe3422003-09-21 01:23:46 +0000240 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
Chris Lattner2f898d22002-02-05 06:02:59 +0000241 if (LR) LR->addSpillCost(BBLoopDepthCost);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000242 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000243
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000244 // if there are multiple defs in this instruction e.g. in SETX
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000245 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000246 addInterf4PseudoInstr(MInst);
247
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000248 // Also add interference for any implicit definitions in a machine
249 // instr (currently, only calls have this).
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000250 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000251 for (unsigned z=0; z < NumOfImpRefs; z++)
252 if (MInst->getImplicitOp(z).opIsDefOnly() ||
253 MInst->getImplicitOp(z).opIsDefAndUse())
254 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +0000255
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000256 } // for all machine instructions in BB
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000257 } // for all BBs in function
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000258
Misha Brukman37f92e22003-09-11 22:34:13 +0000259 // add interferences for function arguments. Since there are no explicit
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000260 // defs in the function for args, we have to add them manually
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000261 addInterferencesForArgs();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000262
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000263 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000264 std::cerr << "Interference graphs calculated!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000265}
266
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000267
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000268//--------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000269// Pseudo-instructions may be expanded to multiple instructions by the
270// assembler. Consequently, all the operands must get distinct registers.
271// Therefore, we mark all operands of a pseudo-instruction as interfering
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000272// with one another.
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000273//--------------------------------------------------------------------------
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000274
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000275void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000276 bool setInterf = false;
277
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000278 // iterate over MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000279 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
280 ItE = MInst->end(); It1 != ItE; ++It1) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000281 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000282 assert((LROfOp1 || !It1.isUseOnly())&&"No LR for Def in PSEUDO insruction");
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000283
Chris Lattner2f898d22002-02-05 06:02:59 +0000284 MachineInstr::const_val_op_iterator It2 = It1;
Chris Lattner7e708292002-06-25 16:13:24 +0000285 for (++It2; It2 != ItE; ++It2) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000286 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000287
Chris Lattner2f898d22002-02-05 06:02:59 +0000288 if (LROfOp2) {
289 RegClass *RCOfOp1 = LROfOp1->getRegClass();
290 RegClass *RCOfOp2 = LROfOp2->getRegClass();
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000291
Chris Lattner7e708292002-06-25 16:13:24 +0000292 if (RCOfOp1 == RCOfOp2 ){
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000293 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000294 setInterf = true;
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000295 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000296 } // if Op2 has a LR
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000297 } // for all other defs in machine instr
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000298 } // for all operands in an instruction
299
Chris Lattner2f898d22002-02-05 06:02:59 +0000300 if (!setInterf && MInst->getNumOperands() > 2) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000301 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
302 std::cerr << *MInst;
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000303 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000304 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000305}
306
307
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000308//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000309// This method adds interferences for incoming arguments to a function.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000310//----------------------------------------------------------------------------
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000311
Chris Lattner296b7732002-02-05 02:52:05 +0000312void PhyRegAlloc::addInterferencesForArgs() {
313 // get the InSet of root BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000314 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000315
Chris Lattnerf726e772002-10-28 19:22:04 +0000316 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000317 // add interferences between args and LVars at start
318 addInterference(AI, &InSet, false);
319
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000320 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000321 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000322 }
323}
324
325
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000326//----------------------------------------------------------------------------
327// This method is called after register allocation is complete to set the
Misha Brukman37f92e22003-09-11 22:34:13 +0000328// allocated registers in the machine code. This code will add register numbers
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000329// to MachineOperands that contain a Value. Also it calls target specific
330// methods to produce caller saving instructions. At the end, it adds all
331// additional instructions produced by the register allocator to the
332// instruction stream.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000333//----------------------------------------------------------------------------
Vikram S. Adve48762092002-04-25 04:34:15 +0000334
335//-----------------------------
336// Utility functions used below
337//-----------------------------
338inline void
Vikram S. Advecb202e32002-10-11 16:12:40 +0000339InsertBefore(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000340 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000341 MachineBasicBlock::iterator& MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000342{
Chris Lattnerf726e772002-10-28 19:22:04 +0000343 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000344 ++MII;
345}
346
347inline void
348InsertAfter(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000349 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000350 MachineBasicBlock::iterator& MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000351{
352 ++MII; // insert before the next instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000353 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000354}
355
356inline void
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000357DeleteInstruction(MachineBasicBlock& MBB,
358 MachineBasicBlock::iterator& MII)
359{
360 MII = MBB.erase(MII);
361}
362
363inline void
Vikram S. Advecb202e32002-10-11 16:12:40 +0000364SubstituteInPlace(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000365 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000366 MachineBasicBlock::iterator MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000367{
368 *MII = newMI;
369}
370
371inline void
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000372PrependInstructions(std::vector<MachineInstr *> &IBef,
Chris Lattnerf726e772002-10-28 19:22:04 +0000373 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000374 MachineBasicBlock::iterator& MII,
Vikram S. Adve48762092002-04-25 04:34:15 +0000375 const std::string& msg)
376{
377 if (!IBef.empty())
378 {
379 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000380 std::vector<MachineInstr *>::iterator AdIt;
Vikram S. Adve48762092002-04-25 04:34:15 +0000381 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
382 {
383 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000384 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
385 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000386 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000387 InsertBefore(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000388 }
389 }
390}
391
392inline void
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000393AppendInstructions(std::vector<MachineInstr *> &IAft,
Chris Lattnerf726e772002-10-28 19:22:04 +0000394 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000395 MachineBasicBlock::iterator& MII,
Vikram S. Adve48762092002-04-25 04:34:15 +0000396 const std::string& msg)
397{
398 if (!IAft.empty())
399 {
400 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000401 std::vector<MachineInstr *>::iterator AdIt;
Chris Lattner7e708292002-06-25 16:13:24 +0000402 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
Vikram S. Adve48762092002-04-25 04:34:15 +0000403 {
Chris Lattner7e708292002-06-25 16:13:24 +0000404 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000405 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
406 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000407 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000408 InsertAfter(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000409 }
410 }
411}
412
Brian Gaeke4efe3422003-09-21 01:23:46 +0000413bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000414{
Vikram S. Adve814030a2003-07-29 19:49:21 +0000415 bool instrNeedsSpills = false;
416
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000417 // First, set the registers for operands in the machine instruction
418 // if a register was successfully allocated. Do this first because we
419 // will need to know which registers are already used by this instr'n.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000420 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
421 {
422 MachineOperand& Op = MInst->getOperand(OpNum);
423 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
424 Op.getType() == MachineOperand::MO_CCRegister)
425 {
426 const Value *const Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000427 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000428 // Remember if any operand needs spilling
429 instrNeedsSpills |= LR->isMarkedForSpill();
430
431 // An operand may have a color whether or not it needs spilling
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000432 if (LR->hasColor())
433 MInst->SetRegForOperand(OpNum,
Brian Gaeke59b1c562003-09-24 17:50:28 +0000434 MRI.getUnifiedRegNum(LR->getRegClassID(),
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000435 LR->getColor()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000436 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000437 }
438 } // for each operand
Vikram S. Adve814030a2003-07-29 19:49:21 +0000439
440 return instrNeedsSpills;
441}
442
443void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
444 MachineBasicBlock &MBB)
445{
446 MachineInstr* MInst = *MII;
447 unsigned Opcode = MInst->getOpCode();
448
449 // Reset tmp stack positions so they can be reused for each machine instr.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000450 MF->getInfo()->popAllTempValues();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000451
452 // Mark the operands for which regs have been allocated.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000453 bool instrNeedsSpills = markAllocatedRegs(*MII);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000454
455#ifndef NDEBUG
456 // Mark that the operands have been updated. Later,
457 // setRelRegsUsedByThisInst() is called to find registers used by each
458 // MachineInst, and it should not be used for an instruction until
459 // this is done. This flag just serves as a sanity check.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000460 OperandsColoredMap[MInst] = true;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000461#endif
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000462
Vikram S. Advebc001b22003-07-25 21:06:09 +0000463 // Now insert caller-saving code before/after the call.
464 // Do this before inserting spill code since some registers must be
465 // used by save/restore and spill code should not use those registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000466 if (TM.getInstrInfo().isCall(Opcode)) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000467 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Adve814030a2003-07-29 19:49:21 +0000468 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
469 MBB.getBasicBlock());
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000470 }
Vikram S. Advebc001b22003-07-25 21:06:09 +0000471
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000472 // Now insert spill code for remaining operands not allocated to
473 // registers. This must be done even for call return instructions
474 // since those are not handled by the special code above.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000475 if (instrNeedsSpills)
476 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
477 {
478 MachineOperand& Op = MInst->getOperand(OpNum);
479 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
480 Op.getType() == MachineOperand::MO_CCRegister)
481 {
482 const Value* Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000483 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000484 if (LR->isMarkedForSpill())
485 insertCode4SpilledLR(LR, MII, MBB, OpNum);
486 }
487 } // for each operand
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000488}
489
490void PhyRegAlloc::updateMachineCode()
491{
Chris Lattner7e708292002-06-25 16:13:24 +0000492 // Insert any instructions needed at method entry
Brian Gaeke4efe3422003-09-21 01:23:46 +0000493 MachineBasicBlock::iterator MII = MF->front().begin();
494 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
Chris Lattner7e708292002-06-25 16:13:24 +0000495 "At function entry: \n");
496 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
497 "InstrsAfter should be unnecessary since we are just inserting at "
498 "the function entry point here.");
Vikram S. Adve48762092002-04-25 04:34:15 +0000499
Brian Gaeke4efe3422003-09-21 01:23:46 +0000500 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000501 BBI != BBE; ++BBI) {
Vikram S. Advecb202e32002-10-11 16:12:40 +0000502
Chris Lattnerf726e772002-10-28 19:22:04 +0000503 MachineBasicBlock &MBB = *BBI;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000504
505 // Iterate over all machine instructions in BB and mark operands with
506 // their assigned registers or insert spill code, as appropriate.
507 // Also, fix operands of call/return instructions.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000508 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000509 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
510 updateInstruction(MII, MBB);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000511
512 // Now, move code out of delay slots of branches and returns if needed.
513 // (Also, move "after" code from calls to the last delay slot instruction.)
514 // Moving code out of delay slots is needed in 2 situations:
515 // (1) If this is a branch and it needs instructions inserted after it,
516 // move any existing instructions out of the delay slot so that the
517 // instructions can go into the delay slot. This only supports the
518 // case that #instrsAfter <= #delay slots.
519 //
520 // (2) If any instruction in the delay slot needs
521 // instructions inserted, move it out of the delay slot and before the
522 // branch because putting code before or after it would be VERY BAD!
523 //
524 // If the annul bit of the branch is set, neither of these is legal!
525 // If so, we need to handle spill differently but annulling is not yet used.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000526 for (MachineBasicBlock::iterator MII = MBB.begin();
527 MII != MBB.end(); ++MII)
528 if (unsigned delaySlots =
529 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
530 {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000531 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
532
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000533 // Check the 2 conditions above:
534 // (1) Does a branch need instructions added after it?
535 // (2) O/w does delay slot instr. need instrns before or after?
Vikram S. Adve814030a2003-07-29 19:49:21 +0000536 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
537 TM.getInstrInfo().isReturn(MInst->getOpCode()));
538 bool cond1 = (isBranch &&
539 AddedInstrMap.count(MInst) &&
540 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
541 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
542 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
543 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000544
545 if (cond1 || cond2)
546 {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000547 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
548 "FIXME: Moving an annulled delay slot instruction!");
549 assert(delaySlots==1 &&
550 "InsertBefore does not yet handle >1 delay slots!");
551 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000552
553 // In case (1), delete it and don't replace with anything!
554 // Otherwise (i.e., case (2) only) replace it with a NOP.
555 if (cond1) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000556 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
557 --MII; // reset MII for ++MII of loop
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000558 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000559 else
560 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
561 MBB, MII+1); // replace with NOP
562
563 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000564 std::cerr << "\nRegAlloc: Moved instr. with added code: "
Vikram S. Adve814030a2003-07-29 19:49:21 +0000565 << *DelaySlotMI
566 << " out of delay slots of instr: " << *MInst;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000567 }
568 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000569 else
570 // For non-branch instr with delay slots (probably a call), move
571 // InstrAfter to the instr. in the last delay slot.
572 move2DelayedInstr(*MII, *(MII+delaySlots));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000573 }
574
575 // Finally iterate over all instructions in BB and insert before/after
Vikram S. Advebc001b22003-07-25 21:06:09 +0000576 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000577 MachineInstr *MInst = *MII;
Vikram S. Advebc001b22003-07-25 21:06:09 +0000578
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000579 // do not process Phis
Vikram S. Advebc001b22003-07-25 21:06:09 +0000580 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000581 continue;
582
Vikram S. Advebc001b22003-07-25 21:06:09 +0000583 // if there are any added instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000584 if (AddedInstrMap.count(MInst)) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000585 AddedInstrns &CallAI = AddedInstrMap[MInst];
586
587#ifndef NDEBUG
Vikram S. Adve814030a2003-07-29 19:49:21 +0000588 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
589 TM.getInstrInfo().isReturn(MInst->getOpCode()));
590 assert((!isBranch ||
591 AddedInstrMap[MInst].InstrnsAfter.size() <=
592 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
593 "Cannot put more than #delaySlots instrns after "
594 "branch or return! Need to handle temps differently.");
595#endif
596
597#ifndef NDEBUG
Vikram S. Advebc001b22003-07-25 21:06:09 +0000598 // Temporary sanity checking code to detect whether the same machine
599 // instruction is ever inserted twice before/after a call.
600 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000601 std::set<const MachineInstr*> instrsSeen;
602 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
603 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
604 "Duplicate machine instruction in InstrnsBefore!");
605 instrsSeen.insert(CallAI.InstrnsBefore[i]);
606 }
607 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
608 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
609 "Duplicate machine instruction in InstrnsBefore/After!");
610 instrsSeen.insert(CallAI.InstrnsAfter[i]);
611 }
612#endif
613
614 // Now add the instructions before/after this MI.
615 // We do this here to ensure that spill for an instruction is inserted
616 // as close as possible to an instruction (see above insertCode4Spill)
Vikram S. Advebc001b22003-07-25 21:06:09 +0000617 if (! CallAI.InstrnsBefore.empty())
618 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
619
620 if (! CallAI.InstrnsAfter.empty())
621 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
622
623 } // if there are any added instructions
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000624 } // for each machine instruction
Ruchira Sasanka0931a012001-09-15 19:06:58 +0000625 }
626}
627
628
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000629//----------------------------------------------------------------------------
630// This method inserts spill code for AN operand whose LR was spilled.
631// This method may be called several times for a single machine instruction
632// if it contains many spilled operands. Each time it is called, it finds
633// a register which is not live at that instruction and also which is not
634// used by other spilled operands of the same instruction. Then it uses
Misha Brukman37f92e22003-09-11 22:34:13 +0000635// this register temporarily to accommodate the spilled value.
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000636//----------------------------------------------------------------------------
Vikram S. Advebc001b22003-07-25 21:06:09 +0000637
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000638void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000639 MachineBasicBlock::iterator& MII,
640 MachineBasicBlock &MBB,
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000641 const unsigned OpNum) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000642 MachineInstr *MInst = *MII;
643 const BasicBlock *BB = MBB.getBasicBlock();
644
Vikram S. Advead9c9782002-09-28 17:02:40 +0000645 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
646 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
647 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
648 "Return value of a ret must be handled elsewhere");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000649
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000650 MachineOperand& Op = MInst->getOperand(OpNum);
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000651 bool isDef = Op.opIsDefOnly();
652 bool isDefAndUse = Op.opIsDefAndUse();
Vikram S. Advebc001b22003-07-25 21:06:09 +0000653 unsigned RegType = MRI.getRegTypeForLR(LR);
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000654 int SpillOff = LR->getSpillOffFromFP();
655 RegClass *RC = LR->getRegClass();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000656
657 // Get the live-variable set to find registers free before this instr.
Vikram S. Advefeb32982003-08-12 22:22:24 +0000658 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
659
660#ifndef NDEBUG
661 // If this instr. is in the delay slot of a branch or return, we need to
662 // include all live variables before that branch or return -- we don't want to
663 // trample those! Verify that the set is included in the LV set before MInst.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000664 if (MII != MBB.begin()) {
665 MachineInstr *PredMI = *(MII-1);
Vikram S. Advefeb32982003-08-12 22:22:24 +0000666 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
667 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
668 .empty() && "Live-var set before branch should be included in "
669 "live-var set of each delay slot instruction!");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000670 }
Vikram S. Advefeb32982003-08-12 22:22:24 +0000671#endif
Vikram S. Adve00521d72001-11-12 23:26:35 +0000672
Brian Gaeke4efe3422003-09-21 01:23:46 +0000673 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000674
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000675 std::vector<MachineInstr*> MIBef, MIAft;
676 std::vector<MachineInstr*> AdIMid;
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000677
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000678 // Choose a register to hold the spilled value, if one was not preallocated.
679 // This may insert code before and after MInst to free up the value. If so,
680 // this code should be first/last in the spill sequence before/after MInst.
681 int TmpRegU=(LR->hasColor()
Brian Gaeke59b1c562003-09-24 17:50:28 +0000682 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000683 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000684
Vikram S. Advef5af6362002-07-08 23:15:32 +0000685 // Set the operand first so that it this register does not get used
686 // as a scratch register for later calls to getUsableUniRegAtMI below
687 MInst->SetRegForOperand(OpNum, TmpRegU);
688
689 // get the added instructions for this instruction
Chris Lattner0b0ffa02002-04-09 05:13:04 +0000690 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Advef5af6362002-07-08 23:15:32 +0000691
692 // We may need a scratch register to copy the spilled value to/from memory.
693 // This may itself have to insert code to free up a scratch register.
694 // Any such code should go before (after) the spill code for a load (store).
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000695 // The scratch reg is not marked as used because it is only used
696 // for the copy and not used across MInst.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000697 int scratchRegType = -1;
698 int scratchReg = -1;
699 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
700 {
Chris Lattner27a08932002-10-22 23:16:21 +0000701 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
702 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000703 assert(scratchReg != MRI.getInvalidRegNum());
Vikram S. Advef5af6362002-07-08 23:15:32 +0000704 }
705
706 if (!isDef || isDefAndUse) {
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000707 // for a USE, we have to load the value of LR from stack to a TmpReg
708 // and use the TmpReg as one operand of instruction
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000709
Vikram S. Advef5af6362002-07-08 23:15:32 +0000710 // actual loading instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000711 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
712 RegType, scratchReg);
Ruchira Sasanka226f1f02001-11-08 19:11:30 +0000713
Vikram S. Advef5af6362002-07-08 23:15:32 +0000714 // the actual load should be after the instructions to free up TmpRegU
715 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
716 AdIMid.clear();
717 }
718
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000719 if (isDef || isDefAndUse) { // if this is a Def
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000720 // for a DEF, we have to store the value produced by this instruction
721 // on the stack position allocated for this LR
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000722
Vikram S. Advef5af6362002-07-08 23:15:32 +0000723 // actual storing instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000724 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
725 RegType, scratchReg);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000726
Vikram S. Advef5af6362002-07-08 23:15:32 +0000727 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000728 } // if !DEF
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000729
Vikram S. Advef5af6362002-07-08 23:15:32 +0000730 // Finally, insert the entire spill code sequences before/after MInst
731 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
732 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
733
Chris Lattner7e708292002-06-25 16:13:24 +0000734 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000735 std::cerr << "\nFor Inst:\n " << *MInst;
736 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
737 std::cerr << "; added Instructions:";
Anand Shuklad58290e2002-07-09 19:18:56 +0000738 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
739 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
Chris Lattner7e708292002-06-25 16:13:24 +0000740 }
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000741}
742
743
Vikram S. Adve814030a2003-07-29 19:49:21 +0000744//----------------------------------------------------------------------------
Misha Brukman37f92e22003-09-11 22:34:13 +0000745// This method inserts caller saving/restoring instructions before/after
Vikram S. Adve814030a2003-07-29 19:49:21 +0000746// a call machine instruction. The caller saving/restoring instructions are
747// inserted like:
748// ** caller saving instructions
749// other instructions inserted for the call by ColorCallArg
750// CALL instruction
751// other instructions inserted for the call ColorCallArg
752// ** caller restoring instructions
753//----------------------------------------------------------------------------
754
755void
756PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
757 std::vector<MachineInstr*> &instrnsAfter,
758 MachineInstr *CallMI,
759 const BasicBlock *BB)
760{
761 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
762
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000763 // hash set to record which registers were saved/restored
Vikram S. Adve814030a2003-07-29 19:49:21 +0000764 hash_set<unsigned> PushedRegSet;
765
766 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
767
768 // if the call is to a instrumentation function, do not insert save and
769 // restore instructions the instrumentation function takes care of save
770 // restore for volatile regs.
771 //
772 // FIXME: this should be made general, not specific to the reoptimizer!
Vikram S. Adve814030a2003-07-29 19:49:21 +0000773 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
774 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
775
776 // Now check if the call has a return value (using argDesc) and if so,
777 // find the LR of the TmpInstruction representing the return value register.
778 // (using the last or second-last *implicit operand* of the call MI).
779 // Insert it to to the PushedRegSet since we must not save that register
780 // and restore it after the call.
781 // We do this because, we look at the LV set *after* the instruction
782 // to determine, which LRs must be saved across calls. The return value
783 // of the call is live in this set - but we must not save/restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000784 if (const Value *origRetVal = argDesc->getReturnValue()) {
785 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
786 (argDesc->getIndirectFuncPtr()? 1 : 2));
787 const TmpInstruction* tmpRetVal =
788 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
789 assert(tmpRetVal->getOperand(0) == origRetVal &&
790 tmpRetVal->getType() == origRetVal->getType() &&
791 "Wrong implicit ref?");
Brian Gaeke4efe3422003-09-21 01:23:46 +0000792 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000793 assert(RetValLR && "No LR for RetValue of call");
794
795 if (! RetValLR->isMarkedForSpill())
796 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
797 RetValLR->getColor()));
798 }
799
800 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
801 ValueSet::const_iterator LIt = LVSetAft.begin();
802
803 // for each live var in live variable set after machine inst
804 for( ; LIt != LVSetAft.end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000805 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000806 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000807
808 // LR can be null if it is a const since a const
809 // doesn't have a dominating def - see Assumptions above
810 if( LR ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000811 if(! LR->isMarkedForSpill()) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000812 assert(LR->hasColor() && "LR is neither spilled nor colored?");
813 unsigned RCID = LR->getRegClassID();
814 unsigned Color = LR->getColor();
815
816 if (MRI.isRegVolatile(RCID, Color) ) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000817 // if this is a call to the first-level reoptimizer
818 // instrumentation entry point, and the register is not
819 // modified by call, don't save and restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000820 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
821 continue;
822
823 // if the value is in both LV sets (i.e., live before and after
824 // the call machine instruction)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000825 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
826
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000827 // if we haven't already pushed this register...
Vikram S. Adve814030a2003-07-29 19:49:21 +0000828 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000829 unsigned RegType = MRI.getRegTypeForLR(LR);
830
831 // Now get two instructions - to push on stack and pop from stack
832 // and add them to InstrnsBefore and InstrnsAfter of the
833 // call instruction
Vikram S. Adve814030a2003-07-29 19:49:21 +0000834 int StackOff =
Brian Gaeke4efe3422003-09-21 01:23:46 +0000835 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000836
837 //---- Insert code for pushing the reg on stack ----------
838
839 std::vector<MachineInstr*> AdIBef, AdIAft;
840
841 // We may need a scratch register to copy the saved value
842 // to/from memory. This may itself have to insert code to
843 // free up a scratch register. Any such code should go before
844 // the save code. The scratch register, if any, is by default
845 // temporary and not "used" by the instruction unless the
846 // copy code itself decides to keep the value in the scratch reg.
847 int scratchRegType = -1;
848 int scratchReg = -1;
849 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
850 { // Find a register not live in the LVSet before CallMI
851 const ValueSet &LVSetBef =
852 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
853 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
854 CallMI, AdIBef, AdIAft);
855 assert(scratchReg != MRI.getInvalidRegNum());
856 }
857
858 if (AdIBef.size() > 0)
859 instrnsBefore.insert(instrnsBefore.end(),
860 AdIBef.begin(), AdIBef.end());
861
862 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
863 StackOff, RegType, scratchReg);
864
865 if (AdIAft.size() > 0)
866 instrnsBefore.insert(instrnsBefore.end(),
867 AdIAft.begin(), AdIAft.end());
868
869 //---- Insert code for popping the reg from the stack ----------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000870 AdIBef.clear();
871 AdIAft.clear();
872
873 // We may need a scratch register to copy the saved value
874 // from memory. This may itself have to insert code to
875 // free up a scratch register. Any such code should go
876 // after the save code. As above, scratch is not marked "used".
Vikram S. Adve814030a2003-07-29 19:49:21 +0000877 scratchRegType = -1;
878 scratchReg = -1;
879 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
880 { // Find a register not live in the LVSet after CallMI
881 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
882 CallMI, AdIBef, AdIAft);
883 assert(scratchReg != MRI.getInvalidRegNum());
884 }
885
886 if (AdIBef.size() > 0)
887 instrnsAfter.insert(instrnsAfter.end(),
888 AdIBef.begin(), AdIBef.end());
889
890 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
891 Reg, RegType, scratchReg);
892
893 if (AdIAft.size() > 0)
894 instrnsAfter.insert(instrnsAfter.end(),
895 AdIAft.begin(), AdIAft.end());
896
897 PushedRegSet.insert(Reg);
898
899 if(DEBUG_RA) {
900 std::cerr << "\nFor call inst:" << *CallMI;
901 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
902 for_each(instrnsBefore.begin(), instrnsBefore.end(),
903 std::mem_fun(&MachineInstr::dump));
904 std::cerr << " -and After:\n\t ";
905 for_each(instrnsAfter.begin(), instrnsAfter.end(),
906 std::mem_fun(&MachineInstr::dump));
907 }
908 } // if not already pushed
Vikram S. Adve814030a2003-07-29 19:49:21 +0000909 } // if LR has a volatile color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000910 } // if LR has color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000911 } // if there is a LR for Var
Vikram S. Adve814030a2003-07-29 19:49:21 +0000912 } // for each value in the LV set after instruction
913}
914
915
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000916//----------------------------------------------------------------------------
917// We can use the following method to get a temporary register to be used
918// BEFORE any given machine instruction. If there is a register available,
919// this method will simply return that register and set MIBef = MIAft = NULL.
920// Otherwise, it will return a register and MIAft and MIBef will contain
921// two instructions used to free up this returned register.
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000922// Returned register number is the UNIFIED register number
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000923//----------------------------------------------------------------------------
924
Vikram S. Advef5af6362002-07-08 23:15:32 +0000925int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
926 const ValueSet *LVSetBef,
927 MachineInstr *MInst,
928 std::vector<MachineInstr*>& MIBef,
929 std::vector<MachineInstr*>& MIAft) {
Chris Lattner133f0792002-10-28 04:45:29 +0000930 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000931
Vikram S. Advebc001b22003-07-25 21:06:09 +0000932 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000933
934 if (RegU == -1) {
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000935 // we couldn't find an unused register. Generate code to free up a reg by
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000936 // saving it on stack and restoring after the instruction
Vikram S. Advef5af6362002-07-08 23:15:32 +0000937
Brian Gaeke4efe3422003-09-21 01:23:46 +0000938 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve12af1642001-11-08 04:48:50 +0000939
Vikram S. Advebc001b22003-07-25 21:06:09 +0000940 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000941
Vikram S. Advef5af6362002-07-08 23:15:32 +0000942 // Check if we need a scratch register to copy this register to memory.
943 int scratchRegType = -1;
944 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
945 {
Chris Lattner133f0792002-10-28 04:45:29 +0000946 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
947 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000948 assert(scratchReg != MRI.getInvalidRegNum());
949
950 // We may as well hold the value in the scratch register instead
951 // of copying it to memory and back. But we have to mark the
952 // register as used by this instruction, so it does not get used
953 // as a scratch reg. by another operand or anyone else.
Chris Lattner3fd1f5b2003-08-05 22:11:13 +0000954 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000955 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
956 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
957 }
958 else
959 { // the register can be copied directly to/from memory so do it.
960 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
961 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
962 }
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000963 }
Vikram S. Advef5af6362002-07-08 23:15:32 +0000964
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000965 return RegU;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000966}
967
Vikram S. Adve814030a2003-07-29 19:49:21 +0000968
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000969//----------------------------------------------------------------------------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000970// This method is called to get a new unused register that can be used
Misha Brukman37f92e22003-09-11 22:34:13 +0000971// to accommodate a temporary value. This method may be called several times
Vikram S. Adve814030a2003-07-29 19:49:21 +0000972// for a single machine instruction. Each time it is called, it finds a
973// register which is not live at that instruction and also which is not used
974// by other spilled operands of the same instruction. Return register number
975// is relative to the register class, NOT the unified number.
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000976//----------------------------------------------------------------------------
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000977
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000978int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +0000979 const int RegType,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000980 const MachineInstr *MInst,
981 const ValueSet* LVSetBef) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000982 RC->clearColorsUsed(); // Reset array
Vikram S. Adve814030a2003-07-29 19:49:21 +0000983
984 if (LVSetBef == NULL) {
985 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
986 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
987 }
988
Chris Lattner296b7732002-02-05 02:52:05 +0000989 ValueSet::const_iterator LIt = LVSetBef->begin();
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000990
991 // for each live var in live variable set after machine inst
Chris Lattner7e708292002-06-25 16:13:24 +0000992 for ( ; LIt != LVSetBef->end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000993 // Get the live range corresponding to live var, and its RegClass
Brian Gaeke4efe3422003-09-21 01:23:46 +0000994 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000995
996 // LR can be null if it is a const since a const
997 // doesn't have a dominating def - see Assumptions above
Vikram S. Advebc001b22003-07-25 21:06:09 +0000998 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
999 RC->markColorsUsed(LRofLV->getColor(),
1000 MRI.getRegTypeForLR(LRofLV), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001001 }
1002
1003 // It is possible that one operand of this MInst was already spilled
1004 // and it received some register temporarily. If that's the case,
1005 // it is recorded in machine operand. We must skip such registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +00001006 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001007
Vikram S. Advebc001b22003-07-25 21:06:09 +00001008 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1009 if (unusedReg >= 0)
1010 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1011
Chris Lattner85c54652002-05-23 15:50:03 +00001012 return -1;
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001013}
1014
1015
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001016//----------------------------------------------------------------------------
1017// Get any other register in a register class, other than what is used
1018// by operands of a machine instruction. Returns the unified reg number.
1019//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001020
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001021int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +00001022 const int RegType,
Chris Lattner85c54652002-05-23 15:50:03 +00001023 const MachineInstr *MInst) {
Vikram S. Advebc001b22003-07-25 21:06:09 +00001024 RC->clearColorsUsed();
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001025
Vikram S. Advebc001b22003-07-25 21:06:09 +00001026 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001027
Vikram S. Advebc001b22003-07-25 21:06:09 +00001028 // find the first unused color
1029 int unusedReg = RC->getUnusedColor(RegType);
1030 assert(unusedReg >= 0 &&
1031 "FATAL: No free register could be found in reg class!!");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001032
Vikram S. Advebc001b22003-07-25 21:06:09 +00001033 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001034}
1035
1036
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001037//----------------------------------------------------------------------------
1038// This method modifies the IsColorUsedArr of the register class passed to it.
1039// It sets the bits corresponding to the registers used by this machine
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +00001040// instructions. Both explicit and implicit operands are set.
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001041//----------------------------------------------------------------------------
Vikram S. Advebc001b22003-07-25 21:06:09 +00001042
Chris Lattner3bed95b2003-08-05 21:55:58 +00001043static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1044 const TargetRegInfo &TRI) {
1045 unsigned classId = 0;
1046 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1047 if (RC->getID() == classId)
1048 RC->markColorsUsed(classRegNum, RegType, RegType);
1049}
1050
1051void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1052 const MachineInstr *MI)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001053{
Chris Lattner3bed95b2003-08-05 21:55:58 +00001054 assert(OperandsColoredMap[MI] == true &&
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001055 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1056 "are marked for an instruction.");
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001057
Chris Lattner3bed95b2003-08-05 21:55:58 +00001058 // Add the registers already marked as used by the instruction.
1059 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1060 if (MI->getOperand(i).hasAllocatedReg())
1061 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1062
1063 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1064 if (MI->getImplicitOp(i).hasAllocatedReg())
1065 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1066 RegType,MRI);
1067
Chris Lattner3fd1f5b2003-08-05 22:11:13 +00001068 // Add all of the scratch registers that are used to save values across the
1069 // instruction (e.g., for saving state register values).
1070 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1071 IR = ScratchRegsUsed.equal_range(MI);
1072 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1073 markRegisterUsed(I->second, RC, RegType, MRI);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001074
Vikram S. Advef5af6362002-07-08 23:15:32 +00001075 // If there are implicit references, mark their allocated regs as well
Chris Lattner3bed95b2003-08-05 21:55:58 +00001076 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
Vikram S. Advef5af6362002-07-08 23:15:32 +00001077 if (const LiveRange*
Brian Gaeke4efe3422003-09-21 01:23:46 +00001078 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
Vikram S. Advef5af6362002-07-08 23:15:32 +00001079 if (LRofImpRef->hasColor())
1080 // this implicit reference is in a LR that received a color
Vikram S. Advebc001b22003-07-25 21:06:09 +00001081 RC->markColorsUsed(LRofImpRef->getColor(),
1082 MRI.getRegTypeForLR(LRofImpRef), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001083}
1084
1085
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001086//----------------------------------------------------------------------------
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001087// If there are delay slots for an instruction, the instructions
1088// added after it must really go after the delayed instruction(s).
1089// So, we move the InstrAfter of that instruction to the
1090// corresponding delayed instruction using the following method.
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001091//----------------------------------------------------------------------------
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001092
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001093void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1094 const MachineInstr *DelayedMI)
1095{
Vikram S. Advefeb32982003-08-12 22:22:24 +00001096 // "added after" instructions of the original instr
1097 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1098
1099 if (DEBUG_RA && OrigAft.size() > 0) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001100 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1101 std::cerr << " to last delay slot instrn: " << *DelayedMI;
Vikram S. Adve814030a2003-07-29 19:49:21 +00001102 }
1103
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001104 // "added after" instructions of the delayed instr
Vikram S. Adve814030a2003-07-29 19:49:21 +00001105 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001106
1107 // go thru all the "added after instructions" of the original instruction
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001108 // and append them to the "added after instructions" of the delayed
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001109 // instructions
Chris Lattner697954c2002-01-20 22:54:45 +00001110 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001111
1112 // empty the "added after instructions" of the original instruction
1113 OrigAft.clear();
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001114}
Ruchira Sasanka0931a012001-09-15 19:06:58 +00001115
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001116
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001117void PhyRegAlloc::colorIncomingArgs()
1118{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001119 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
Vikram S. Adve814030a2003-07-29 19:49:21 +00001120 AddedInstrAtEntry.InstrnsAfter);
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001121}
1122
Ruchira Sasankae727f852001-09-18 22:43:57 +00001123
1124//----------------------------------------------------------------------------
Brian Gaeke59b1c562003-09-24 17:50:28 +00001125// This method determines whether the suggested color of each live range
1126// is really usable, and then calls its setSuggestedColorUsable() method to
1127// record the answer. A suggested color is NOT usable when the suggested color
1128// is volatile AND when there are call interferences.
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001129//----------------------------------------------------------------------------
1130
1131void PhyRegAlloc::markUnusableSugColors()
1132{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001133 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1134 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001135
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001136 for (; HMI != HMIEnd ; ++HMI ) {
1137 if (HMI->first) {
1138 LiveRange *L = HMI->second; // get the LiveRange
Brian Gaeke59b1c562003-09-24 17:50:28 +00001139 if (L && L->hasSuggestedColor ())
1140 L->setSuggestedColorUsable
1141 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1142 && L->isCallInterference ()));
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001143 }
1144 } // for all LR's in hash map
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001145}
1146
1147
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001148//----------------------------------------------------------------------------
1149// The following method will set the stack offsets of the live ranges that
Misha Brukman37f92e22003-09-11 22:34:13 +00001150// are decided to be spilled. This must be called just after coloring the
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001151// LRs using the graph coloring algo. For each live range that is spilled,
1152// this method allocate a new spill position on the stack.
1153//----------------------------------------------------------------------------
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001154
Chris Lattner37730942002-02-05 03:52:29 +00001155void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001156 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001157
Brian Gaeke4efe3422003-09-21 01:23:46 +00001158 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1159 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001160
Chris Lattner7e708292002-06-25 16:13:24 +00001161 for ( ; HMI != HMIEnd ; ++HMI) {
Chris Lattner37730942002-02-05 03:52:29 +00001162 if (HMI->first && HMI->second) {
Vikram S. Adve3bf08922003-07-10 19:42:55 +00001163 LiveRange *L = HMI->second; // get the LiveRange
1164 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
Brian Gaeke4efe3422003-09-21 01:23:46 +00001165 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001166 L->setSpillOffFromFP(stackOffset);
1167 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001168 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001169 << ": stack-offset = " << stackOffset << "\n";
1170 }
Chris Lattner37730942002-02-05 03:52:29 +00001171 }
1172 } // for all LR's in hash map
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001173}
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001174
Brian Gaeke874f4232003-09-21 02:50:21 +00001175
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001176//----------------------------------------------------------------------------
Brian Gaeke305f02d2003-09-16 15:38:05 +00001177// The entry point to Register Allocation
Ruchira Sasankae727f852001-09-18 22:43:57 +00001178//----------------------------------------------------------------------------
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001179
Brian Gaeke4efe3422003-09-21 01:23:46 +00001180bool PhyRegAlloc::runOnFunction (Function &F) {
1181 if (DEBUG_RA)
1182 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1183
1184 Fn = &F;
1185 MF = &MachineFunction::get (Fn);
1186 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1187 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1188 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1189
1190 // Create each RegClass for the target machine and add it to the
1191 // RegClassList. This must be done before calling constructLiveRanges().
1192 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1193 RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (),
1194 MRI.getMachineRegClass (rc)));
1195
1196 LRI->constructLiveRanges(); // create LR info
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001197 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
Brian Gaeke4efe3422003-09-21 01:23:46 +00001198 LRI->printLiveRanges();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001199
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001200 createIGNodeListsAndIGs(); // create IGNode list and IGs
1201
1202 buildInterferenceGraphs(); // build IGs in all reg classes
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001203
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001204 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001205 // print all LRs in all reg classes
Chris Lattner7e708292002-06-25 16:13:24 +00001206 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1207 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001208
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001209 // print IGs in all register classes
Chris Lattner7e708292002-06-25 16:13:24 +00001210 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1211 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001212 }
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001213
Brian Gaeke4efe3422003-09-21 01:23:46 +00001214 LRI->coalesceLRs(); // coalesce all live ranges
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +00001215
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001216 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001217 // print all LRs in all reg classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001218 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1219 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001220
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001221 // print IGs in all register classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001222 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1223 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001224 }
1225
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001226 // mark un-usable suggested color before graph coloring algorithm.
1227 // When this is done, the graph coloring algo will not reserve
1228 // suggested color unnecessarily - they can be used by another LR
1229 markUnusableSugColors();
1230
1231 // color all register classes using the graph coloring algo
Chris Lattner7e708292002-06-25 16:13:24 +00001232 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerf726e772002-10-28 19:22:04 +00001233 RegClassList[rc]->colorAllRegs();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001234
Misha Brukman37f92e22003-09-11 22:34:13 +00001235 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1236 // a position for such spilled LRs
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001237 allocateStackSpace4SpilledLRs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001238
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001239 // Reset the temp. area on the stack before use by the first instruction.
1240 // This will also happen after updating each instruction.
Brian Gaeke4efe3422003-09-21 01:23:46 +00001241 MF->getInfo()->popAllTempValues();
Ruchira Sasankaf90870f2001-11-15 22:02:06 +00001242
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001243 // color incoming args - if the correct color was not received
1244 // insert code to copy to the correct register
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001245 colorIncomingArgs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001246
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001247 // Now update the machine code with register names and add any
1248 // additional code inserted by the register allocator to the instruction
1249 // stream
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001250 updateMachineCode();
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001251
Chris Lattner045e7c82001-09-19 16:26:23 +00001252 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001253 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
Brian Gaeke4efe3422003-09-21 01:23:46 +00001254 MF->dump();
Chris Lattner045e7c82001-09-19 16:26:23 +00001255 }
Brian Gaeke4efe3422003-09-21 01:23:46 +00001256
1257 // Tear down temporary data structures
1258 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1259 delete RegClassList[rc];
1260 RegClassList.clear ();
1261 AddedInstrMap.clear ();
1262 OperandsColoredMap.clear ();
1263 ScratchRegsUsed.clear ();
1264 AddedInstrAtEntry.clear ();
1265 delete LRI;
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001266
Brian Gaeke4efe3422003-09-21 01:23:46 +00001267 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1268 return false; // Function was not modified
1269}