blob: 0f1f6d289b90277c4a8d377be4a2756f781e99b9 [file] [log] [blame]
Chris Lattner179cdfb2002-08-09 20:08:03 +00001//===-- PhyRegAlloc.cpp ---------------------------------------------------===//
Vikram S. Adve12af1642001-11-08 04:48:50 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Brian Gaeke222bd532003-09-24 18:16:23 +000010// Traditional graph-coloring global register allocator currently used
11// by the SPARC back-end.
12//
13// NOTE: This register allocator has some special support
14// for the Reoptimizer, such as not saving some registers on calls to
15// the first-level instrumentation function.
16//
17// NOTE 2: This register allocator can save its state in a global
18// variable in the module it's working on. This feature is not
19// thread-safe; if you have doubts, leave it turned off.
Chris Lattner179cdfb2002-08-09 20:08:03 +000020//
21//===----------------------------------------------------------------------===//
Ruchira Sasanka8e604792001-09-14 21:18:34 +000022
Brian Gaeke537132b2003-10-23 20:32:55 +000023#include "AllocInfo.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000024#include "IGNode.h"
Chris Lattner70b2f562003-09-01 20:09:04 +000025#include "PhyRegAlloc.h"
Chris Lattner4309e732003-01-15 19:57:07 +000026#include "RegAllocCommon.h"
Chris Lattner9d4ed152003-01-15 21:14:01 +000027#include "RegClass.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000028#include "llvm/Constants.h"
29#include "llvm/DerivedTypes.h"
30#include "llvm/iOther.h"
31#include "llvm/Module.h"
32#include "llvm/Type.h"
33#include "llvm/Analysis/LoopInfo.h"
Chris Lattner797c1362003-09-30 20:13:59 +000034#include "llvm/CodeGen/FunctionLiveVarInfo.h"
35#include "llvm/CodeGen/InstrSelection.h"
Brian Gaeke3ceac852003-10-30 21:21:33 +000036#include "llvm/CodeGen/MachineCodeForInstruction.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000037#include "llvm/CodeGen/MachineFunction.h"
38#include "llvm/CodeGen/MachineFunctionInfo.h"
Brian Gaeke874f4232003-09-21 02:50:21 +000039#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerf6ee49f2003-01-15 18:08:07 +000040#include "llvm/CodeGen/MachineInstrBuilder.h"
Vikram S. Advedabb41d2002-05-19 15:29:31 +000041#include "llvm/CodeGen/MachineInstrAnnot.h"
Chris Lattner797c1362003-09-30 20:13:59 +000042#include "llvm/CodeGen/Passes.h"
Chris Lattner797c1362003-09-30 20:13:59 +000043#include "llvm/Support/InstIterator.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000044#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner4bc23482002-09-15 07:07:55 +000045#include "Support/CommandLine.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000046#include "Support/SetOperations.h"
47#include "Support/STLExtras.h"
Brian Gaekebd353fb2003-09-21 03:57:37 +000048#include <cmath>
Vikram S. Adve12af1642001-11-08 04:48:50 +000049
Brian Gaeked0fde302003-11-11 22:41:34 +000050namespace llvm {
51
Chris Lattner70e60cb2002-05-22 17:08:27 +000052RegAllocDebugLevel_t DEBUG_RA;
Vikram S. Adve39c94e12002-09-14 23:05:33 +000053
Brian Gaeke8fc49342003-10-24 21:21:58 +000054/// The reoptimizer wants to be able to grovel through the register
55/// allocator's state after it has done its job. This is a hack.
56///
57PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
Brian Gaekee9414ca2003-11-10 07:12:01 +000058const bool SaveStateToModule = true;
Brian Gaeke8fc49342003-10-24 21:21:58 +000059
Chris Lattner5ff62e92002-07-22 02:10:13 +000060static cl::opt<RegAllocDebugLevel_t, true>
61DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
62 cl::desc("enable register allocation debugging information"),
63 cl::values(
Vikram S. Adve39c94e12002-09-14 23:05:33 +000064 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
65 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
66 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
67 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
68 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
69 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
Chris Lattner5ff62e92002-07-22 02:10:13 +000070 0));
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000071
Brian Gaeke59b1c562003-09-24 17:50:28 +000072static cl::opt<bool>
73SaveRegAllocState("save-ra-state", cl::Hidden,
74 cl::desc("write reg. allocator state into module"));
75
Brian Gaekebf3c4cf2003-08-14 06:09:32 +000076FunctionPass *getRegisterAllocator(TargetMachine &T) {
Brian Gaeke4efe3422003-09-21 01:23:46 +000077 return new PhyRegAlloc (T);
Chris Lattner2f9b28e2002-02-04 15:54:09 +000078}
Chris Lattner6dd98a62002-02-04 00:33:08 +000079
Chris Lattner8474f6f2003-09-23 15:13:04 +000080void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
81 AU.addRequired<LoopInfo> ();
82 AU.addRequired<FunctionLiveVarInfo> ();
83}
84
85
Brian Gaekeaf843702003-10-22 20:22:53 +000086/// Initialize interference graphs (one in each reg class) and IGNodeLists
87/// (one in each IG). The actual nodes will be pushed later.
88///
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000089void PhyRegAlloc::createIGNodeListsAndIGs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +000090 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000091
Brian Gaeke4efe3422003-09-21 01:23:46 +000092 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
Brian Gaeke4efe3422003-09-21 01:23:46 +000093 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000094
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000095 for (; HMI != HMIEnd ; ++HMI ) {
96 if (HMI->first) {
97 LiveRange *L = HMI->second; // get the LiveRange
98 if (!L) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +000099 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000100 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000101 << RAV(HMI->first) << "****\n";
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000102 continue;
103 }
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000104
105 // if the Value * is not null, and LR is not yet written to the IGNodeList
Chris Lattner7e708292002-06-25 16:13:24 +0000106 if (!(L->getUserIGNode()) ) {
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000107 RegClass *const RC = // RegClass of first value in the LR
Brian Gaeke59b1c562003-09-24 17:50:28 +0000108 RegClassList[ L->getRegClassID() ];
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000109 RC->addLRToIG(L); // add this LR to an IG
110 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000111 }
112 }
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000113
114 // init RegClassList
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000116 RegClassList[rc]->createInterferenceGraph();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000117
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000118 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000119}
120
121
Brian Gaekeaf843702003-10-22 20:22:53 +0000122/// Add all interferences for a given instruction. Interference occurs only
123/// if the LR of Def (Inst or Arg) is of the same reg class as that of live
124/// var. The live var passed to this function is the LVset AFTER the
125/// instruction.
126///
127void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
Chris Lattner296b7732002-02-05 02:52:05 +0000128 bool isCallInst) {
Chris Lattner296b7732002-02-05 02:52:05 +0000129 ValueSet::const_iterator LIt = LVSet->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000130
131 // get the live range of instruction
Brian Gaeke4efe3422003-09-21 01:23:46 +0000132 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000133
134 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
135 assert( IGNodeOfDef );
136
137 RegClass *const RCOfDef = LROfDef->getRegClass();
138
139 // for each live var in live variable set
Chris Lattner7e708292002-06-25 16:13:24 +0000140 for ( ; LIt != LVSet->end(); ++LIt) {
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000141
Vikram S. Advef5af6362002-07-08 23:15:32 +0000142 if (DEBUG_RA >= RA_DEBUG_Verbose)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000143 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000144
145 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000146 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000147
148 // LROfVar can be null if it is a const since a const
149 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000150 if (LROfVar)
151 if (LROfDef != LROfVar) // do not set interf for same LR
152 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
153 RCOfDef->setInterference( LROfDef, LROfVar);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000154 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000155}
156
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000157
Brian Gaekeaf843702003-10-22 20:22:53 +0000158/// For a call instruction, this method sets the CallInterference flag in
159/// the LR of each variable live in the Live Variable Set live after the
160/// call instruction (except the return value of the call instruction - since
161/// the return value does not interfere with that call itself).
162///
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000163void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
Chris Lattner296b7732002-02-05 02:52:05 +0000164 const ValueSet *LVSetAft) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000165 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000166 std::cerr << "\n For call inst: " << *MInst;
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000167
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000168 // for each live var in live variable set after machine inst
Vikram S. Adve65b2f402003-07-02 01:24:00 +0000169 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
170 LIt != LEnd; ++LIt) {
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000171
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000172 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000173 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000174
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000175 // LR can be null if it is a const since a const
176 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000177 if (LR ) {
178 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000179 std::cerr << "\n\tLR after Call: ";
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000180 printSet(*LR);
181 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000182 LR->setCallInterference();
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000183 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000184 std::cerr << "\n ++After adding call interference for LR: " ;
Chris Lattner296b7732002-02-05 02:52:05 +0000185 printSet(*LR);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000186 }
187 }
188
189 }
190
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000191 // Now find the LR of the return value of the call
192 // We do this because, we look at the LV set *after* the instruction
193 // to determine, which LRs must be saved across calls. The return value
194 // of the call is live in this set - but it does not interfere with call
195 // (i.e., we can allocate a volatile register to the return value)
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000196 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
197
198 if (const Value *RetVal = argDesc->getReturnValue()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000199 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000200 assert( RetValLR && "No LR for RetValue of call");
201 RetValLR->clearCallInterference();
202 }
203
204 // If the CALL is an indirect call, find the LR of the function pointer.
205 // That has a call interference because it conflicts with outgoing args.
Chris Lattner7e708292002-06-25 16:13:24 +0000206 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000207 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000208 assert( AddrValLR && "No LR for indirect addr val of call");
209 AddrValLR->setCallInterference();
210 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000211}
212
213
Brian Gaekeaf843702003-10-22 20:22:53 +0000214/// Create interferences in the IG of each RegClass, and calculate the spill
215/// cost of each Live Range (it is done in this method to save another pass
216/// over the code).
217///
218void PhyRegAlloc::buildInterferenceGraphs() {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000219 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000220 std::cerr << "Creating interference graphs ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000221
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000222 unsigned BBLoopDepthCost;
Brian Gaeke4efe3422003-09-21 01:23:46 +0000223 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000224 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000225 const MachineBasicBlock &MBB = *BBI;
226 const BasicBlock *BB = MBB.getBasicBlock();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000227
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000228 // find the 10^(loop_depth) of this BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000229 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000230
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000231 // get the iterator for machine instructions
Chris Lattnerf726e772002-10-28 19:22:04 +0000232 MachineBasicBlock::const_iterator MII = MBB.begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000233
234 // iterate over all the machine instructions in BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000235 for ( ; MII != MBB.end(); ++MII) {
236 const MachineInstr *MInst = *MII;
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000237
238 // get the LV set after the instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000239 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
240 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000241
Brian Gaekeaf843702003-10-22 20:22:53 +0000242 if (isCallInst) {
Misha Brukman37f92e22003-09-11 22:34:13 +0000243 // set the isCallInterference flag of each live range which extends
244 // across this call instruction. This information is used by graph
245 // coloring algorithm to avoid allocating volatile colors to live ranges
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000246 // that span across calls (since they have to be saved/restored)
Chris Lattner748697d2002-02-05 04:20:12 +0000247 setCallInterferences(MInst, &LVSetAI);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000248 }
249
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000250 // iterate over all MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000251 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
252 OpE = MInst->end(); OpI != OpE; ++OpI) {
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000253 if (OpI.isDef()) // create a new LR since def
Chris Lattner748697d2002-02-05 04:20:12 +0000254 addInterference(*OpI, &LVSetAI, isCallInst);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000255
256 // Calculate the spill cost of each live range
Brian Gaeke4efe3422003-09-21 01:23:46 +0000257 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
Chris Lattner2f898d22002-02-05 06:02:59 +0000258 if (LR) LR->addSpillCost(BBLoopDepthCost);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000259 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000260
Brian Gaekeaf843702003-10-22 20:22:53 +0000261 // Mark all operands of pseudo-instructions as interfering with one
262 // another. This must be done because pseudo-instructions may be
263 // expanded to multiple instructions by the assembler, so all the
264 // operands must get distinct registers.
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000265 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000266 addInterf4PseudoInstr(MInst);
267
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000268 // Also add interference for any implicit definitions in a machine
269 // instr (currently, only calls have this).
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000270 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000271 for (unsigned z=0; z < NumOfImpRefs; z++)
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000272 if (MInst->getImplicitOp(z).isDef())
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000273 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +0000274
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000275 } // for all machine instructions in BB
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000276 } // for all BBs in function
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000277
Misha Brukman37f92e22003-09-11 22:34:13 +0000278 // add interferences for function arguments. Since there are no explicit
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000279 // defs in the function for args, we have to add them manually
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000280 addInterferencesForArgs();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000281
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000282 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000283 std::cerr << "Interference graphs calculated!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000284}
285
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000286
Brian Gaekeaf843702003-10-22 20:22:53 +0000287/// Mark all operands of the given MachineInstr as interfering with one
288/// another.
289///
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000290void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000291 bool setInterf = false;
292
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000293 // iterate over MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000294 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
295 ItE = MInst->end(); It1 != ItE; ++It1) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000296 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000297 assert((LROfOp1 || It1.isDef()) && "No LR for Def in PSEUDO insruction");
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000298
Chris Lattner2f898d22002-02-05 06:02:59 +0000299 MachineInstr::const_val_op_iterator It2 = It1;
Chris Lattner7e708292002-06-25 16:13:24 +0000300 for (++It2; It2 != ItE; ++It2) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000301 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000302
Chris Lattner2f898d22002-02-05 06:02:59 +0000303 if (LROfOp2) {
304 RegClass *RCOfOp1 = LROfOp1->getRegClass();
305 RegClass *RCOfOp2 = LROfOp2->getRegClass();
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000306
Chris Lattner7e708292002-06-25 16:13:24 +0000307 if (RCOfOp1 == RCOfOp2 ){
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000308 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000309 setInterf = true;
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000310 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000311 } // if Op2 has a LR
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000312 } // for all other defs in machine instr
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000313 } // for all operands in an instruction
314
Chris Lattner2f898d22002-02-05 06:02:59 +0000315 if (!setInterf && MInst->getNumOperands() > 2) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000316 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
317 std::cerr << *MInst;
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000318 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000319 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000320}
321
322
Brian Gaekeaf843702003-10-22 20:22:53 +0000323/// Add interferences for incoming arguments to a function.
324///
Chris Lattner296b7732002-02-05 02:52:05 +0000325void PhyRegAlloc::addInterferencesForArgs() {
326 // get the InSet of root BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000327 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000328
Chris Lattnerf726e772002-10-28 19:22:04 +0000329 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000330 // add interferences between args and LVars at start
331 addInterference(AI, &InSet, false);
332
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000333 if (DEBUG_RA >= RA_DEBUG_Interference)
Brian Gaekeaf843702003-10-22 20:22:53 +0000334 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000335 }
336}
337
338
Brian Gaekeaf843702003-10-22 20:22:53 +0000339/// The following are utility functions used solely by updateMachineCode and
340/// the functions that it calls. They should probably be folded back into
341/// updateMachineCode at some point.
342///
Vikram S. Adve48762092002-04-25 04:34:15 +0000343
Brian Gaekeaf843702003-10-22 20:22:53 +0000344// used by: updateMachineCode (1 time), PrependInstructions (1 time)
345inline void InsertBefore(MachineInstr* newMI, MachineBasicBlock& MBB,
346 MachineBasicBlock::iterator& MII) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000347 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000348 ++MII;
349}
350
Brian Gaekeaf843702003-10-22 20:22:53 +0000351// used by: AppendInstructions (1 time)
352inline void InsertAfter(MachineInstr* newMI, MachineBasicBlock& MBB,
353 MachineBasicBlock::iterator& MII) {
Vikram S. Advecb202e32002-10-11 16:12:40 +0000354 ++MII; // insert before the next instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000355 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000356}
357
Brian Gaekeaf843702003-10-22 20:22:53 +0000358// used by: updateMachineCode (1 time)
359inline void DeleteInstruction(MachineBasicBlock& MBB,
360 MachineBasicBlock::iterator& MII) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000361 MII = MBB.erase(MII);
362}
363
Brian Gaekeaf843702003-10-22 20:22:53 +0000364// used by: updateMachineCode (1 time)
365inline void SubstituteInPlace(MachineInstr* newMI, MachineBasicBlock& MBB,
366 MachineBasicBlock::iterator MII) {
Vikram S. Advecb202e32002-10-11 16:12:40 +0000367 *MII = newMI;
368}
369
Brian Gaekeaf843702003-10-22 20:22:53 +0000370// used by: updateMachineCode (2 times)
371inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
372 MachineBasicBlock& MBB,
373 MachineBasicBlock::iterator& MII,
374 const std::string& msg) {
375 if (!IBef.empty()) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000376 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000377 std::vector<MachineInstr *>::iterator AdIt;
Brian Gaekeaf843702003-10-22 20:22:53 +0000378 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000379 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
Brian Gaekeaf843702003-10-22 20:22:53 +0000388// used by: updateMachineCode (1 time)
389inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
390 MachineBasicBlock& MBB,
391 MachineBasicBlock::iterator& MII,
392 const std::string& msg) {
393 if (!IAft.empty()) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000394 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000395 std::vector<MachineInstr *>::iterator AdIt;
Brian Gaekeaf843702003-10-22 20:22:53 +0000396 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
Chris Lattner7e708292002-06-25 16:13:24 +0000397 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000398 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
399 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000400 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000401 InsertAfter(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000402 }
403 }
404}
405
Brian Gaekeaf843702003-10-22 20:22:53 +0000406/// Set the registers for operands in the given MachineInstr, if a register was
407/// successfully allocated. Return true if any of its operands has been marked
408/// for spill.
409///
Brian Gaeke4efe3422003-09-21 01:23:46 +0000410bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000411{
Vikram S. Adve814030a2003-07-29 19:49:21 +0000412 bool instrNeedsSpills = false;
413
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000414 // First, set the registers for operands in the machine instruction
415 // if a register was successfully allocated. Do this first because we
416 // will need to know which registers are already used by this instr'n.
Brian Gaekeaf843702003-10-22 20:22:53 +0000417 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000418 MachineOperand& Op = MInst->getOperand(OpNum);
419 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
Brian Gaekeaf843702003-10-22 20:22:53 +0000420 Op.getType() == MachineOperand::MO_CCRegister) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000421 const Value *const Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000422 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000423 // Remember if any operand needs spilling
424 instrNeedsSpills |= LR->isMarkedForSpill();
425
426 // An operand may have a color whether or not it needs spilling
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000427 if (LR->hasColor())
428 MInst->SetRegForOperand(OpNum,
Brian Gaeke59b1c562003-09-24 17:50:28 +0000429 MRI.getUnifiedRegNum(LR->getRegClassID(),
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000430 LR->getColor()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000431 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000432 }
433 } // for each operand
Vikram S. Adve814030a2003-07-29 19:49:21 +0000434
435 return instrNeedsSpills;
436}
437
Brian Gaekeaf843702003-10-22 20:22:53 +0000438/// Mark allocated registers (using markAllocatedRegs()) on the instruction
439/// that MII points to. Then, if it's a call instruction, insert caller-saving
440/// code before and after it. Finally, insert spill code before and after it,
441/// using insertCode4SpilledLR().
442///
Vikram S. Adve814030a2003-07-29 19:49:21 +0000443void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
Brian Gaekeaf843702003-10-22 20:22:53 +0000444 MachineBasicBlock &MBB) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000445 MachineInstr* MInst = *MII;
446 unsigned Opcode = MInst->getOpCode();
447
448 // Reset tmp stack positions so they can be reused for each machine instr.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000449 MF->getInfo()->popAllTempValues();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000450
451 // Mark the operands for which regs have been allocated.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000452 bool instrNeedsSpills = markAllocatedRegs(*MII);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000453
454#ifndef NDEBUG
455 // Mark that the operands have been updated. Later,
456 // setRelRegsUsedByThisInst() is called to find registers used by each
457 // MachineInst, and it should not be used for an instruction until
458 // this is done. This flag just serves as a sanity check.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000459 OperandsColoredMap[MInst] = true;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000460#endif
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000461
Vikram S. Advebc001b22003-07-25 21:06:09 +0000462 // Now insert caller-saving code before/after the call.
463 // Do this before inserting spill code since some registers must be
464 // used by save/restore and spill code should not use those registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000465 if (TM.getInstrInfo().isCall(Opcode)) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000466 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Adve814030a2003-07-29 19:49:21 +0000467 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
468 MBB.getBasicBlock());
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000469 }
Vikram S. Advebc001b22003-07-25 21:06:09 +0000470
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000471 // Now insert spill code for remaining operands not allocated to
472 // registers. This must be done even for call return instructions
473 // since those are not handled by the special code above.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000474 if (instrNeedsSpills)
Brian Gaekeaf843702003-10-22 20:22:53 +0000475 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000476 MachineOperand& Op = MInst->getOperand(OpNum);
477 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
Brian Gaekeaf843702003-10-22 20:22:53 +0000478 Op.getType() == MachineOperand::MO_CCRegister) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000479 const Value* Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000480 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000481 if (LR->isMarkedForSpill())
482 insertCode4SpilledLR(LR, MII, MBB, OpNum);
483 }
484 } // for each operand
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000485}
486
Brian Gaekeaf843702003-10-22 20:22:53 +0000487/// Iterate over all the MachineBasicBlocks in the current function and set
488/// the allocated registers for each instruction (using updateInstruction()),
489/// after register allocation is complete. Then move code out of delay slots.
490///
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000491void PhyRegAlloc::updateMachineCode()
492{
Chris Lattner7e708292002-06-25 16:13:24 +0000493 // Insert any instructions needed at method entry
Brian Gaeke4efe3422003-09-21 01:23:46 +0000494 MachineBasicBlock::iterator MII = MF->front().begin();
495 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
Chris Lattner7e708292002-06-25 16:13:24 +0000496 "At function entry: \n");
497 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
498 "InstrsAfter should be unnecessary since we are just inserting at "
499 "the function entry point here.");
Vikram S. Adve48762092002-04-25 04:34:15 +0000500
Brian Gaeke4efe3422003-09-21 01:23:46 +0000501 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000502 BBI != BBE; ++BBI) {
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 =
Brian Gaekeaf843702003-10-22 20:22:53 +0000529 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode())) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000530 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
531
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000532 // Check the 2 conditions above:
533 // (1) Does a branch need instructions added after it?
534 // (2) O/w does delay slot instr. need instrns before or after?
Vikram S. Adve814030a2003-07-29 19:49:21 +0000535 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
536 TM.getInstrInfo().isReturn(MInst->getOpCode()));
537 bool cond1 = (isBranch &&
538 AddedInstrMap.count(MInst) &&
539 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
540 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
541 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
542 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000543
Brian Gaekeaf843702003-10-22 20:22:53 +0000544 if (cond1 || cond2) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000545 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
546 "FIXME: Moving an annulled delay slot instruction!");
547 assert(delaySlots==1 &&
548 "InsertBefore does not yet handle >1 delay slots!");
549 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000550
551 // In case (1), delete it and don't replace with anything!
552 // Otherwise (i.e., case (2) only) replace it with a NOP.
553 if (cond1) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000554 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
555 --MII; // reset MII for ++MII of loop
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000556 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000557 else
558 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
559 MBB, MII+1); // replace with NOP
560
561 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000562 std::cerr << "\nRegAlloc: Moved instr. with added code: "
Vikram S. Adve814030a2003-07-29 19:49:21 +0000563 << *DelaySlotMI
564 << " out of delay slots of instr: " << *MInst;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000565 }
566 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000567 else
568 // For non-branch instr with delay slots (probably a call), move
569 // InstrAfter to the instr. in the last delay slot.
570 move2DelayedInstr(*MII, *(MII+delaySlots));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000571 }
572
573 // Finally iterate over all instructions in BB and insert before/after
Vikram S. Advebc001b22003-07-25 21:06:09 +0000574 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000575 MachineInstr *MInst = *MII;
Vikram S. Advebc001b22003-07-25 21:06:09 +0000576
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000577 // do not process Phis
Vikram S. Advebc001b22003-07-25 21:06:09 +0000578 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000579 continue;
580
Vikram S. Advebc001b22003-07-25 21:06:09 +0000581 // if there are any added instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000582 if (AddedInstrMap.count(MInst)) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000583 AddedInstrns &CallAI = AddedInstrMap[MInst];
584
585#ifndef NDEBUG
Vikram S. Adve814030a2003-07-29 19:49:21 +0000586 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
587 TM.getInstrInfo().isReturn(MInst->getOpCode()));
588 assert((!isBranch ||
589 AddedInstrMap[MInst].InstrnsAfter.size() <=
590 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
591 "Cannot put more than #delaySlots instrns after "
592 "branch or return! Need to handle temps differently.");
593#endif
594
595#ifndef NDEBUG
Vikram S. Advebc001b22003-07-25 21:06:09 +0000596 // Temporary sanity checking code to detect whether the same machine
597 // instruction is ever inserted twice before/after a call.
598 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000599 std::set<const MachineInstr*> instrsSeen;
600 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
601 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
602 "Duplicate machine instruction in InstrnsBefore!");
603 instrsSeen.insert(CallAI.InstrnsBefore[i]);
604 }
605 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
606 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
607 "Duplicate machine instruction in InstrnsBefore/After!");
608 instrsSeen.insert(CallAI.InstrnsAfter[i]);
609 }
610#endif
611
612 // Now add the instructions before/after this MI.
613 // We do this here to ensure that spill for an instruction is inserted
614 // as close as possible to an instruction (see above insertCode4Spill)
Vikram S. Advebc001b22003-07-25 21:06:09 +0000615 if (! CallAI.InstrnsBefore.empty())
616 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
617
618 if (! CallAI.InstrnsAfter.empty())
619 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
620
621 } // if there are any added instructions
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000622 } // for each machine instruction
Ruchira Sasanka0931a012001-09-15 19:06:58 +0000623 }
624}
625
626
Brian Gaekeaf843702003-10-22 20:22:53 +0000627/// Insert spill code for AN operand whose LR was spilled. May be called
628/// repeatedly for a single MachineInstr if it has many spilled operands. On
629/// each call, it finds a register which is not live at that instruction and
630/// also which is not used by other spilled operands of the same
631/// instruction. Then it uses this register temporarily to accommodate the
632/// spilled value.
633///
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);
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000647 bool isDef = Op.isDef();
648 bool isUse = Op.isUse();
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 Gaekeaf843702003-10-22 20:22:53 +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()
Brian Gaeke59b1c562003-09-24 17:50:28 +0000678 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000679 : 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;
Brian Gaekeaf843702003-10-22 20:22:53 +0000695 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
Chris Lattner27a08932002-10-22 23:16:21 +0000696 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
697 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000698 assert(scratchReg != MRI.getInvalidRegNum());
Vikram S. Advef5af6362002-07-08 23:15:32 +0000699 }
700
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000701 if (isUse) {
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000702 // for a USE, we have to load the value of LR from stack to a TmpReg
703 // and use the TmpReg as one operand of instruction
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000704
Vikram S. Advef5af6362002-07-08 23:15:32 +0000705 // actual loading instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000706 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
707 RegType, scratchReg);
Ruchira Sasanka226f1f02001-11-08 19:11:30 +0000708
Vikram S. Advef5af6362002-07-08 23:15:32 +0000709 // the actual load should be after the instructions to free up TmpRegU
710 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
711 AdIMid.clear();
712 }
713
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000714 if (isDef) { // if this is a Def
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000715 // for a DEF, we have to store the value produced by this instruction
716 // on the stack position allocated for this LR
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000717
Vikram S. Advef5af6362002-07-08 23:15:32 +0000718 // actual storing instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000719 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
720 RegType, scratchReg);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000721
Vikram S. Advef5af6362002-07-08 23:15:32 +0000722 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000723 } // if !DEF
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000724
Vikram S. Advef5af6362002-07-08 23:15:32 +0000725 // Finally, insert the entire spill code sequences before/after MInst
726 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
727 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
728
Chris Lattner7e708292002-06-25 16:13:24 +0000729 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000730 std::cerr << "\nFor Inst:\n " << *MInst;
731 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
732 std::cerr << "; added Instructions:";
Anand Shuklad58290e2002-07-09 19:18:56 +0000733 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
734 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
Chris Lattner7e708292002-06-25 16:13:24 +0000735 }
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000736}
737
738
Brian Gaekeaf843702003-10-22 20:22:53 +0000739/// Insert caller saving/restoring instructions before/after a call machine
740/// instruction (before or after any other instructions that were inserted for
741/// the call).
742///
Vikram S. Adve814030a2003-07-29 19:49:21 +0000743void
744PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
745 std::vector<MachineInstr*> &instrnsAfter,
746 MachineInstr *CallMI,
Brian Gaekeaf843702003-10-22 20:22:53 +0000747 const BasicBlock *BB) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000748 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
749
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000750 // hash set to record which registers were saved/restored
Vikram S. Adve814030a2003-07-29 19:49:21 +0000751 hash_set<unsigned> PushedRegSet;
752
753 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
754
755 // if the call is to a instrumentation function, do not insert save and
756 // restore instructions the instrumentation function takes care of save
757 // restore for volatile regs.
758 //
759 // FIXME: this should be made general, not specific to the reoptimizer!
Vikram S. Adve814030a2003-07-29 19:49:21 +0000760 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
761 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
762
763 // Now check if the call has a return value (using argDesc) and if so,
764 // find the LR of the TmpInstruction representing the return value register.
765 // (using the last or second-last *implicit operand* of the call MI).
766 // Insert it to to the PushedRegSet since we must not save that register
767 // and restore it after the call.
768 // We do this because, we look at the LV set *after* the instruction
769 // to determine, which LRs must be saved across calls. The return value
770 // of the call is live in this set - but we must not save/restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000771 if (const Value *origRetVal = argDesc->getReturnValue()) {
772 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
773 (argDesc->getIndirectFuncPtr()? 1 : 2));
774 const TmpInstruction* tmpRetVal =
775 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
776 assert(tmpRetVal->getOperand(0) == origRetVal &&
777 tmpRetVal->getType() == origRetVal->getType() &&
778 "Wrong implicit ref?");
Brian Gaeke4efe3422003-09-21 01:23:46 +0000779 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000780 assert(RetValLR && "No LR for RetValue of call");
781
782 if (! RetValLR->isMarkedForSpill())
783 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
784 RetValLR->getColor()));
785 }
786
787 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
788 ValueSet::const_iterator LIt = LVSetAft.begin();
789
790 // for each live var in live variable set after machine inst
791 for( ; LIt != LVSetAft.end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000792 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000793 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000794
795 // LR can be null if it is a const since a const
796 // doesn't have a dominating def - see Assumptions above
Brian Gaekeaf843702003-10-22 20:22:53 +0000797 if (LR) {
798 if (! LR->isMarkedForSpill()) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000799 assert(LR->hasColor() && "LR is neither spilled nor colored?");
800 unsigned RCID = LR->getRegClassID();
801 unsigned Color = LR->getColor();
802
803 if (MRI.isRegVolatile(RCID, Color) ) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000804 // if this is a call to the first-level reoptimizer
805 // instrumentation entry point, and the register is not
806 // modified by call, don't save and restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000807 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
808 continue;
809
810 // if the value is in both LV sets (i.e., live before and after
811 // the call machine instruction)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000812 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
813
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000814 // if we haven't already pushed this register...
Vikram S. Adve814030a2003-07-29 19:49:21 +0000815 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000816 unsigned RegType = MRI.getRegTypeForLR(LR);
817
818 // Now get two instructions - to push on stack and pop from stack
819 // and add them to InstrnsBefore and InstrnsAfter of the
820 // call instruction
Vikram S. Adve814030a2003-07-29 19:49:21 +0000821 int StackOff =
Brian Gaeke4efe3422003-09-21 01:23:46 +0000822 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000823
824 //---- Insert code for pushing the reg on stack ----------
825
826 std::vector<MachineInstr*> AdIBef, AdIAft;
827
828 // We may need a scratch register to copy the saved value
829 // to/from memory. This may itself have to insert code to
830 // free up a scratch register. Any such code should go before
831 // the save code. The scratch register, if any, is by default
832 // temporary and not "used" by the instruction unless the
833 // copy code itself decides to keep the value in the scratch reg.
834 int scratchRegType = -1;
835 int scratchReg = -1;
836 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
837 { // Find a register not live in the LVSet before CallMI
838 const ValueSet &LVSetBef =
839 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
840 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
841 CallMI, AdIBef, AdIAft);
842 assert(scratchReg != MRI.getInvalidRegNum());
843 }
844
845 if (AdIBef.size() > 0)
846 instrnsBefore.insert(instrnsBefore.end(),
847 AdIBef.begin(), AdIBef.end());
848
849 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
850 StackOff, RegType, scratchReg);
851
852 if (AdIAft.size() > 0)
853 instrnsBefore.insert(instrnsBefore.end(),
854 AdIAft.begin(), AdIAft.end());
855
856 //---- Insert code for popping the reg from the stack ----------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000857 AdIBef.clear();
858 AdIAft.clear();
859
860 // We may need a scratch register to copy the saved value
861 // from memory. This may itself have to insert code to
862 // free up a scratch register. Any such code should go
863 // after the save code. As above, scratch is not marked "used".
Vikram S. Adve814030a2003-07-29 19:49:21 +0000864 scratchRegType = -1;
865 scratchReg = -1;
866 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
867 { // Find a register not live in the LVSet after CallMI
868 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
869 CallMI, AdIBef, AdIAft);
870 assert(scratchReg != MRI.getInvalidRegNum());
871 }
872
873 if (AdIBef.size() > 0)
874 instrnsAfter.insert(instrnsAfter.end(),
875 AdIBef.begin(), AdIBef.end());
876
877 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
878 Reg, RegType, scratchReg);
879
880 if (AdIAft.size() > 0)
881 instrnsAfter.insert(instrnsAfter.end(),
882 AdIAft.begin(), AdIAft.end());
883
884 PushedRegSet.insert(Reg);
885
886 if(DEBUG_RA) {
887 std::cerr << "\nFor call inst:" << *CallMI;
888 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
889 for_each(instrnsBefore.begin(), instrnsBefore.end(),
890 std::mem_fun(&MachineInstr::dump));
891 std::cerr << " -and After:\n\t ";
892 for_each(instrnsAfter.begin(), instrnsAfter.end(),
893 std::mem_fun(&MachineInstr::dump));
894 }
895 } // if not already pushed
Vikram S. Adve814030a2003-07-29 19:49:21 +0000896 } // if LR has a volatile color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000897 } // if LR has color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000898 } // if there is a LR for Var
Vikram S. Adve814030a2003-07-29 19:49:21 +0000899 } // for each value in the LV set after instruction
900}
901
902
Brian Gaekeaf843702003-10-22 20:22:53 +0000903/// Returns the unified register number of a temporary register to be used
904/// BEFORE MInst. If no register is available, it will pick one and modify
905/// MIBef and MIAft to contain instructions used to free up this returned
906/// register.
907///
Vikram S. Advef5af6362002-07-08 23:15:32 +0000908int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
909 const ValueSet *LVSetBef,
910 MachineInstr *MInst,
911 std::vector<MachineInstr*>& MIBef,
912 std::vector<MachineInstr*>& MIAft) {
Chris Lattner133f0792002-10-28 04:45:29 +0000913 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000914
Brian Gaekeaf843702003-10-22 20:22:53 +0000915 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000916
917 if (RegU == -1) {
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000918 // we couldn't find an unused register. Generate code to free up a reg by
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000919 // saving it on stack and restoring after the instruction
Vikram S. Advef5af6362002-07-08 23:15:32 +0000920
Brian Gaeke4efe3422003-09-21 01:23:46 +0000921 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve12af1642001-11-08 04:48:50 +0000922
Vikram S. Advebc001b22003-07-25 21:06:09 +0000923 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000924
Vikram S. Advef5af6362002-07-08 23:15:32 +0000925 // Check if we need a scratch register to copy this register to memory.
926 int scratchRegType = -1;
Brian Gaekeaf843702003-10-22 20:22:53 +0000927 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
Chris Lattner133f0792002-10-28 04:45:29 +0000928 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
929 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000930 assert(scratchReg != MRI.getInvalidRegNum());
931
932 // We may as well hold the value in the scratch register instead
933 // of copying it to memory and back. But we have to mark the
934 // register as used by this instruction, so it does not get used
935 // as a scratch reg. by another operand or anyone else.
Chris Lattner3fd1f5b2003-08-05 22:11:13 +0000936 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000937 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
938 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
Brian Gaekeaf843702003-10-22 20:22:53 +0000939 } else { // the register can be copied directly to/from memory so do it.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000940 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
941 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
Brian Gaekeaf843702003-10-22 20:22:53 +0000942 }
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000943 }
Vikram S. Advef5af6362002-07-08 23:15:32 +0000944
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000945 return RegU;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000946}
947
Vikram S. Adve814030a2003-07-29 19:49:21 +0000948
Brian Gaekeaf843702003-10-22 20:22:53 +0000949/// Returns the register-class register number of a new unused register that
950/// can be used to accommodate a temporary value. May be called repeatedly
951/// for a single MachineInstr. On each call, it finds a register which is not
952/// live at that instruction and which is not used by any spilled operands of
953/// that instruction.
954///
955int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000956 const MachineInstr *MInst,
957 const ValueSet* LVSetBef) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000958 RC->clearColorsUsed(); // Reset array
Vikram S. Adve814030a2003-07-29 19:49:21 +0000959
960 if (LVSetBef == NULL) {
961 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
962 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
963 }
964
Chris Lattner296b7732002-02-05 02:52:05 +0000965 ValueSet::const_iterator LIt = LVSetBef->begin();
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000966
967 // for each live var in live variable set after machine inst
Chris Lattner7e708292002-06-25 16:13:24 +0000968 for ( ; LIt != LVSetBef->end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000969 // Get the live range corresponding to live var, and its RegClass
Brian Gaeke4efe3422003-09-21 01:23:46 +0000970 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000971
972 // LR can be null if it is a const since a const
973 // doesn't have a dominating def - see Assumptions above
Vikram S. Advebc001b22003-07-25 21:06:09 +0000974 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
975 RC->markColorsUsed(LRofLV->getColor(),
976 MRI.getRegTypeForLR(LRofLV), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000977 }
978
979 // It is possible that one operand of this MInst was already spilled
980 // and it received some register temporarily. If that's the case,
981 // it is recorded in machine operand. We must skip such registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000982 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000983
Vikram S. Advebc001b22003-07-25 21:06:09 +0000984 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
985 if (unusedReg >= 0)
986 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
987
Chris Lattner85c54652002-05-23 15:50:03 +0000988 return -1;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000989}
990
991
Brian Gaekeaf843702003-10-22 20:22:53 +0000992/// Return the unified register number of a register in class RC which is not
993/// used by any operands of MInst.
994///
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000995int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +0000996 const int RegType,
Chris Lattner85c54652002-05-23 15:50:03 +0000997 const MachineInstr *MInst) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000998 RC->clearColorsUsed();
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000999
Vikram S. Advebc001b22003-07-25 21:06:09 +00001000 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001001
Vikram S. Advebc001b22003-07-25 21:06:09 +00001002 // find the first unused color
1003 int unusedReg = RC->getUnusedColor(RegType);
1004 assert(unusedReg >= 0 &&
1005 "FATAL: No free register could be found in reg class!!");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001006
Vikram S. Advebc001b22003-07-25 21:06:09 +00001007 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001008}
1009
1010
Brian Gaekeaf843702003-10-22 20:22:53 +00001011/// Modify the IsColorUsedArr of register class RC, by setting the bits
1012/// corresponding to register RegNo. This is a helper method of
1013/// setRelRegsUsedByThisInst().
1014///
Chris Lattner3bed95b2003-08-05 21:55:58 +00001015static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1016 const TargetRegInfo &TRI) {
1017 unsigned classId = 0;
1018 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1019 if (RC->getID() == classId)
1020 RC->markColorsUsed(classRegNum, RegType, RegType);
1021}
1022
1023void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
Brian Gaekeaf843702003-10-22 20:22:53 +00001024 const MachineInstr *MI) {
Chris Lattner3bed95b2003-08-05 21:55:58 +00001025 assert(OperandsColoredMap[MI] == true &&
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001026 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1027 "are marked for an instruction.");
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001028
Brian Gaekeaf843702003-10-22 20:22:53 +00001029 // Add the registers already marked as used by the instruction. Both
1030 // explicit and implicit operands are set.
Chris Lattner3bed95b2003-08-05 21:55:58 +00001031 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1032 if (MI->getOperand(i).hasAllocatedReg())
1033 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1034
1035 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1036 if (MI->getImplicitOp(i).hasAllocatedReg())
1037 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1038 RegType,MRI);
1039
Chris Lattner3fd1f5b2003-08-05 22:11:13 +00001040 // Add all of the scratch registers that are used to save values across the
1041 // instruction (e.g., for saving state register values).
1042 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1043 IR = ScratchRegsUsed.equal_range(MI);
1044 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1045 markRegisterUsed(I->second, RC, RegType, MRI);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001046
Vikram S. Advef5af6362002-07-08 23:15:32 +00001047 // If there are implicit references, mark their allocated regs as well
Chris Lattner3bed95b2003-08-05 21:55:58 +00001048 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
Vikram S. Advef5af6362002-07-08 23:15:32 +00001049 if (const LiveRange*
Brian Gaeke4efe3422003-09-21 01:23:46 +00001050 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
Vikram S. Advef5af6362002-07-08 23:15:32 +00001051 if (LRofImpRef->hasColor())
1052 // this implicit reference is in a LR that received a color
Vikram S. Advebc001b22003-07-25 21:06:09 +00001053 RC->markColorsUsed(LRofImpRef->getColor(),
1054 MRI.getRegTypeForLR(LRofImpRef), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001055}
1056
1057
Brian Gaekeaf843702003-10-22 20:22:53 +00001058/// If there are delay slots for an instruction, the instructions added after
1059/// it must really go after the delayed instruction(s). So, we Move the
1060/// InstrAfter of that instruction to the corresponding delayed instruction
1061/// using the following method.
1062///
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001063void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1064 const MachineInstr *DelayedMI)
1065{
Vikram S. Advefeb32982003-08-12 22:22:24 +00001066 // "added after" instructions of the original instr
1067 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1068
1069 if (DEBUG_RA && OrigAft.size() > 0) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001070 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1071 std::cerr << " to last delay slot instrn: " << *DelayedMI;
Vikram S. Adve814030a2003-07-29 19:49:21 +00001072 }
1073
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001074 // "added after" instructions of the delayed instr
Vikram S. Adve814030a2003-07-29 19:49:21 +00001075 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001076
1077 // go thru all the "added after instructions" of the original instruction
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001078 // and append them to the "added after instructions" of the delayed
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001079 // instructions
Chris Lattner697954c2002-01-20 22:54:45 +00001080 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001081
1082 // empty the "added after instructions" of the original instruction
1083 OrigAft.clear();
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001084}
Ruchira Sasanka0931a012001-09-15 19:06:58 +00001085
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001086
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001087void PhyRegAlloc::colorIncomingArgs()
1088{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001089 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
Vikram S. Adve814030a2003-07-29 19:49:21 +00001090 AddedInstrAtEntry.InstrnsAfter);
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001091}
1092
Ruchira Sasankae727f852001-09-18 22:43:57 +00001093
Brian Gaekeaf843702003-10-22 20:22:53 +00001094/// Determine whether the suggested color of each live range is really usable,
1095/// and then call its setSuggestedColorUsable() method to record the answer. A
1096/// suggested color is NOT usable when the suggested color is volatile AND
1097/// when there are call interferences.
1098///
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001099void PhyRegAlloc::markUnusableSugColors()
1100{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001101 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1102 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001103
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001104 for (; HMI != HMIEnd ; ++HMI ) {
1105 if (HMI->first) {
1106 LiveRange *L = HMI->second; // get the LiveRange
Brian Gaeke59b1c562003-09-24 17:50:28 +00001107 if (L && L->hasSuggestedColor ())
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001108 L->setSuggestedColorUsable
1109 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1110 && L->isCallInterference ()));
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001111 }
1112 } // for all LR's in hash map
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001113}
1114
1115
Brian Gaekeaf843702003-10-22 20:22:53 +00001116/// For each live range that is spilled, allocates a new spill position on the
1117/// stack, and set the stack offsets of the live range that will be spilled to
1118/// that position. This must be called just after coloring the LRs.
1119///
Chris Lattner37730942002-02-05 03:52:29 +00001120void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001121 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001122
Brian Gaeke4efe3422003-09-21 01:23:46 +00001123 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1124 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001125
Chris Lattner7e708292002-06-25 16:13:24 +00001126 for ( ; HMI != HMIEnd ; ++HMI) {
Chris Lattner37730942002-02-05 03:52:29 +00001127 if (HMI->first && HMI->second) {
Vikram S. Adve3bf08922003-07-10 19:42:55 +00001128 LiveRange *L = HMI->second; // get the LiveRange
1129 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
Brian Gaeke4efe3422003-09-21 01:23:46 +00001130 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001131 L->setSpillOffFromFP(stackOffset);
1132 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001133 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001134 << ": stack-offset = " << stackOffset << "\n";
1135 }
Chris Lattner37730942002-02-05 03:52:29 +00001136 }
1137 } // for all LR's in hash map
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001138}
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001139
Brian Gaeke874f4232003-09-21 02:50:21 +00001140
Brian Gaeke21390412003-11-10 00:05:26 +00001141void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
1142 const Value *V, unsigned Insn, int Opnd) {
1143 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V);
1144 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();
1145 AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated;
1146 int Placement = -1;
1147 if ((HMI != HMIEnd) && HMI->second) {
1148 LiveRange *L = HMI->second;
1149 assert ((L->hasColor () || L->isMarkedForSpill ())
1150 && "Live range exists but not colored or spilled");
1151 if (L->hasColor ()) {
1152 AllocState = AllocInfo::Allocated;
1153 Placement = MRI.getUnifiedRegNum (L->getRegClassID (),
1154 L->getColor ());
1155 } else if (L->isMarkedForSpill ()) {
1156 AllocState = AllocInfo::Spilled;
1157 assert (L->hasSpillOffset ()
1158 && "Live range marked for spill but has no spill offset");
1159 Placement = L->getSpillOffFromFP ();
1160 }
1161 }
1162 state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement));
1163}
1164
1165
Brian Gaekeaf843702003-10-22 20:22:53 +00001166/// Save the global register allocation decisions made by the register
1167/// allocator so that they can be accessed later (sort of like "poor man's
1168/// debug info").
1169///
1170void PhyRegAlloc::saveState () {
Brian Gaeke537132b2003-10-23 20:32:55 +00001171 std::vector<AllocInfo> &state = FnAllocState[Fn];
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001172 unsigned Insn = 0;
Brian Gaeke3ceac852003-10-30 21:21:33 +00001173 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
Brian Gaeke21390412003-11-10 00:05:26 +00001174 saveStateForValue (state, (*II), Insn, -1);
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001175 for (unsigned i = 0; i < (*II)->getNumOperands (); ++i) {
1176 const Value *V = (*II)->getOperand (i);
Brian Gaeke21390412003-11-10 00:05:26 +00001177 // Don't worry about it unless it's something whose reg. we'll need.
1178 if (!isa<Argument> (V) && !isa<Instruction> (V))
1179 continue;
1180 saveStateForValue (state, V, Insn, i);
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001181 }
Brian Gaeke3ceac852003-10-30 21:21:33 +00001182 ++Insn;
1183 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001184}
1185
Brian Gaeke537132b2003-10-23 20:32:55 +00001186
Brian Gaekeaf843702003-10-22 20:22:53 +00001187/// Check the saved state filled in by saveState(), and abort if it looks
Brian Gaeke55766e12003-11-04 22:42:41 +00001188/// wrong. Only used when debugging. FIXME: Currently it just prints out
1189/// the state, which isn't quite as useful.
Brian Gaekeaf843702003-10-22 20:22:53 +00001190///
1191void PhyRegAlloc::verifySavedState () {
Brian Gaeke3ceac852003-10-30 21:21:33 +00001192 std::vector<AllocInfo> &state = FnAllocState[Fn];
1193 unsigned Insn = 0;
1194 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II) {
1195 const Instruction *I = *II;
1196 MachineCodeForInstruction &Instrs = MachineCodeForInstruction::get (I);
1197 std::cerr << "Instruction:\n" << " " << *I << "\n"
1198 << "MachineCodeForInstruction:\n";
1199 for (unsigned i = 0, n = Instrs.size (); i != n; ++i)
1200 std::cerr << " " << *Instrs[i] << "\n";
1201 std::cerr << "FnAllocState:\n";
1202 for (unsigned i = 0; i < state.size (); ++i) {
1203 AllocInfo &S = state[i];
Brian Gaeke97374d42004-01-28 19:05:43 +00001204 if (Insn == S.Instruction)
1205 std::cerr << " " << S << "\n";
Brian Gaeke3ceac852003-10-30 21:21:33 +00001206 }
1207 std::cerr << "----------\n";
1208 ++Insn;
1209 }
Brian Gaekeaf843702003-10-22 20:22:53 +00001210}
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001211
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001212
Brian Gaeke537132b2003-10-23 20:32:55 +00001213/// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1214/// Constant and stuffing it inside the Module. (NOTE: Soon, there will be
1215/// other, better ways of storing the saved state; this one is cumbersome and
Brian Gaeke21390412003-11-10 00:05:26 +00001216/// does not work well with the JIT.)
Brian Gaeke537132b2003-10-23 20:32:55 +00001217///
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001218bool PhyRegAlloc::doFinalization (Module &M) {
1219 if (!SaveRegAllocState)
1220 return false; // Nothing to do here, unless we're saving state.
1221
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001222 // If saving state into the module, just copy new elements to the
1223 // correct global.
Brian Gaeke8fc49342003-10-24 21:21:58 +00001224 if (!SaveStateToModule) {
1225 ExportedFnAllocState = FnAllocState;
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001226 // FIXME: should ONLY copy new elements in FnAllocState
Brian Gaeke8fc49342003-10-24 21:21:58 +00001227 return false;
1228 }
1229
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001230 // Convert FnAllocState to a single Constant array and add it
1231 // to the Module.
1232 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1233 std::vector<const Type *> TV;
1234 TV.push_back (Type::UIntTy);
1235 TV.push_back (AT);
1236 PointerType *PT = PointerType::get (StructType::get (TV));
1237
1238 std::vector<Constant *> allstate;
1239 for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1240 Function *F = I;
Brian Gaeke55766e12003-11-04 22:42:41 +00001241 if (F->isExternal ()) continue;
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001242 if (FnAllocState.find (F) == FnAllocState.end ()) {
1243 allstate.push_back (ConstantPointerNull::get (PT));
1244 } else {
Brian Gaeke537132b2003-10-23 20:32:55 +00001245 std::vector<AllocInfo> &state = FnAllocState[F];
Brian Gaeke60a3c552003-10-22 20:44:23 +00001246
1247 // Convert state into an LLVM ConstantArray, and put it in a
1248 // ConstantStruct (named S) along with its size.
Brian Gaeke537132b2003-10-23 20:32:55 +00001249 std::vector<Constant *> stateConstants;
1250 for (unsigned i = 0, s = state.size (); i != s; ++i)
1251 stateConstants.push_back (state[i].toConstant ());
1252 unsigned Size = stateConstants.size ();
Brian Gaeke60a3c552003-10-22 20:44:23 +00001253 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1254 std::vector<const Type *> TV;
1255 TV.push_back (Type::UIntTy);
1256 TV.push_back (AT);
1257 StructType *ST = StructType::get (TV);
1258 std::vector<Constant *> CV;
1259 CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
Brian Gaeke537132b2003-10-23 20:32:55 +00001260 CV.push_back (ConstantArray::get (AT, stateConstants));
Brian Gaeke60a3c552003-10-22 20:44:23 +00001261 Constant *S = ConstantStruct::get (ST, CV);
1262
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001263 GlobalVariable *GV =
Brian Gaeke60a3c552003-10-22 20:44:23 +00001264 new GlobalVariable (ST, true,
1265 GlobalValue::InternalLinkage, S,
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001266 F->getName () + ".regAllocState", &M);
Brian Gaeke60a3c552003-10-22 20:44:23 +00001267
Brian Gaeke21390412003-11-10 00:05:26 +00001268 // Have: { uint, [Size x { uint, int, uint, int }] } *
1269 // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001270 Constant *CE = ConstantExpr::getCast (ConstantPointerRef::get (GV), PT);
1271 allstate.push_back (CE);
1272 }
1273 }
1274
1275 unsigned Size = allstate.size ();
1276 // Final structure type is:
Brian Gaeke21390412003-11-10 00:05:26 +00001277 // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001278 std::vector<const Type *> TV2;
1279 TV2.push_back (Type::UIntTy);
1280 ArrayType *AT2 = ArrayType::get (PT, Size);
1281 TV2.push_back (AT2);
1282 StructType *ST2 = StructType::get (TV2);
1283 std::vector<Constant *> CV2;
1284 CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1285 CV2.push_back (ConstantArray::get (AT2, allstate));
Brian Gaekee9414ca2003-11-10 07:12:01 +00001286 new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001287 ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1288 &M);
1289 return false; // No error.
1290}
1291
1292
Brian Gaekeaf843702003-10-22 20:22:53 +00001293/// Allocate registers for the machine code previously generated for F using
1294/// the graph-coloring algorithm.
1295///
Brian Gaeke4efe3422003-09-21 01:23:46 +00001296bool PhyRegAlloc::runOnFunction (Function &F) {
1297 if (DEBUG_RA)
1298 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1299
1300 Fn = &F;
1301 MF = &MachineFunction::get (Fn);
1302 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1303 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1304 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1305
1306 // Create each RegClass for the target machine and add it to the
1307 // RegClassList. This must be done before calling constructLiveRanges().
1308 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1309 RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (),
1310 MRI.getMachineRegClass (rc)));
1311
1312 LRI->constructLiveRanges(); // create LR info
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001313 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
Brian Gaeke4efe3422003-09-21 01:23:46 +00001314 LRI->printLiveRanges();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001315
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001316 createIGNodeListsAndIGs(); // create IGNode list and IGs
1317
1318 buildInterferenceGraphs(); // build IGs in all reg classes
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001319
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001320 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001321 // print all LRs in all reg classes
Chris Lattner7e708292002-06-25 16:13:24 +00001322 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1323 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001324
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001325 // print IGs in all register classes
Chris Lattner7e708292002-06-25 16:13:24 +00001326 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1327 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001328 }
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001329
Brian Gaeke4efe3422003-09-21 01:23:46 +00001330 LRI->coalesceLRs(); // coalesce all live ranges
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +00001331
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001332 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001333 // print all LRs in all reg classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001334 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1335 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001336
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001337 // print IGs in all register classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001338 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1339 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001340 }
1341
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001342 // mark un-usable suggested color before graph coloring algorithm.
1343 // When this is done, the graph coloring algo will not reserve
1344 // suggested color unnecessarily - they can be used by another LR
1345 markUnusableSugColors();
1346
1347 // color all register classes using the graph coloring algo
Chris Lattner7e708292002-06-25 16:13:24 +00001348 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerf726e772002-10-28 19:22:04 +00001349 RegClassList[rc]->colorAllRegs();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001350
Misha Brukman37f92e22003-09-11 22:34:13 +00001351 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1352 // a position for such spilled LRs
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001353 allocateStackSpace4SpilledLRs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001354
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001355 // Reset the temp. area on the stack before use by the first instruction.
1356 // This will also happen after updating each instruction.
Brian Gaeke4efe3422003-09-21 01:23:46 +00001357 MF->getInfo()->popAllTempValues();
Ruchira Sasankaf90870f2001-11-15 22:02:06 +00001358
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001359 // color incoming args - if the correct color was not received
1360 // insert code to copy to the correct register
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001361 colorIncomingArgs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001362
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001363 // Save register allocation state for this function in a Constant.
1364 if (SaveRegAllocState)
1365 saveState();
Brian Gaekeaf843702003-10-22 20:22:53 +00001366 if (DEBUG_RA) { // Check our work.
1367 verifySavedState ();
1368 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001369
Brian Gaeke60a3c552003-10-22 20:44:23 +00001370 // Now update the machine code with register names and add any additional
1371 // code inserted by the register allocator to the instruction stream.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001372 updateMachineCode();
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001373
Chris Lattner045e7c82001-09-19 16:26:23 +00001374 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001375 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
Brian Gaeke4efe3422003-09-21 01:23:46 +00001376 MF->dump();
Chris Lattner045e7c82001-09-19 16:26:23 +00001377 }
Brian Gaeke4efe3422003-09-21 01:23:46 +00001378
1379 // Tear down temporary data structures
1380 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1381 delete RegClassList[rc];
1382 RegClassList.clear ();
1383 AddedInstrMap.clear ();
1384 OperandsColoredMap.clear ();
1385 ScratchRegsUsed.clear ();
1386 AddedInstrAtEntry.clear ();
1387 delete LRI;
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001388
Brian Gaeke4efe3422003-09-21 01:23:46 +00001389 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1390 return false; // Function was not modified
1391}
Brian Gaeked0fde302003-11-11 22:41:34 +00001392
1393} // End llvm namespace