blob: 92cf3765168e9f139549fb6d3113e2959208b5f6 [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 Gaekebf3c4cf2003-08-14 06:09:32 +000042FunctionPass *getRegisterAllocator(TargetMachine &T) {
Brian Gaeke4efe3422003-09-21 01:23:46 +000043 return new PhyRegAlloc (T);
Chris Lattner2f9b28e2002-02-04 15:54:09 +000044}
Chris Lattner6dd98a62002-02-04 00:33:08 +000045
Chris Lattner8474f6f2003-09-23 15:13:04 +000046void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequired<LoopInfo> ();
48 AU.addRequired<FunctionLiveVarInfo> ();
49}
50
51
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +000052
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000053//----------------------------------------------------------------------------
Misha Brukman37f92e22003-09-11 22:34:13 +000054// This method initially creates interference graphs (one in each reg class)
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000055// and IGNodeList (one in each IG). The actual nodes will be pushed later.
56//----------------------------------------------------------------------------
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000057void PhyRegAlloc::createIGNodeListsAndIGs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +000058 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000059
60 // hash map iterator
Brian Gaeke4efe3422003-09-21 01:23:46 +000061 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000062
63 // hash map end
Brian Gaeke4efe3422003-09-21 01:23:46 +000064 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000065
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000066 for (; HMI != HMIEnd ; ++HMI ) {
67 if (HMI->first) {
68 LiveRange *L = HMI->second; // get the LiveRange
69 if (!L) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +000070 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +000071 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
Vikram S. Adve39c94e12002-09-14 23:05:33 +000072 << RAV(HMI->first) << "****\n";
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000073 continue;
74 }
Vikram S. Adve39c94e12002-09-14 23:05:33 +000075
76 // if the Value * is not null, and LR is not yet written to the IGNodeList
Chris Lattner7e708292002-06-25 16:13:24 +000077 if (!(L->getUserIGNode()) ) {
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000078 RegClass *const RC = // RegClass of first value in the LR
79 RegClassList[ L->getRegClass()->getID() ];
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000080 RC->addLRToIG(L); // add this LR to an IG
81 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +000082 }
83 }
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000084
85 // init RegClassList
Chris Lattner7e708292002-06-25 16:13:24 +000086 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000087 RegClassList[rc]->createInterferenceGraph();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000088
Chris Lattnerc083dcc2003-09-01 20:05:47 +000089 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000090}
91
92
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000093//----------------------------------------------------------------------------
94// This method will add all interferences at for a given instruction.
Misha Brukman37f92e22003-09-11 22:34:13 +000095// Interference occurs only if the LR of Def (Inst or Arg) is of the same reg
Ruchira Sasanka8e604792001-09-14 21:18:34 +000096// class as that of live var. The live var passed to this function is the
97// LVset AFTER the instruction
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000098//----------------------------------------------------------------------------
Vikram S. Adve39c94e12002-09-14 23:05:33 +000099
Chris Lattner296b7732002-02-05 02:52:05 +0000100void PhyRegAlloc::addInterference(const Value *Def,
101 const ValueSet *LVSet,
102 bool isCallInst) {
Chris Lattner296b7732002-02-05 02:52:05 +0000103 ValueSet::const_iterator LIt = LVSet->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000104
105 // get the live range of instruction
Brian Gaeke4efe3422003-09-21 01:23:46 +0000106 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000107
108 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
109 assert( IGNodeOfDef );
110
111 RegClass *const RCOfDef = LROfDef->getRegClass();
112
113 // for each live var in live variable set
Chris Lattner7e708292002-06-25 16:13:24 +0000114 for ( ; LIt != LVSet->end(); ++LIt) {
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000115
Vikram S. Advef5af6362002-07-08 23:15:32 +0000116 if (DEBUG_RA >= RA_DEBUG_Verbose)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000117 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000118
119 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000120 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000121
122 // LROfVar can be null if it is a const since a const
123 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000124 if (LROfVar)
125 if (LROfDef != LROfVar) // do not set interf for same LR
126 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
127 RCOfDef->setInterference( LROfDef, LROfVar);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000128 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000129}
130
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000131
132//----------------------------------------------------------------------------
133// For a call instruction, this method sets the CallInterference flag in
134// the LR of each variable live int the Live Variable Set live after the
135// call instruction (except the return value of the call instruction - since
136// the return value does not interfere with that call itself).
137//----------------------------------------------------------------------------
138
139void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
Chris Lattner296b7732002-02-05 02:52:05 +0000140 const ValueSet *LVSetAft) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000141 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000142 std::cerr << "\n For call inst: " << *MInst;
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000143
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000144 // for each live var in live variable set after machine inst
Vikram S. Adve65b2f402003-07-02 01:24:00 +0000145 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
146 LIt != LEnd; ++LIt) {
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000147
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000148 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000149 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000150
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000151 // LR can be null if it is a const since a const
152 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000153 if (LR ) {
154 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000155 std::cerr << "\n\tLR after Call: ";
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000156 printSet(*LR);
157 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000158 LR->setCallInterference();
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000159 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000160 std::cerr << "\n ++After adding call interference for LR: " ;
Chris Lattner296b7732002-02-05 02:52:05 +0000161 printSet(*LR);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000162 }
163 }
164
165 }
166
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000167 // Now find the LR of the return value of the call
168 // We do this because, we look at the LV set *after* the instruction
169 // to determine, which LRs must be saved across calls. The return value
170 // of the call is live in this set - but it does not interfere with call
171 // (i.e., we can allocate a volatile register to the return value)
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000172 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
173
174 if (const Value *RetVal = argDesc->getReturnValue()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000175 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000176 assert( RetValLR && "No LR for RetValue of call");
177 RetValLR->clearCallInterference();
178 }
179
180 // If the CALL is an indirect call, find the LR of the function pointer.
181 // That has a call interference because it conflicts with outgoing args.
Chris Lattner7e708292002-06-25 16:13:24 +0000182 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000183 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000184 assert( AddrValLR && "No LR for indirect addr val of call");
185 AddrValLR->setCallInterference();
186 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000187}
188
189
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000190//----------------------------------------------------------------------------
191// This method will walk thru code and create interferences in the IG of
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000192// each RegClass. Also, this method calculates the spill cost of each
193// Live Range (it is done in this method to save another pass over the code).
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000194//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000195
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000196void PhyRegAlloc::buildInterferenceGraphs()
197{
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000198 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000199 std::cerr << "Creating interference graphs ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000200
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000201 unsigned BBLoopDepthCost;
Brian Gaeke4efe3422003-09-21 01:23:46 +0000202 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000203 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000204 const MachineBasicBlock &MBB = *BBI;
205 const BasicBlock *BB = MBB.getBasicBlock();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000206
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000207 // find the 10^(loop_depth) of this BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000208 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000209
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000210 // get the iterator for machine instructions
Chris Lattnerf726e772002-10-28 19:22:04 +0000211 MachineBasicBlock::const_iterator MII = MBB.begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000212
213 // iterate over all the machine instructions in BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000214 for ( ; MII != MBB.end(); ++MII) {
215 const MachineInstr *MInst = *MII;
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000216
217 // get the LV set after the instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000218 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
219 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000220
Chris Lattner7e708292002-06-25 16:13:24 +0000221 if (isCallInst ) {
Misha Brukman37f92e22003-09-11 22:34:13 +0000222 // set the isCallInterference flag of each live range which extends
223 // across this call instruction. This information is used by graph
224 // coloring algorithm to avoid allocating volatile colors to live ranges
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000225 // that span across calls (since they have to be saved/restored)
Chris Lattner748697d2002-02-05 04:20:12 +0000226 setCallInterferences(MInst, &LVSetAI);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000227 }
228
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000229 // iterate over all MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000230 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
231 OpE = MInst->end(); OpI != OpE; ++OpI) {
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000232 if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
Chris Lattner748697d2002-02-05 04:20:12 +0000233 addInterference(*OpI, &LVSetAI, isCallInst);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000234
235 // Calculate the spill cost of each live range
Brian Gaeke4efe3422003-09-21 01:23:46 +0000236 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
Chris Lattner2f898d22002-02-05 06:02:59 +0000237 if (LR) LR->addSpillCost(BBLoopDepthCost);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000238 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000239
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000240 // if there are multiple defs in this instruction e.g. in SETX
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000241 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000242 addInterf4PseudoInstr(MInst);
243
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000244 // Also add interference for any implicit definitions in a machine
245 // instr (currently, only calls have this).
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000246 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000247 for (unsigned z=0; z < NumOfImpRefs; z++)
248 if (MInst->getImplicitOp(z).opIsDefOnly() ||
249 MInst->getImplicitOp(z).opIsDefAndUse())
250 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +0000251
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000252 } // for all machine instructions in BB
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000253 } // for all BBs in function
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000254
Misha Brukman37f92e22003-09-11 22:34:13 +0000255 // add interferences for function arguments. Since there are no explicit
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000256 // defs in the function for args, we have to add them manually
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000257 addInterferencesForArgs();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000258
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000259 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000260 std::cerr << "Interference graphs calculated!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000261}
262
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000263
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000264//--------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000265// Pseudo-instructions may be expanded to multiple instructions by the
266// assembler. Consequently, all the operands must get distinct registers.
267// Therefore, we mark all operands of a pseudo-instruction as interfering
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000268// with one another.
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000269//--------------------------------------------------------------------------
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000270
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000271void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000272 bool setInterf = false;
273
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000274 // iterate over MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000275 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
276 ItE = MInst->end(); It1 != ItE; ++It1) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000277 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000278 assert((LROfOp1 || !It1.isUseOnly())&&"No LR for Def in PSEUDO insruction");
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000279
Chris Lattner2f898d22002-02-05 06:02:59 +0000280 MachineInstr::const_val_op_iterator It2 = It1;
Chris Lattner7e708292002-06-25 16:13:24 +0000281 for (++It2; It2 != ItE; ++It2) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000282 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000283
Chris Lattner2f898d22002-02-05 06:02:59 +0000284 if (LROfOp2) {
285 RegClass *RCOfOp1 = LROfOp1->getRegClass();
286 RegClass *RCOfOp2 = LROfOp2->getRegClass();
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000287
Chris Lattner7e708292002-06-25 16:13:24 +0000288 if (RCOfOp1 == RCOfOp2 ){
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000289 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000290 setInterf = true;
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000291 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000292 } // if Op2 has a LR
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000293 } // for all other defs in machine instr
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000294 } // for all operands in an instruction
295
Chris Lattner2f898d22002-02-05 06:02:59 +0000296 if (!setInterf && MInst->getNumOperands() > 2) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000297 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
298 std::cerr << *MInst;
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000299 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000300 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000301}
302
303
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000304//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000305// This method adds interferences for incoming arguments to a function.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000306//----------------------------------------------------------------------------
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000307
Chris Lattner296b7732002-02-05 02:52:05 +0000308void PhyRegAlloc::addInterferencesForArgs() {
309 // get the InSet of root BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000310 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000311
Chris Lattnerf726e772002-10-28 19:22:04 +0000312 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000313 // add interferences between args and LVars at start
314 addInterference(AI, &InSet, false);
315
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000316 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000317 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000318 }
319}
320
321
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000322//----------------------------------------------------------------------------
323// This method is called after register allocation is complete to set the
Misha Brukman37f92e22003-09-11 22:34:13 +0000324// allocated registers in the machine code. This code will add register numbers
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000325// to MachineOperands that contain a Value. Also it calls target specific
326// methods to produce caller saving instructions. At the end, it adds all
327// additional instructions produced by the register allocator to the
328// instruction stream.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000329//----------------------------------------------------------------------------
Vikram S. Adve48762092002-04-25 04:34:15 +0000330
331//-----------------------------
332// Utility functions used below
333//-----------------------------
334inline void
Vikram S. Advecb202e32002-10-11 16:12:40 +0000335InsertBefore(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000336 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000337 MachineBasicBlock::iterator& MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000338{
Chris Lattnerf726e772002-10-28 19:22:04 +0000339 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000340 ++MII;
341}
342
343inline void
344InsertAfter(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000345 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000346 MachineBasicBlock::iterator& MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000347{
348 ++MII; // insert before the next instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000349 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000350}
351
352inline void
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000353DeleteInstruction(MachineBasicBlock& MBB,
354 MachineBasicBlock::iterator& MII)
355{
356 MII = MBB.erase(MII);
357}
358
359inline void
Vikram S. Advecb202e32002-10-11 16:12:40 +0000360SubstituteInPlace(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000361 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000362 MachineBasicBlock::iterator MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000363{
364 *MII = newMI;
365}
366
367inline void
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000368PrependInstructions(std::vector<MachineInstr *> &IBef,
Chris Lattnerf726e772002-10-28 19:22:04 +0000369 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000370 MachineBasicBlock::iterator& MII,
Vikram S. Adve48762092002-04-25 04:34:15 +0000371 const std::string& msg)
372{
373 if (!IBef.empty())
374 {
375 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000376 std::vector<MachineInstr *>::iterator AdIt;
Vikram S. Adve48762092002-04-25 04:34:15 +0000377 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
378 {
379 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000380 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
381 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000382 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000383 InsertBefore(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000384 }
385 }
386}
387
388inline void
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000389AppendInstructions(std::vector<MachineInstr *> &IAft,
Chris Lattnerf726e772002-10-28 19:22:04 +0000390 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000391 MachineBasicBlock::iterator& MII,
Vikram S. Adve48762092002-04-25 04:34:15 +0000392 const std::string& msg)
393{
394 if (!IAft.empty())
395 {
396 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000397 std::vector<MachineInstr *>::iterator AdIt;
Chris Lattner7e708292002-06-25 16:13:24 +0000398 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
Vikram S. Adve48762092002-04-25 04:34:15 +0000399 {
Chris Lattner7e708292002-06-25 16:13:24 +0000400 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000401 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
402 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000403 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000404 InsertAfter(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000405 }
406 }
407}
408
Brian Gaeke4efe3422003-09-21 01:23:46 +0000409bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000410{
Vikram S. Adve814030a2003-07-29 19:49:21 +0000411 bool instrNeedsSpills = false;
412
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000413 // First, set the registers for operands in the machine instruction
414 // if a register was successfully allocated. Do this first because we
415 // will need to know which registers are already used by this instr'n.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000416 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
417 {
418 MachineOperand& Op = MInst->getOperand(OpNum);
419 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
420 Op.getType() == MachineOperand::MO_CCRegister)
421 {
422 const Value *const Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000423 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000424 // Remember if any operand needs spilling
425 instrNeedsSpills |= LR->isMarkedForSpill();
426
427 // An operand may have a color whether or not it needs spilling
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000428 if (LR->hasColor())
429 MInst->SetRegForOperand(OpNum,
430 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
431 LR->getColor()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000432 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000433 }
434 } // for each operand
Vikram S. Adve814030a2003-07-29 19:49:21 +0000435
436 return instrNeedsSpills;
437}
438
439void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
440 MachineBasicBlock &MBB)
441{
442 MachineInstr* MInst = *MII;
443 unsigned Opcode = MInst->getOpCode();
444
445 // Reset tmp stack positions so they can be reused for each machine instr.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000446 MF->getInfo()->popAllTempValues();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000447
448 // Mark the operands for which regs have been allocated.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000449 bool instrNeedsSpills = markAllocatedRegs(*MII);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000450
451#ifndef NDEBUG
452 // Mark that the operands have been updated. Later,
453 // setRelRegsUsedByThisInst() is called to find registers used by each
454 // MachineInst, and it should not be used for an instruction until
455 // this is done. This flag just serves as a sanity check.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000456 OperandsColoredMap[MInst] = true;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000457#endif
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000458
Vikram S. Advebc001b22003-07-25 21:06:09 +0000459 // Now insert caller-saving code before/after the call.
460 // Do this before inserting spill code since some registers must be
461 // used by save/restore and spill code should not use those registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000462 if (TM.getInstrInfo().isCall(Opcode)) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000463 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Adve814030a2003-07-29 19:49:21 +0000464 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
465 MBB.getBasicBlock());
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000466 }
Vikram S. Advebc001b22003-07-25 21:06:09 +0000467
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000468 // Now insert spill code for remaining operands not allocated to
469 // registers. This must be done even for call return instructions
470 // since those are not handled by the special code above.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000471 if (instrNeedsSpills)
472 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
473 {
474 MachineOperand& Op = MInst->getOperand(OpNum);
475 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
476 Op.getType() == MachineOperand::MO_CCRegister)
477 {
478 const Value* Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000479 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000480 if (LR->isMarkedForSpill())
481 insertCode4SpilledLR(LR, MII, MBB, OpNum);
482 }
483 } // for each operand
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000484}
485
486void PhyRegAlloc::updateMachineCode()
487{
Chris Lattner7e708292002-06-25 16:13:24 +0000488 // Insert any instructions needed at method entry
Brian Gaeke4efe3422003-09-21 01:23:46 +0000489 MachineBasicBlock::iterator MII = MF->front().begin();
490 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
Chris Lattner7e708292002-06-25 16:13:24 +0000491 "At function entry: \n");
492 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
493 "InstrsAfter should be unnecessary since we are just inserting at "
494 "the function entry point here.");
Vikram S. Adve48762092002-04-25 04:34:15 +0000495
Brian Gaeke4efe3422003-09-21 01:23:46 +0000496 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000497 BBI != BBE; ++BBI) {
Vikram S. Advecb202e32002-10-11 16:12:40 +0000498
Chris Lattnerf726e772002-10-28 19:22:04 +0000499 MachineBasicBlock &MBB = *BBI;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000500
501 // Iterate over all machine instructions in BB and mark operands with
502 // their assigned registers or insert spill code, as appropriate.
503 // Also, fix operands of call/return instructions.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000504 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000505 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
506 updateInstruction(MII, MBB);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000507
508 // Now, move code out of delay slots of branches and returns if needed.
509 // (Also, move "after" code from calls to the last delay slot instruction.)
510 // Moving code out of delay slots is needed in 2 situations:
511 // (1) If this is a branch and it needs instructions inserted after it,
512 // move any existing instructions out of the delay slot so that the
513 // instructions can go into the delay slot. This only supports the
514 // case that #instrsAfter <= #delay slots.
515 //
516 // (2) If any instruction in the delay slot needs
517 // instructions inserted, move it out of the delay slot and before the
518 // branch because putting code before or after it would be VERY BAD!
519 //
520 // If the annul bit of the branch is set, neither of these is legal!
521 // If so, we need to handle spill differently but annulling is not yet used.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000522 for (MachineBasicBlock::iterator MII = MBB.begin();
523 MII != MBB.end(); ++MII)
524 if (unsigned delaySlots =
525 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
526 {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000527 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
528
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000529 // Check the 2 conditions above:
530 // (1) Does a branch need instructions added after it?
531 // (2) O/w does delay slot instr. need instrns before or after?
Vikram S. Adve814030a2003-07-29 19:49:21 +0000532 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
533 TM.getInstrInfo().isReturn(MInst->getOpCode()));
534 bool cond1 = (isBranch &&
535 AddedInstrMap.count(MInst) &&
536 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
537 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
538 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
539 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000540
541 if (cond1 || cond2)
542 {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000543 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
544 "FIXME: Moving an annulled delay slot instruction!");
545 assert(delaySlots==1 &&
546 "InsertBefore does not yet handle >1 delay slots!");
547 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000548
549 // In case (1), delete it and don't replace with anything!
550 // Otherwise (i.e., case (2) only) replace it with a NOP.
551 if (cond1) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000552 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
553 --MII; // reset MII for ++MII of loop
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000554 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000555 else
556 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
557 MBB, MII+1); // replace with NOP
558
559 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000560 std::cerr << "\nRegAlloc: Moved instr. with added code: "
Vikram S. Adve814030a2003-07-29 19:49:21 +0000561 << *DelaySlotMI
562 << " out of delay slots of instr: " << *MInst;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000563 }
564 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000565 else
566 // For non-branch instr with delay slots (probably a call), move
567 // InstrAfter to the instr. in the last delay slot.
568 move2DelayedInstr(*MII, *(MII+delaySlots));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000569 }
570
571 // Finally iterate over all instructions in BB and insert before/after
Vikram S. Advebc001b22003-07-25 21:06:09 +0000572 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000573 MachineInstr *MInst = *MII;
Vikram S. Advebc001b22003-07-25 21:06:09 +0000574
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000575 // do not process Phis
Vikram S. Advebc001b22003-07-25 21:06:09 +0000576 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000577 continue;
578
Vikram S. Advebc001b22003-07-25 21:06:09 +0000579 // if there are any added instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000580 if (AddedInstrMap.count(MInst)) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000581 AddedInstrns &CallAI = AddedInstrMap[MInst];
582
583#ifndef NDEBUG
Vikram S. Adve814030a2003-07-29 19:49:21 +0000584 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
585 TM.getInstrInfo().isReturn(MInst->getOpCode()));
586 assert((!isBranch ||
587 AddedInstrMap[MInst].InstrnsAfter.size() <=
588 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
589 "Cannot put more than #delaySlots instrns after "
590 "branch or return! Need to handle temps differently.");
591#endif
592
593#ifndef NDEBUG
Vikram S. Advebc001b22003-07-25 21:06:09 +0000594 // Temporary sanity checking code to detect whether the same machine
595 // instruction is ever inserted twice before/after a call.
596 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000597 std::set<const MachineInstr*> instrsSeen;
598 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
599 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
600 "Duplicate machine instruction in InstrnsBefore!");
601 instrsSeen.insert(CallAI.InstrnsBefore[i]);
602 }
603 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
604 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
605 "Duplicate machine instruction in InstrnsBefore/After!");
606 instrsSeen.insert(CallAI.InstrnsAfter[i]);
607 }
608#endif
609
610 // Now add the instructions before/after this MI.
611 // We do this here to ensure that spill for an instruction is inserted
612 // as close as possible to an instruction (see above insertCode4Spill)
Vikram S. Advebc001b22003-07-25 21:06:09 +0000613 if (! CallAI.InstrnsBefore.empty())
614 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
615
616 if (! CallAI.InstrnsAfter.empty())
617 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
618
619 } // if there are any added instructions
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000620 } // for each machine instruction
Ruchira Sasanka0931a012001-09-15 19:06:58 +0000621 }
622}
623
624
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000625//----------------------------------------------------------------------------
626// This method inserts spill code for AN operand whose LR was spilled.
627// This method may be called several times for a single machine instruction
628// if it contains many spilled operands. Each time it is called, it finds
629// a register which is not live at that instruction and also which is not
630// used by other spilled operands of the same instruction. Then it uses
Misha Brukman37f92e22003-09-11 22:34:13 +0000631// this register temporarily to accommodate the spilled value.
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000632//----------------------------------------------------------------------------
Vikram S. Advebc001b22003-07-25 21:06:09 +0000633
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000634void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000635 MachineBasicBlock::iterator& MII,
636 MachineBasicBlock &MBB,
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000637 const unsigned OpNum) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000638 MachineInstr *MInst = *MII;
639 const BasicBlock *BB = MBB.getBasicBlock();
640
Vikram S. Advead9c9782002-09-28 17:02:40 +0000641 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
642 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
643 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
644 "Return value of a ret must be handled elsewhere");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000645
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000646 MachineOperand& Op = MInst->getOperand(OpNum);
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000647 bool isDef = Op.opIsDefOnly();
648 bool isDefAndUse = Op.opIsDefAndUse();
Vikram S. Advebc001b22003-07-25 21:06:09 +0000649 unsigned RegType = MRI.getRegTypeForLR(LR);
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000650 int SpillOff = LR->getSpillOffFromFP();
651 RegClass *RC = LR->getRegClass();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000652
653 // Get the live-variable set to find registers free before this instr.
Vikram S. Advefeb32982003-08-12 22:22:24 +0000654 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
655
656#ifndef NDEBUG
657 // If this instr. is in the delay slot of a branch or return, we need to
658 // include all live variables before that branch or return -- we don't want to
659 // trample those! Verify that the set is included in the LV set before MInst.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000660 if (MII != MBB.begin()) {
661 MachineInstr *PredMI = *(MII-1);
Vikram S. Advefeb32982003-08-12 22:22:24 +0000662 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
663 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
664 .empty() && "Live-var set before branch should be included in "
665 "live-var set of each delay slot instruction!");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000666 }
Vikram S. Advefeb32982003-08-12 22:22:24 +0000667#endif
Vikram S. Adve00521d72001-11-12 23:26:35 +0000668
Brian Gaeke4efe3422003-09-21 01:23:46 +0000669 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000670
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000671 std::vector<MachineInstr*> MIBef, MIAft;
672 std::vector<MachineInstr*> AdIMid;
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000673
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000674 // Choose a register to hold the spilled value, if one was not preallocated.
675 // This may insert code before and after MInst to free up the value. If so,
676 // this code should be first/last in the spill sequence before/after MInst.
677 int TmpRegU=(LR->hasColor()
678 ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
679 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000680
Vikram S. Advef5af6362002-07-08 23:15:32 +0000681 // Set the operand first so that it this register does not get used
682 // as a scratch register for later calls to getUsableUniRegAtMI below
683 MInst->SetRegForOperand(OpNum, TmpRegU);
684
685 // get the added instructions for this instruction
Chris Lattner0b0ffa02002-04-09 05:13:04 +0000686 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Advef5af6362002-07-08 23:15:32 +0000687
688 // We may need a scratch register to copy the spilled value to/from memory.
689 // This may itself have to insert code to free up a scratch register.
690 // Any such code should go before (after) the spill code for a load (store).
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000691 // The scratch reg is not marked as used because it is only used
692 // for the copy and not used across MInst.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000693 int scratchRegType = -1;
694 int scratchReg = -1;
695 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
696 {
Chris Lattner27a08932002-10-22 23:16:21 +0000697 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
698 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000699 assert(scratchReg != MRI.getInvalidRegNum());
Vikram S. Advef5af6362002-07-08 23:15:32 +0000700 }
701
702 if (!isDef || isDefAndUse) {
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000703 // for a USE, we have to load the value of LR from stack to a TmpReg
704 // and use the TmpReg as one operand of instruction
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000705
Vikram S. Advef5af6362002-07-08 23:15:32 +0000706 // actual loading instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000707 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
708 RegType, scratchReg);
Ruchira Sasanka226f1f02001-11-08 19:11:30 +0000709
Vikram S. Advef5af6362002-07-08 23:15:32 +0000710 // the actual load should be after the instructions to free up TmpRegU
711 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
712 AdIMid.clear();
713 }
714
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000715 if (isDef || isDefAndUse) { // if this is a Def
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000716 // for a DEF, we have to store the value produced by this instruction
717 // on the stack position allocated for this LR
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000718
Vikram S. Advef5af6362002-07-08 23:15:32 +0000719 // actual storing instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000720 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
721 RegType, scratchReg);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000722
Vikram S. Advef5af6362002-07-08 23:15:32 +0000723 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000724 } // if !DEF
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000725
Vikram S. Advef5af6362002-07-08 23:15:32 +0000726 // Finally, insert the entire spill code sequences before/after MInst
727 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
728 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
729
Chris Lattner7e708292002-06-25 16:13:24 +0000730 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000731 std::cerr << "\nFor Inst:\n " << *MInst;
732 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
733 std::cerr << "; added Instructions:";
Anand Shuklad58290e2002-07-09 19:18:56 +0000734 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
735 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
Chris Lattner7e708292002-06-25 16:13:24 +0000736 }
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000737}
738
739
Vikram S. Adve814030a2003-07-29 19:49:21 +0000740//----------------------------------------------------------------------------
Misha Brukman37f92e22003-09-11 22:34:13 +0000741// This method inserts caller saving/restoring instructions before/after
Vikram S. Adve814030a2003-07-29 19:49:21 +0000742// a call machine instruction. The caller saving/restoring instructions are
743// inserted like:
744// ** caller saving instructions
745// other instructions inserted for the call by ColorCallArg
746// CALL instruction
747// other instructions inserted for the call ColorCallArg
748// ** caller restoring instructions
749//----------------------------------------------------------------------------
750
751void
752PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
753 std::vector<MachineInstr*> &instrnsAfter,
754 MachineInstr *CallMI,
755 const BasicBlock *BB)
756{
757 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
758
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000759 // hash set to record which registers were saved/restored
Vikram S. Adve814030a2003-07-29 19:49:21 +0000760 hash_set<unsigned> PushedRegSet;
761
762 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
763
764 // if the call is to a instrumentation function, do not insert save and
765 // restore instructions the instrumentation function takes care of save
766 // restore for volatile regs.
767 //
768 // FIXME: this should be made general, not specific to the reoptimizer!
Vikram S. Adve814030a2003-07-29 19:49:21 +0000769 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
770 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
771
772 // Now check if the call has a return value (using argDesc) and if so,
773 // find the LR of the TmpInstruction representing the return value register.
774 // (using the last or second-last *implicit operand* of the call MI).
775 // Insert it to to the PushedRegSet since we must not save that register
776 // and restore it after the call.
777 // We do this because, we look at the LV set *after* the instruction
778 // to determine, which LRs must be saved across calls. The return value
779 // of the call is live in this set - but we must not save/restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000780 if (const Value *origRetVal = argDesc->getReturnValue()) {
781 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
782 (argDesc->getIndirectFuncPtr()? 1 : 2));
783 const TmpInstruction* tmpRetVal =
784 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
785 assert(tmpRetVal->getOperand(0) == origRetVal &&
786 tmpRetVal->getType() == origRetVal->getType() &&
787 "Wrong implicit ref?");
Brian Gaeke4efe3422003-09-21 01:23:46 +0000788 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000789 assert(RetValLR && "No LR for RetValue of call");
790
791 if (! RetValLR->isMarkedForSpill())
792 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
793 RetValLR->getColor()));
794 }
795
796 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
797 ValueSet::const_iterator LIt = LVSetAft.begin();
798
799 // for each live var in live variable set after machine inst
800 for( ; LIt != LVSetAft.end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000801 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000802 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000803
804 // LR can be null if it is a const since a const
805 // doesn't have a dominating def - see Assumptions above
806 if( LR ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000807 if(! LR->isMarkedForSpill()) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000808 assert(LR->hasColor() && "LR is neither spilled nor colored?");
809 unsigned RCID = LR->getRegClassID();
810 unsigned Color = LR->getColor();
811
812 if (MRI.isRegVolatile(RCID, Color) ) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000813 // if this is a call to the first-level reoptimizer
814 // instrumentation entry point, and the register is not
815 // modified by call, don't save and restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000816 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
817 continue;
818
819 // if the value is in both LV sets (i.e., live before and after
820 // the call machine instruction)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000821 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
822
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000823 // if we haven't already pushed this register...
Vikram S. Adve814030a2003-07-29 19:49:21 +0000824 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000825 unsigned RegType = MRI.getRegTypeForLR(LR);
826
827 // Now get two instructions - to push on stack and pop from stack
828 // and add them to InstrnsBefore and InstrnsAfter of the
829 // call instruction
Vikram S. Adve814030a2003-07-29 19:49:21 +0000830 int StackOff =
Brian Gaeke4efe3422003-09-21 01:23:46 +0000831 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000832
833 //---- Insert code for pushing the reg on stack ----------
834
835 std::vector<MachineInstr*> AdIBef, AdIAft;
836
837 // We may need a scratch register to copy the saved value
838 // to/from memory. This may itself have to insert code to
839 // free up a scratch register. Any such code should go before
840 // the save code. The scratch register, if any, is by default
841 // temporary and not "used" by the instruction unless the
842 // copy code itself decides to keep the value in the scratch reg.
843 int scratchRegType = -1;
844 int scratchReg = -1;
845 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
846 { // Find a register not live in the LVSet before CallMI
847 const ValueSet &LVSetBef =
848 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
849 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
850 CallMI, AdIBef, AdIAft);
851 assert(scratchReg != MRI.getInvalidRegNum());
852 }
853
854 if (AdIBef.size() > 0)
855 instrnsBefore.insert(instrnsBefore.end(),
856 AdIBef.begin(), AdIBef.end());
857
858 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
859 StackOff, RegType, scratchReg);
860
861 if (AdIAft.size() > 0)
862 instrnsBefore.insert(instrnsBefore.end(),
863 AdIAft.begin(), AdIAft.end());
864
865 //---- Insert code for popping the reg from the stack ----------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000866 AdIBef.clear();
867 AdIAft.clear();
868
869 // We may need a scratch register to copy the saved value
870 // from memory. This may itself have to insert code to
871 // free up a scratch register. Any such code should go
872 // after the save code. As above, scratch is not marked "used".
Vikram S. Adve814030a2003-07-29 19:49:21 +0000873 scratchRegType = -1;
874 scratchReg = -1;
875 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
876 { // Find a register not live in the LVSet after CallMI
877 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
878 CallMI, AdIBef, AdIAft);
879 assert(scratchReg != MRI.getInvalidRegNum());
880 }
881
882 if (AdIBef.size() > 0)
883 instrnsAfter.insert(instrnsAfter.end(),
884 AdIBef.begin(), AdIBef.end());
885
886 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
887 Reg, RegType, scratchReg);
888
889 if (AdIAft.size() > 0)
890 instrnsAfter.insert(instrnsAfter.end(),
891 AdIAft.begin(), AdIAft.end());
892
893 PushedRegSet.insert(Reg);
894
895 if(DEBUG_RA) {
896 std::cerr << "\nFor call inst:" << *CallMI;
897 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
898 for_each(instrnsBefore.begin(), instrnsBefore.end(),
899 std::mem_fun(&MachineInstr::dump));
900 std::cerr << " -and After:\n\t ";
901 for_each(instrnsAfter.begin(), instrnsAfter.end(),
902 std::mem_fun(&MachineInstr::dump));
903 }
904 } // if not already pushed
Vikram S. Adve814030a2003-07-29 19:49:21 +0000905 } // if LR has a volatile color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000906 } // if LR has color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000907 } // if there is a LR for Var
Vikram S. Adve814030a2003-07-29 19:49:21 +0000908 } // for each value in the LV set after instruction
909}
910
911
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000912//----------------------------------------------------------------------------
913// We can use the following method to get a temporary register to be used
914// BEFORE any given machine instruction. If there is a register available,
915// this method will simply return that register and set MIBef = MIAft = NULL.
916// Otherwise, it will return a register and MIAft and MIBef will contain
917// two instructions used to free up this returned register.
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000918// Returned register number is the UNIFIED register number
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000919//----------------------------------------------------------------------------
920
Vikram S. Advef5af6362002-07-08 23:15:32 +0000921int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
922 const ValueSet *LVSetBef,
923 MachineInstr *MInst,
924 std::vector<MachineInstr*>& MIBef,
925 std::vector<MachineInstr*>& MIAft) {
Chris Lattner133f0792002-10-28 04:45:29 +0000926 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000927
Vikram S. Advebc001b22003-07-25 21:06:09 +0000928 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000929
930 if (RegU == -1) {
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000931 // we couldn't find an unused register. Generate code to free up a reg by
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000932 // saving it on stack and restoring after the instruction
Vikram S. Advef5af6362002-07-08 23:15:32 +0000933
Brian Gaeke4efe3422003-09-21 01:23:46 +0000934 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve12af1642001-11-08 04:48:50 +0000935
Vikram S. Advebc001b22003-07-25 21:06:09 +0000936 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000937
Vikram S. Advef5af6362002-07-08 23:15:32 +0000938 // Check if we need a scratch register to copy this register to memory.
939 int scratchRegType = -1;
940 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
941 {
Chris Lattner133f0792002-10-28 04:45:29 +0000942 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
943 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000944 assert(scratchReg != MRI.getInvalidRegNum());
945
946 // We may as well hold the value in the scratch register instead
947 // of copying it to memory and back. But we have to mark the
948 // register as used by this instruction, so it does not get used
949 // as a scratch reg. by another operand or anyone else.
Chris Lattner3fd1f5b2003-08-05 22:11:13 +0000950 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000951 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
952 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
953 }
954 else
955 { // the register can be copied directly to/from memory so do it.
956 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
957 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
958 }
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000959 }
Vikram S. Advef5af6362002-07-08 23:15:32 +0000960
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000961 return RegU;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000962}
963
Vikram S. Adve814030a2003-07-29 19:49:21 +0000964
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000965//----------------------------------------------------------------------------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000966// This method is called to get a new unused register that can be used
Misha Brukman37f92e22003-09-11 22:34:13 +0000967// to accommodate a temporary value. This method may be called several times
Vikram S. Adve814030a2003-07-29 19:49:21 +0000968// for a single machine instruction. Each time it is called, it finds a
969// register which is not live at that instruction and also which is not used
970// by other spilled operands of the same instruction. Return register number
971// is relative to the register class, NOT the unified number.
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000972//----------------------------------------------------------------------------
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000973
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000974int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +0000975 const int RegType,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000976 const MachineInstr *MInst,
977 const ValueSet* LVSetBef) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000978 RC->clearColorsUsed(); // Reset array
Vikram S. Adve814030a2003-07-29 19:49:21 +0000979
980 if (LVSetBef == NULL) {
981 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
982 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
983 }
984
Chris Lattner296b7732002-02-05 02:52:05 +0000985 ValueSet::const_iterator LIt = LVSetBef->begin();
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000986
987 // for each live var in live variable set after machine inst
Chris Lattner7e708292002-06-25 16:13:24 +0000988 for ( ; LIt != LVSetBef->end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000989 // Get the live range corresponding to live var, and its RegClass
Brian Gaeke4efe3422003-09-21 01:23:46 +0000990 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000991
992 // LR can be null if it is a const since a const
993 // doesn't have a dominating def - see Assumptions above
Vikram S. Advebc001b22003-07-25 21:06:09 +0000994 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
995 RC->markColorsUsed(LRofLV->getColor(),
996 MRI.getRegTypeForLR(LRofLV), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000997 }
998
999 // It is possible that one operand of this MInst was already spilled
1000 // and it received some register temporarily. If that's the case,
1001 // it is recorded in machine operand. We must skip such registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +00001002 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001003
Vikram S. Advebc001b22003-07-25 21:06:09 +00001004 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1005 if (unusedReg >= 0)
1006 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1007
Chris Lattner85c54652002-05-23 15:50:03 +00001008 return -1;
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001009}
1010
1011
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001012//----------------------------------------------------------------------------
1013// Get any other register in a register class, other than what is used
1014// by operands of a machine instruction. Returns the unified reg number.
1015//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001016
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001017int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +00001018 const int RegType,
Chris Lattner85c54652002-05-23 15:50:03 +00001019 const MachineInstr *MInst) {
Vikram S. Advebc001b22003-07-25 21:06:09 +00001020 RC->clearColorsUsed();
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001021
Vikram S. Advebc001b22003-07-25 21:06:09 +00001022 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001023
Vikram S. Advebc001b22003-07-25 21:06:09 +00001024 // find the first unused color
1025 int unusedReg = RC->getUnusedColor(RegType);
1026 assert(unusedReg >= 0 &&
1027 "FATAL: No free register could be found in reg class!!");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001028
Vikram S. Advebc001b22003-07-25 21:06:09 +00001029 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001030}
1031
1032
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001033//----------------------------------------------------------------------------
1034// This method modifies the IsColorUsedArr of the register class passed to it.
1035// It sets the bits corresponding to the registers used by this machine
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +00001036// instructions. Both explicit and implicit operands are set.
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001037//----------------------------------------------------------------------------
Vikram S. Advebc001b22003-07-25 21:06:09 +00001038
Chris Lattner3bed95b2003-08-05 21:55:58 +00001039static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1040 const TargetRegInfo &TRI) {
1041 unsigned classId = 0;
1042 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1043 if (RC->getID() == classId)
1044 RC->markColorsUsed(classRegNum, RegType, RegType);
1045}
1046
1047void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1048 const MachineInstr *MI)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001049{
Chris Lattner3bed95b2003-08-05 21:55:58 +00001050 assert(OperandsColoredMap[MI] == true &&
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001051 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1052 "are marked for an instruction.");
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001053
Chris Lattner3bed95b2003-08-05 21:55:58 +00001054 // Add the registers already marked as used by the instruction.
1055 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1056 if (MI->getOperand(i).hasAllocatedReg())
1057 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1058
1059 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1060 if (MI->getImplicitOp(i).hasAllocatedReg())
1061 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1062 RegType,MRI);
1063
Chris Lattner3fd1f5b2003-08-05 22:11:13 +00001064 // Add all of the scratch registers that are used to save values across the
1065 // instruction (e.g., for saving state register values).
1066 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1067 IR = ScratchRegsUsed.equal_range(MI);
1068 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1069 markRegisterUsed(I->second, RC, RegType, MRI);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001070
Vikram S. Advef5af6362002-07-08 23:15:32 +00001071 // If there are implicit references, mark their allocated regs as well
Chris Lattner3bed95b2003-08-05 21:55:58 +00001072 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
Vikram S. Advef5af6362002-07-08 23:15:32 +00001073 if (const LiveRange*
Brian Gaeke4efe3422003-09-21 01:23:46 +00001074 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
Vikram S. Advef5af6362002-07-08 23:15:32 +00001075 if (LRofImpRef->hasColor())
1076 // this implicit reference is in a LR that received a color
Vikram S. Advebc001b22003-07-25 21:06:09 +00001077 RC->markColorsUsed(LRofImpRef->getColor(),
1078 MRI.getRegTypeForLR(LRofImpRef), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001079}
1080
1081
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001082//----------------------------------------------------------------------------
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001083// If there are delay slots for an instruction, the instructions
1084// added after it must really go after the delayed instruction(s).
1085// So, we move the InstrAfter of that instruction to the
1086// corresponding delayed instruction using the following method.
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001087//----------------------------------------------------------------------------
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001088
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001089void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1090 const MachineInstr *DelayedMI)
1091{
Vikram S. Advefeb32982003-08-12 22:22:24 +00001092 // "added after" instructions of the original instr
1093 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1094
1095 if (DEBUG_RA && OrigAft.size() > 0) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001096 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1097 std::cerr << " to last delay slot instrn: " << *DelayedMI;
Vikram S. Adve814030a2003-07-29 19:49:21 +00001098 }
1099
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001100 // "added after" instructions of the delayed instr
Vikram S. Adve814030a2003-07-29 19:49:21 +00001101 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001102
1103 // go thru all the "added after instructions" of the original instruction
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001104 // and append them to the "added after instructions" of the delayed
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001105 // instructions
Chris Lattner697954c2002-01-20 22:54:45 +00001106 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001107
1108 // empty the "added after instructions" of the original instruction
1109 OrigAft.clear();
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001110}
Ruchira Sasanka0931a012001-09-15 19:06:58 +00001111
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001112
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001113void PhyRegAlloc::colorIncomingArgs()
1114{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001115 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
Vikram S. Adve814030a2003-07-29 19:49:21 +00001116 AddedInstrAtEntry.InstrnsAfter);
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001117}
1118
Ruchira Sasankae727f852001-09-18 22:43:57 +00001119
1120//----------------------------------------------------------------------------
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001121// This method calls setSugColorUsable method of each live range. This
1122// will determine whether the suggested color of LR is really usable.
1123// A suggested color is not usable when the suggested color is volatile
1124// AND when there are call interferences
1125//----------------------------------------------------------------------------
1126
1127void PhyRegAlloc::markUnusableSugColors()
1128{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001129 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1130 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001131
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001132 for (; HMI != HMIEnd ; ++HMI ) {
1133 if (HMI->first) {
1134 LiveRange *L = HMI->second; // get the LiveRange
1135 if (L) {
1136 if (L->hasSuggestedColor()) {
1137 int RCID = L->getRegClass()->getID();
1138 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1139 L->isCallInterference() )
1140 L->setSuggestedColorUsable( false );
1141 else
1142 L->setSuggestedColorUsable( true );
1143 }
1144 } // if L->hasSuggestedColor()
1145 }
1146 } // for all LR's in hash map
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001147}
1148
1149
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001150//----------------------------------------------------------------------------
1151// The following method will set the stack offsets of the live ranges that
Misha Brukman37f92e22003-09-11 22:34:13 +00001152// are decided to be spilled. This must be called just after coloring the
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001153// LRs using the graph coloring algo. For each live range that is spilled,
1154// this method allocate a new spill position on the stack.
1155//----------------------------------------------------------------------------
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001156
Chris Lattner37730942002-02-05 03:52:29 +00001157void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001158 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001159
Brian Gaeke4efe3422003-09-21 01:23:46 +00001160 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1161 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001162
Chris Lattner7e708292002-06-25 16:13:24 +00001163 for ( ; HMI != HMIEnd ; ++HMI) {
Chris Lattner37730942002-02-05 03:52:29 +00001164 if (HMI->first && HMI->second) {
Vikram S. Adve3bf08922003-07-10 19:42:55 +00001165 LiveRange *L = HMI->second; // get the LiveRange
1166 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
Brian Gaeke4efe3422003-09-21 01:23:46 +00001167 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001168 L->setSpillOffFromFP(stackOffset);
1169 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001170 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001171 << ": stack-offset = " << stackOffset << "\n";
1172 }
Chris Lattner37730942002-02-05 03:52:29 +00001173 }
1174 } // for all LR's in hash map
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001175}
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001176
Brian Gaeke874f4232003-09-21 02:50:21 +00001177
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001178//----------------------------------------------------------------------------
Brian Gaeke305f02d2003-09-16 15:38:05 +00001179// The entry point to Register Allocation
Ruchira Sasankae727f852001-09-18 22:43:57 +00001180//----------------------------------------------------------------------------
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001181
Brian Gaeke4efe3422003-09-21 01:23:46 +00001182bool PhyRegAlloc::runOnFunction (Function &F) {
1183 if (DEBUG_RA)
1184 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1185
1186 Fn = &F;
1187 MF = &MachineFunction::get (Fn);
1188 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1189 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1190 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1191
1192 // Create each RegClass for the target machine and add it to the
1193 // RegClassList. This must be done before calling constructLiveRanges().
1194 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1195 RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (),
1196 MRI.getMachineRegClass (rc)));
1197
1198 LRI->constructLiveRanges(); // create LR info
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001199 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
Brian Gaeke4efe3422003-09-21 01:23:46 +00001200 LRI->printLiveRanges();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001201
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001202 createIGNodeListsAndIGs(); // create IGNode list and IGs
1203
1204 buildInterferenceGraphs(); // build IGs in all reg classes
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001205
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001206 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001207 // print all LRs in all reg classes
Chris Lattner7e708292002-06-25 16:13:24 +00001208 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1209 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001210
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001211 // print IGs in all register classes
Chris Lattner7e708292002-06-25 16:13:24 +00001212 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1213 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001214 }
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001215
Brian Gaeke4efe3422003-09-21 01:23:46 +00001216 LRI->coalesceLRs(); // coalesce all live ranges
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +00001217
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001218 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001219 // print all LRs in all reg classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001220 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1221 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001222
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001223 // print IGs in all register classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001224 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1225 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001226 }
1227
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001228 // mark un-usable suggested color before graph coloring algorithm.
1229 // When this is done, the graph coloring algo will not reserve
1230 // suggested color unnecessarily - they can be used by another LR
1231 markUnusableSugColors();
1232
1233 // color all register classes using the graph coloring algo
Chris Lattner7e708292002-06-25 16:13:24 +00001234 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerf726e772002-10-28 19:22:04 +00001235 RegClassList[rc]->colorAllRegs();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001236
Misha Brukman37f92e22003-09-11 22:34:13 +00001237 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1238 // a position for such spilled LRs
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001239 allocateStackSpace4SpilledLRs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001240
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001241 // Reset the temp. area on the stack before use by the first instruction.
1242 // This will also happen after updating each instruction.
Brian Gaeke4efe3422003-09-21 01:23:46 +00001243 MF->getInfo()->popAllTempValues();
Ruchira Sasankaf90870f2001-11-15 22:02:06 +00001244
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001245 // color incoming args - if the correct color was not received
1246 // insert code to copy to the correct register
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001247 colorIncomingArgs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001248
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001249 // Now update the machine code with register names and add any
1250 // additional code inserted by the register allocator to the instruction
1251 // stream
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001252 updateMachineCode();
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001253
Chris Lattner045e7c82001-09-19 16:26:23 +00001254 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001255 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
Brian Gaeke4efe3422003-09-21 01:23:46 +00001256 MF->dump();
Chris Lattner045e7c82001-09-19 16:26:23 +00001257 }
Brian Gaeke4efe3422003-09-21 01:23:46 +00001258
1259 // Tear down temporary data structures
1260 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1261 delete RegClassList[rc];
1262 RegClassList.clear ();
1263 AddedInstrMap.clear ();
1264 OperandsColoredMap.clear ();
1265 ScratchRegsUsed.clear ();
1266 AddedInstrAtEntry.clear ();
1267 delete LRI;
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001268
Brian Gaeke4efe3422003-09-21 01:23:46 +00001269 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1270 return false; // Function was not modified
1271}