blob: 26424ef7e107985fcf207051bc840e2b813bf736 [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"
Brian Gaeke748fba12004-02-24 19:46:00 +000028#include "../LiveVar/FunctionLiveVarInfo.h"
Brian Gaekec9989812004-07-27 17:43:24 +000029#include "../SparcV9InstrInfo.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000030#include "llvm/Constants.h"
31#include "llvm/DerivedTypes.h"
Brian Gaeke25d4b542004-05-30 07:08:43 +000032#include "llvm/iPHINode.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000033#include "llvm/iOther.h"
34#include "llvm/Module.h"
35#include "llvm/Type.h"
36#include "llvm/Analysis/LoopInfo.h"
Chris Lattner797c1362003-09-30 20:13:59 +000037#include "llvm/CodeGen/InstrSelection.h"
Brian Gaeke3ceac852003-10-30 21:21:33 +000038#include "llvm/CodeGen/MachineCodeForInstruction.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000039#include "llvm/CodeGen/MachineFunction.h"
40#include "llvm/CodeGen/MachineFunctionInfo.h"
Brian Gaeke874f4232003-09-21 02:50:21 +000041#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerf6ee49f2003-01-15 18:08:07 +000042#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner08d49632004-02-29 19:12:51 +000043#include "../MachineInstrAnnot.h"
Chris Lattner797c1362003-09-30 20:13:59 +000044#include "llvm/CodeGen/Passes.h"
Chris Lattner797c1362003-09-30 20:13:59 +000045#include "llvm/Support/InstIterator.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000046#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner4bc23482002-09-15 07:07:55 +000047#include "Support/CommandLine.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000048#include "Support/SetOperations.h"
49#include "Support/STLExtras.h"
Brian Gaekebd353fb2003-09-21 03:57:37 +000050#include <cmath>
Reid Spencer954da372004-07-04 12:19:56 +000051#include <iostream>
Vikram S. Adve12af1642001-11-08 04:48:50 +000052
Brian Gaeked0fde302003-11-11 22:41:34 +000053namespace llvm {
54
Chris Lattner70e60cb2002-05-22 17:08:27 +000055RegAllocDebugLevel_t DEBUG_RA;
Vikram S. Adve39c94e12002-09-14 23:05:33 +000056
Chris Lattner5ff62e92002-07-22 02:10:13 +000057static cl::opt<RegAllocDebugLevel_t, true>
58DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
59 cl::desc("enable register allocation debugging information"),
60 cl::values(
Vikram S. Adve39c94e12002-09-14 23:05:33 +000061 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
62 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
63 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
64 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
65 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
66 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
Chris Lattner4d143ee2004-07-16 00:08:28 +000067 clEnumValEnd));
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000068
Brian Gaeked1b36792004-03-10 22:21:03 +000069/// The reoptimizer wants to be able to grovel through the register
70/// allocator's state after it has done its job. This is a hack.
71///
72PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
73bool SaveRegAllocState = false;
74bool SaveStateToModule = true;
75static cl::opt<bool, true>
76SaveRegAllocStateOpt("save-ra-state", cl::Hidden,
77 cl::location (SaveRegAllocState),
78 cl::init(false),
Brian Gaeke59b1c562003-09-24 17:50:28 +000079 cl::desc("write reg. allocator state into module"));
80
Brian Gaekebf3c4cf2003-08-14 06:09:32 +000081FunctionPass *getRegisterAllocator(TargetMachine &T) {
Brian Gaeke4efe3422003-09-21 01:23:46 +000082 return new PhyRegAlloc (T);
Chris Lattner2f9b28e2002-02-04 15:54:09 +000083}
Chris Lattner6dd98a62002-02-04 00:33:08 +000084
Chris Lattner8474f6f2003-09-23 15:13:04 +000085void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired<LoopInfo> ();
87 AU.addRequired<FunctionLiveVarInfo> ();
88}
89
90
Brian Gaekeaf843702003-10-22 20:22:53 +000091/// Initialize interference graphs (one in each reg class) and IGNodeLists
92/// (one in each IG). The actual nodes will be pushed later.
93///
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000094void PhyRegAlloc::createIGNodeListsAndIGs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +000095 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000096
Brian Gaeke4efe3422003-09-21 01:23:46 +000097 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
Brian Gaeke4efe3422003-09-21 01:23:46 +000098 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000099
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000100 for (; HMI != HMIEnd ; ++HMI ) {
101 if (HMI->first) {
102 LiveRange *L = HMI->second; // get the LiveRange
103 if (!L) {
Brian Gaekeeb8863d2004-03-29 21:58:41 +0000104 if (DEBUG_RA && !isa<ConstantIntegral> (HMI->first))
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000105 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000106 << RAV(HMI->first) << "****\n";
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000107 continue;
108 }
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000109
110 // if the Value * is not null, and LR is not yet written to the IGNodeList
Chris Lattner7e708292002-06-25 16:13:24 +0000111 if (!(L->getUserIGNode()) ) {
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000112 RegClass *const RC = // RegClass of first value in the LR
Brian Gaeke59b1c562003-09-24 17:50:28 +0000113 RegClassList[ L->getRegClassID() ];
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000114 RC->addLRToIG(L); // add this LR to an IG
115 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000116 }
117 }
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000118
119 // init RegClassList
Chris Lattner7e708292002-06-25 16:13:24 +0000120 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000121 RegClassList[rc]->createInterferenceGraph();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000122
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000123 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000124}
125
126
Brian Gaekeaf843702003-10-22 20:22:53 +0000127/// Add all interferences for a given instruction. Interference occurs only
128/// if the LR of Def (Inst or Arg) is of the same reg class as that of live
129/// var. The live var passed to this function is the LVset AFTER the
130/// instruction.
131///
132void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
Chris Lattner296b7732002-02-05 02:52:05 +0000133 bool isCallInst) {
Chris Lattner296b7732002-02-05 02:52:05 +0000134 ValueSet::const_iterator LIt = LVSet->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000135
136 // get the live range of instruction
Brian Gaeke4efe3422003-09-21 01:23:46 +0000137 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000138
139 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
140 assert( IGNodeOfDef );
141
142 RegClass *const RCOfDef = LROfDef->getRegClass();
143
144 // for each live var in live variable set
Chris Lattner7e708292002-06-25 16:13:24 +0000145 for ( ; LIt != LVSet->end(); ++LIt) {
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000146
Vikram S. Advef5af6362002-07-08 23:15:32 +0000147 if (DEBUG_RA >= RA_DEBUG_Verbose)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000148 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000149
150 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000151 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000152
153 // LROfVar can be null if it is a const since a const
154 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000155 if (LROfVar)
156 if (LROfDef != LROfVar) // do not set interf for same LR
157 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
158 RCOfDef->setInterference( LROfDef, LROfVar);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000159 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000160}
161
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000162
Brian Gaekeaf843702003-10-22 20:22:53 +0000163/// For a call instruction, this method sets the CallInterference flag in
164/// the LR of each variable live in the Live Variable Set live after the
165/// call instruction (except the return value of the call instruction - since
166/// the return value does not interfere with that call itself).
167///
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000168void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
Chris Lattner296b7732002-02-05 02:52:05 +0000169 const ValueSet *LVSetAft) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000170 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000171 std::cerr << "\n For call inst: " << *MInst;
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000172
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000173 // for each live var in live variable set after machine inst
Vikram S. Adve65b2f402003-07-02 01:24:00 +0000174 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
175 LIt != LEnd; ++LIt) {
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000176
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000177 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000178 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000179
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000180 // LR can be null if it is a const since a const
181 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000182 if (LR ) {
183 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000184 std::cerr << "\n\tLR after Call: ";
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000185 printSet(*LR);
186 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000187 LR->setCallInterference();
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000188 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000189 std::cerr << "\n ++After adding call interference for LR: " ;
Chris Lattner296b7732002-02-05 02:52:05 +0000190 printSet(*LR);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000191 }
192 }
193
194 }
195
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000196 // Now find the LR of the return value of the call
197 // We do this because, we look at the LV set *after* the instruction
198 // to determine, which LRs must be saved across calls. The return value
199 // of the call is live in this set - but it does not interfere with call
200 // (i.e., we can allocate a volatile register to the return value)
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000201 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
202
203 if (const Value *RetVal = argDesc->getReturnValue()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000204 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000205 assert( RetValLR && "No LR for RetValue of call");
206 RetValLR->clearCallInterference();
207 }
208
209 // If the CALL is an indirect call, find the LR of the function pointer.
210 // That has a call interference because it conflicts with outgoing args.
Chris Lattner7e708292002-06-25 16:13:24 +0000211 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000212 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000213 assert( AddrValLR && "No LR for indirect addr val of call");
214 AddrValLR->setCallInterference();
215 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000216}
217
218
Brian Gaekeaf843702003-10-22 20:22:53 +0000219/// Create interferences in the IG of each RegClass, and calculate the spill
220/// cost of each Live Range (it is done in this method to save another pass
221/// over the code).
222///
223void PhyRegAlloc::buildInterferenceGraphs() {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000224 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000225 std::cerr << "Creating interference graphs ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000226
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000227 unsigned BBLoopDepthCost;
Brian Gaeke4efe3422003-09-21 01:23:46 +0000228 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000229 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000230 const MachineBasicBlock &MBB = *BBI;
231 const BasicBlock *BB = MBB.getBasicBlock();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000232
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000233 // find the 10^(loop_depth) of this BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000234 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000235
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000236 // get the iterator for machine instructions
Chris Lattnerf726e772002-10-28 19:22:04 +0000237 MachineBasicBlock::const_iterator MII = MBB.begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000238
239 // iterate over all the machine instructions in BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000240 for ( ; MII != MBB.end(); ++MII) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000241 const MachineInstr *MInst = MII;
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000242
243 // get the LV set after the instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000244 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
Chris Lattnerd029cd22004-06-02 05:55:25 +0000245 bool isCallInst = TM.getInstrInfo()->isCall(MInst->getOpcode());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000246
Brian Gaekeaf843702003-10-22 20:22:53 +0000247 if (isCallInst) {
Misha Brukman37f92e22003-09-11 22:34:13 +0000248 // set the isCallInterference flag of each live range which extends
249 // across this call instruction. This information is used by graph
250 // coloring algorithm to avoid allocating volatile colors to live ranges
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000251 // that span across calls (since they have to be saved/restored)
Chris Lattner748697d2002-02-05 04:20:12 +0000252 setCallInterferences(MInst, &LVSetAI);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000253 }
254
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000255 // iterate over all MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000256 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
257 OpE = MInst->end(); OpI != OpE; ++OpI) {
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000258 if (OpI.isDef()) // create a new LR since def
Chris Lattner748697d2002-02-05 04:20:12 +0000259 addInterference(*OpI, &LVSetAI, isCallInst);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000260
261 // Calculate the spill cost of each live range
Brian Gaeke4efe3422003-09-21 01:23:46 +0000262 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
Chris Lattner2f898d22002-02-05 06:02:59 +0000263 if (LR) LR->addSpillCost(BBLoopDepthCost);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000264 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000265
Brian Gaekeaf843702003-10-22 20:22:53 +0000266 // Mark all operands of pseudo-instructions as interfering with one
267 // another. This must be done because pseudo-instructions may be
268 // expanded to multiple instructions by the assembler, so all the
269 // operands must get distinct registers.
Chris Lattnerd029cd22004-06-02 05:55:25 +0000270 if (TM.getInstrInfo()->isPseudoInstr(MInst->getOpcode()))
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000271 addInterf4PseudoInstr(MInst);
272
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000273 // Also add interference for any implicit definitions in a machine
274 // instr (currently, only calls have this).
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000275 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000276 for (unsigned z=0; z < NumOfImpRefs; z++)
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000277 if (MInst->getImplicitOp(z).isDef())
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000278 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +0000279
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000280 } // for all machine instructions in BB
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000281 } // for all BBs in function
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000282
Misha Brukman37f92e22003-09-11 22:34:13 +0000283 // add interferences for function arguments. Since there are no explicit
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000284 // defs in the function for args, we have to add them manually
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000285 addInterferencesForArgs();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000286
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000287 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000288 std::cerr << "Interference graphs calculated!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000289}
290
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000291
Brian Gaekeaf843702003-10-22 20:22:53 +0000292/// Mark all operands of the given MachineInstr as interfering with one
293/// another.
294///
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000295void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000296 bool setInterf = false;
297
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000298 // iterate over MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000299 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
300 ItE = MInst->end(); It1 != ItE; ++It1) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000301 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000302 assert((LROfOp1 || It1.isDef()) && "No LR for Def in PSEUDO insruction");
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000303
Chris Lattner2f898d22002-02-05 06:02:59 +0000304 MachineInstr::const_val_op_iterator It2 = It1;
Chris Lattner7e708292002-06-25 16:13:24 +0000305 for (++It2; It2 != ItE; ++It2) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000306 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000307
Chris Lattner2f898d22002-02-05 06:02:59 +0000308 if (LROfOp2) {
309 RegClass *RCOfOp1 = LROfOp1->getRegClass();
310 RegClass *RCOfOp2 = LROfOp2->getRegClass();
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000311
Chris Lattner7e708292002-06-25 16:13:24 +0000312 if (RCOfOp1 == RCOfOp2 ){
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000313 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000314 setInterf = true;
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000315 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000316 } // if Op2 has a LR
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000317 } // for all other defs in machine instr
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000318 } // for all operands in an instruction
319
Chris Lattner2f898d22002-02-05 06:02:59 +0000320 if (!setInterf && MInst->getNumOperands() > 2) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000321 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
322 std::cerr << *MInst;
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000323 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000324 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000325}
326
327
Brian Gaekeaf843702003-10-22 20:22:53 +0000328/// Add interferences for incoming arguments to a function.
329///
Chris Lattner296b7732002-02-05 02:52:05 +0000330void PhyRegAlloc::addInterferencesForArgs() {
331 // get the InSet of root BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000332 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000333
Chris Lattnerf726e772002-10-28 19:22:04 +0000334 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000335 // add interferences between args and LVars at start
336 addInterference(AI, &InSet, false);
337
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000338 if (DEBUG_RA >= RA_DEBUG_Interference)
Brian Gaekeaf843702003-10-22 20:22:53 +0000339 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000340 }
341}
342
343
Brian Gaekeaf843702003-10-22 20:22:53 +0000344/// The following are utility functions used solely by updateMachineCode and
345/// the functions that it calls. They should probably be folded back into
346/// updateMachineCode at some point.
347///
Vikram S. Adve48762092002-04-25 04:34:15 +0000348
Brian Gaekeaf843702003-10-22 20:22:53 +0000349// used by: updateMachineCode (1 time), PrependInstructions (1 time)
350inline void InsertBefore(MachineInstr* newMI, MachineBasicBlock& MBB,
351 MachineBasicBlock::iterator& MII) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000352 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000353 ++MII;
354}
355
Brian Gaekeaf843702003-10-22 20:22:53 +0000356// used by: AppendInstructions (1 time)
357inline void InsertAfter(MachineInstr* newMI, MachineBasicBlock& MBB,
358 MachineBasicBlock::iterator& MII) {
Vikram S. Advecb202e32002-10-11 16:12:40 +0000359 ++MII; // insert before the next instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000360 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000361}
362
Brian Gaekeaf843702003-10-22 20:22:53 +0000363// used by: updateMachineCode (2 times)
364inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
365 MachineBasicBlock& MBB,
366 MachineBasicBlock::iterator& MII,
367 const std::string& msg) {
368 if (!IBef.empty()) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000369 MachineInstr* OrigMI = MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000370 std::vector<MachineInstr *>::iterator AdIt;
Brian Gaekeaf843702003-10-22 20:22:53 +0000371 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000372 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000373 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
374 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000375 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000376 InsertBefore(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000377 }
378 }
379}
380
Brian Gaekeaf843702003-10-22 20:22:53 +0000381// used by: updateMachineCode (1 time)
382inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
383 MachineBasicBlock& MBB,
384 MachineBasicBlock::iterator& MII,
385 const std::string& msg) {
386 if (!IAft.empty()) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000387 MachineInstr* OrigMI = MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000388 std::vector<MachineInstr *>::iterator AdIt;
Brian Gaekeaf843702003-10-22 20:22:53 +0000389 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
Chris Lattner7e708292002-06-25 16:13:24 +0000390 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000391 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
392 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000393 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000394 InsertAfter(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000395 }
396 }
397}
398
Brian Gaekeaf843702003-10-22 20:22:53 +0000399/// Set the registers for operands in the given MachineInstr, if a register was
400/// successfully allocated. Return true if any of its operands has been marked
401/// for spill.
402///
Brian Gaeke4efe3422003-09-21 01:23:46 +0000403bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000404{
Vikram S. Adve814030a2003-07-29 19:49:21 +0000405 bool instrNeedsSpills = false;
406
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000407 // First, set the registers for operands in the machine instruction
408 // if a register was successfully allocated. Do this first because we
409 // will need to know which registers are already used by this instr'n.
Brian Gaekeaf843702003-10-22 20:22:53 +0000410 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000411 MachineOperand& Op = MInst->getOperand(OpNum);
412 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
Brian Gaekeaf843702003-10-22 20:22:53 +0000413 Op.getType() == MachineOperand::MO_CCRegister) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000414 const Value *const Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000415 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000416 // Remember if any operand needs spilling
417 instrNeedsSpills |= LR->isMarkedForSpill();
418
419 // An operand may have a color whether or not it needs spilling
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000420 if (LR->hasColor())
421 MInst->SetRegForOperand(OpNum,
Brian Gaeke59b1c562003-09-24 17:50:28 +0000422 MRI.getUnifiedRegNum(LR->getRegClassID(),
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000423 LR->getColor()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000424 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000425 }
426 } // for each operand
Vikram S. Adve814030a2003-07-29 19:49:21 +0000427
428 return instrNeedsSpills;
429}
430
Brian Gaekeaf843702003-10-22 20:22:53 +0000431/// Mark allocated registers (using markAllocatedRegs()) on the instruction
432/// that MII points to. Then, if it's a call instruction, insert caller-saving
433/// code before and after it. Finally, insert spill code before and after it,
434/// using insertCode4SpilledLR().
435///
Vikram S. Adve814030a2003-07-29 19:49:21 +0000436void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
Brian Gaekeaf843702003-10-22 20:22:53 +0000437 MachineBasicBlock &MBB) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000438 MachineInstr* MInst = MII;
Brian Gaeke12c1d2c2004-02-11 20:47:34 +0000439 unsigned Opcode = MInst->getOpcode();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000440
441 // Reset tmp stack positions so they can be reused for each machine instr.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000442 MF->getInfo()->popAllTempValues();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000443
444 // Mark the operands for which regs have been allocated.
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000445 bool instrNeedsSpills = markAllocatedRegs(MII);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000446
447#ifndef NDEBUG
448 // Mark that the operands have been updated. Later,
449 // setRelRegsUsedByThisInst() is called to find registers used by each
450 // MachineInst, and it should not be used for an instruction until
451 // this is done. This flag just serves as a sanity check.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000452 OperandsColoredMap[MInst] = true;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000453#endif
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000454
Vikram S. Advebc001b22003-07-25 21:06:09 +0000455 // Now insert caller-saving code before/after the call.
456 // Do this before inserting spill code since some registers must be
457 // used by save/restore and spill code should not use those registers.
Chris Lattnerd029cd22004-06-02 05:55:25 +0000458 if (TM.getInstrInfo()->isCall(Opcode)) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000459 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Adve814030a2003-07-29 19:49:21 +0000460 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
461 MBB.getBasicBlock());
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000462 }
Vikram S. Advebc001b22003-07-25 21:06:09 +0000463
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000464 // Now insert spill code for remaining operands not allocated to
465 // registers. This must be done even for call return instructions
466 // since those are not handled by the special code above.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000467 if (instrNeedsSpills)
Brian Gaekeaf843702003-10-22 20:22:53 +0000468 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000469 MachineOperand& Op = MInst->getOperand(OpNum);
470 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
Brian Gaekeaf843702003-10-22 20:22:53 +0000471 Op.getType() == MachineOperand::MO_CCRegister) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000472 const Value* Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000473 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000474 if (LR->isMarkedForSpill())
475 insertCode4SpilledLR(LR, MII, MBB, OpNum);
476 }
477 } // for each operand
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000478}
479
Brian Gaekeaf843702003-10-22 20:22:53 +0000480/// Iterate over all the MachineBasicBlocks in the current function and set
481/// the allocated registers for each instruction (using updateInstruction()),
482/// after register allocation is complete. Then move code out of delay slots.
483///
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000484void PhyRegAlloc::updateMachineCode()
485{
Chris Lattner7e708292002-06-25 16:13:24 +0000486 // Insert any instructions needed at method entry
Brian Gaeke4efe3422003-09-21 01:23:46 +0000487 MachineBasicBlock::iterator MII = MF->front().begin();
488 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
Chris Lattner7e708292002-06-25 16:13:24 +0000489 "At function entry: \n");
490 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
491 "InstrsAfter should be unnecessary since we are just inserting at "
492 "the function entry point here.");
Vikram S. Adve48762092002-04-25 04:34:15 +0000493
Brian Gaeke4efe3422003-09-21 01:23:46 +0000494 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000495 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000496 MachineBasicBlock &MBB = *BBI;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000497
498 // Iterate over all machine instructions in BB and mark operands with
499 // their assigned registers or insert spill code, as appropriate.
500 // Also, fix operands of call/return instructions.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000501 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
Chris Lattnerd029cd22004-06-02 05:55:25 +0000502 if (! TM.getInstrInfo()->isDummyPhiInstr(MII->getOpcode()))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000503 updateInstruction(MII, MBB);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000504
505 // Now, move code out of delay slots of branches and returns if needed.
506 // (Also, move "after" code from calls to the last delay slot instruction.)
507 // Moving code out of delay slots is needed in 2 situations:
508 // (1) If this is a branch and it needs instructions inserted after it,
509 // move any existing instructions out of the delay slot so that the
510 // instructions can go into the delay slot. This only supports the
511 // case that #instrsAfter <= #delay slots.
512 //
513 // (2) If any instruction in the delay slot needs
514 // instructions inserted, move it out of the delay slot and before the
515 // branch because putting code before or after it would be VERY BAD!
516 //
517 // If the annul bit of the branch is set, neither of these is legal!
518 // If so, we need to handle spill differently but annulling is not yet used.
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000519 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000520 if (unsigned delaySlots =
Chris Lattnerd029cd22004-06-02 05:55:25 +0000521 TM.getInstrInfo()->getNumDelaySlots(MII->getOpcode())) {
Alkis Evlogimenosf81af212004-02-14 01:18:34 +0000522 MachineBasicBlock::iterator DelaySlotMI = next(MII);
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000523 assert(DelaySlotMI != MBB.end() && "no instruction for delay slot");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000524
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000525 // Check the 2 conditions above:
526 // (1) Does a branch need instructions added after it?
527 // (2) O/w does delay slot instr. need instrns before or after?
Chris Lattnerd029cd22004-06-02 05:55:25 +0000528 bool isBranch = (TM.getInstrInfo()->isBranch(MII->getOpcode()) ||
529 TM.getInstrInfo()->isReturn(MII->getOpcode()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000530 bool cond1 = (isBranch &&
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000531 AddedInstrMap.count(MII) &&
532 AddedInstrMap[MII].InstrnsAfter.size() > 0);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000533 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
534 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
535 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000536
Brian Gaekeaf843702003-10-22 20:22:53 +0000537 if (cond1 || cond2) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000538 assert(delaySlots==1 &&
539 "InsertBefore does not yet handle >1 delay slots!");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000540
541 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000542 std::cerr << "\nRegAlloc: Moved instr. with added code: "
Vikram S. Adve814030a2003-07-29 19:49:21 +0000543 << *DelaySlotMI
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000544 << " out of delay slots of instr: " << *MII;
545 }
546
547 // move instruction before branch
Chris Lattnerb4186e02004-03-31 21:59:59 +0000548 MBB.insert(MII, MBB.remove(DelaySlotMI++));
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000549
550 // On cond1 we are done (we already moved the
551 // instruction out of the delay slot). On cond2 we need
552 // to insert a nop in place of the moved instruction
553 if (cond2) {
Brian Gaekec9989812004-07-27 17:43:24 +0000554 MBB.insert(MII, BuildMI(V9::NOP, 1));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000555 }
556 }
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000557 else {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000558 // For non-branch instr with delay slots (probably a call), move
559 // InstrAfter to the instr. in the last delay slot.
Alkis Evlogimenosf81af212004-02-14 01:18:34 +0000560 MachineBasicBlock::iterator tmp = next(MII, delaySlots);
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000561 move2DelayedInstr(MII, tmp);
562 }
563 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000564
565 // Finally iterate over all instructions in BB and insert before/after
Vikram S. Advebc001b22003-07-25 21:06:09 +0000566 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000567 MachineInstr *MInst = MII;
Vikram S. Advebc001b22003-07-25 21:06:09 +0000568
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000569 // do not process Phis
Chris Lattnerd029cd22004-06-02 05:55:25 +0000570 if (TM.getInstrInfo()->isDummyPhiInstr(MInst->getOpcode()))
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000571 continue;
572
Vikram S. Advebc001b22003-07-25 21:06:09 +0000573 // if there are any added instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000574 if (AddedInstrMap.count(MInst)) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000575 AddedInstrns &CallAI = AddedInstrMap[MInst];
576
577#ifndef NDEBUG
Chris Lattnerd029cd22004-06-02 05:55:25 +0000578 bool isBranch = (TM.getInstrInfo()->isBranch(MInst->getOpcode()) ||
579 TM.getInstrInfo()->isReturn(MInst->getOpcode()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000580 assert((!isBranch ||
581 AddedInstrMap[MInst].InstrnsAfter.size() <=
Chris Lattnerd029cd22004-06-02 05:55:25 +0000582 TM.getInstrInfo()->getNumDelaySlots(MInst->getOpcode())) &&
Vikram S. Adve814030a2003-07-29 19:49:21 +0000583 "Cannot put more than #delaySlots instrns after "
584 "branch or return! Need to handle temps differently.");
585#endif
586
587#ifndef NDEBUG
Vikram S. Advebc001b22003-07-25 21:06:09 +0000588 // Temporary sanity checking code to detect whether the same machine
589 // instruction is ever inserted twice before/after a call.
590 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000591 std::set<const MachineInstr*> instrsSeen;
592 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
593 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
594 "Duplicate machine instruction in InstrnsBefore!");
595 instrsSeen.insert(CallAI.InstrnsBefore[i]);
596 }
597 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
598 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
599 "Duplicate machine instruction in InstrnsBefore/After!");
600 instrsSeen.insert(CallAI.InstrnsAfter[i]);
601 }
602#endif
603
604 // Now add the instructions before/after this MI.
605 // We do this here to ensure that spill for an instruction is inserted
606 // as close as possible to an instruction (see above insertCode4Spill)
Vikram S. Advebc001b22003-07-25 21:06:09 +0000607 if (! CallAI.InstrnsBefore.empty())
608 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
609
610 if (! CallAI.InstrnsAfter.empty())
611 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
612
613 } // if there are any added instructions
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000614 } // for each machine instruction
Ruchira Sasanka0931a012001-09-15 19:06:58 +0000615 }
616}
617
618
Brian Gaekeaf843702003-10-22 20:22:53 +0000619/// Insert spill code for AN operand whose LR was spilled. May be called
620/// repeatedly for a single MachineInstr if it has many spilled operands. On
621/// each call, it finds a register which is not live at that instruction and
622/// also which is not used by other spilled operands of the same
623/// instruction. Then it uses this register temporarily to accommodate the
624/// spilled value.
625///
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000626void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000627 MachineBasicBlock::iterator& MII,
628 MachineBasicBlock &MBB,
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000629 const unsigned OpNum) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000630 MachineInstr *MInst = MII;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000631 const BasicBlock *BB = MBB.getBasicBlock();
632
Chris Lattnerd029cd22004-06-02 05:55:25 +0000633 assert((! TM.getInstrInfo()->isCall(MInst->getOpcode()) || OpNum == 0) &&
Vikram S. Advead9c9782002-09-28 17:02:40 +0000634 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
Chris Lattnerd029cd22004-06-02 05:55:25 +0000635 assert(! TM.getInstrInfo()->isReturn(MInst->getOpcode()) &&
Vikram S. Advead9c9782002-09-28 17:02:40 +0000636 "Return value of a ret must be handled elsewhere");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000637
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000638 MachineOperand& Op = MInst->getOperand(OpNum);
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000639 bool isDef = Op.isDef();
640 bool isUse = Op.isUse();
Vikram S. Advebc001b22003-07-25 21:06:09 +0000641 unsigned RegType = MRI.getRegTypeForLR(LR);
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000642 int SpillOff = LR->getSpillOffFromFP();
643 RegClass *RC = LR->getRegClass();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000644
645 // Get the live-variable set to find registers free before this instr.
Vikram S. Advefeb32982003-08-12 22:22:24 +0000646 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
647
648#ifndef NDEBUG
649 // If this instr. is in the delay slot of a branch or return, we need to
650 // include all live variables before that branch or return -- we don't want to
651 // trample those! Verify that the set is included in the LV set before MInst.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000652 if (MII != MBB.begin()) {
Alkis Evlogimenosf81af212004-02-14 01:18:34 +0000653 MachineBasicBlock::iterator PredMI = prior(MII);
Chris Lattnerd029cd22004-06-02 05:55:25 +0000654 if (unsigned DS = TM.getInstrInfo()->getNumDelaySlots(PredMI->getOpcode()))
Vikram S. Advefeb32982003-08-12 22:22:24 +0000655 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
656 .empty() && "Live-var set before branch should be included in "
657 "live-var set of each delay slot instruction!");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000658 }
Vikram S. Advefeb32982003-08-12 22:22:24 +0000659#endif
Vikram S. Adve00521d72001-11-12 23:26:35 +0000660
Brian Gaekeaf843702003-10-22 20:22:53 +0000661 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000662
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000663 std::vector<MachineInstr*> MIBef, MIAft;
664 std::vector<MachineInstr*> AdIMid;
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000665
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000666 // Choose a register to hold the spilled value, if one was not preallocated.
667 // This may insert code before and after MInst to free up the value. If so,
668 // this code should be first/last in the spill sequence before/after MInst.
669 int TmpRegU=(LR->hasColor()
Brian Gaeke59b1c562003-09-24 17:50:28 +0000670 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000671 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000672
Vikram S. Advef5af6362002-07-08 23:15:32 +0000673 // Set the operand first so that it this register does not get used
674 // as a scratch register for later calls to getUsableUniRegAtMI below
675 MInst->SetRegForOperand(OpNum, TmpRegU);
676
677 // get the added instructions for this instruction
Chris Lattner0b0ffa02002-04-09 05:13:04 +0000678 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Advef5af6362002-07-08 23:15:32 +0000679
680 // We may need a scratch register to copy the spilled value to/from memory.
681 // This may itself have to insert code to free up a scratch register.
682 // Any such code should go before (after) the spill code for a load (store).
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000683 // The scratch reg is not marked as used because it is only used
684 // for the copy and not used across MInst.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000685 int scratchRegType = -1;
686 int scratchReg = -1;
Brian Gaekeaf843702003-10-22 20:22:53 +0000687 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
Chris Lattner27a08932002-10-22 23:16:21 +0000688 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
689 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000690 assert(scratchReg != MRI.getInvalidRegNum());
Vikram S. Advef5af6362002-07-08 23:15:32 +0000691 }
692
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000693 if (isUse) {
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000694 // for a USE, we have to load the value of LR from stack to a TmpReg
695 // and use the TmpReg as one operand of instruction
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000696
Vikram S. Advef5af6362002-07-08 23:15:32 +0000697 // actual loading instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000698 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
699 RegType, scratchReg);
Ruchira Sasanka226f1f02001-11-08 19:11:30 +0000700
Vikram S. Advef5af6362002-07-08 23:15:32 +0000701 // the actual load should be after the instructions to free up TmpRegU
702 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
703 AdIMid.clear();
704 }
705
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000706 if (isDef) { // if this is a Def
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000707 // for a DEF, we have to store the value produced by this instruction
708 // on the stack position allocated for this LR
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000709
Vikram S. Advef5af6362002-07-08 23:15:32 +0000710 // actual storing instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000711 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
712 RegType, scratchReg);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000713
Vikram S. Advef5af6362002-07-08 23:15:32 +0000714 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000715 } // if !DEF
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000716
Vikram S. Advef5af6362002-07-08 23:15:32 +0000717 // Finally, insert the entire spill code sequences before/after MInst
718 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
719 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
720
Chris Lattner7e708292002-06-25 16:13:24 +0000721 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000722 std::cerr << "\nFor Inst:\n " << *MInst;
723 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
724 std::cerr << "; added Instructions:";
Anand Shuklad58290e2002-07-09 19:18:56 +0000725 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
726 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
Chris Lattner7e708292002-06-25 16:13:24 +0000727 }
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000728}
729
730
Brian Gaekeaf843702003-10-22 20:22:53 +0000731/// Insert caller saving/restoring instructions before/after a call machine
732/// instruction (before or after any other instructions that were inserted for
733/// the call).
734///
Vikram S. Adve814030a2003-07-29 19:49:21 +0000735void
736PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
737 std::vector<MachineInstr*> &instrnsAfter,
738 MachineInstr *CallMI,
Brian Gaekeaf843702003-10-22 20:22:53 +0000739 const BasicBlock *BB) {
Chris Lattnerd029cd22004-06-02 05:55:25 +0000740 assert(TM.getInstrInfo()->isCall(CallMI->getOpcode()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000741
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000742 // hash set to record which registers were saved/restored
Vikram S. Adve814030a2003-07-29 19:49:21 +0000743 hash_set<unsigned> PushedRegSet;
744
745 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
746
747 // if the call is to a instrumentation function, do not insert save and
748 // restore instructions the instrumentation function takes care of save
749 // restore for volatile regs.
750 //
751 // FIXME: this should be made general, not specific to the reoptimizer!
Vikram S. Adve814030a2003-07-29 19:49:21 +0000752 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
753 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
754
755 // Now check if the call has a return value (using argDesc) and if so,
756 // find the LR of the TmpInstruction representing the return value register.
757 // (using the last or second-last *implicit operand* of the call MI).
758 // Insert it to to the PushedRegSet since we must not save that register
759 // and restore it after the call.
760 // We do this because, we look at the LV set *after* the instruction
761 // to determine, which LRs must be saved across calls. The return value
762 // of the call is live in this set - but we must not save/restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000763 if (const Value *origRetVal = argDesc->getReturnValue()) {
764 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
765 (argDesc->getIndirectFuncPtr()? 1 : 2));
766 const TmpInstruction* tmpRetVal =
767 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
768 assert(tmpRetVal->getOperand(0) == origRetVal &&
769 tmpRetVal->getType() == origRetVal->getType() &&
770 "Wrong implicit ref?");
Brian Gaeke4efe3422003-09-21 01:23:46 +0000771 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000772 assert(RetValLR && "No LR for RetValue of call");
773
774 if (! RetValLR->isMarkedForSpill())
775 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
776 RetValLR->getColor()));
777 }
778
779 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
780 ValueSet::const_iterator LIt = LVSetAft.begin();
781
782 // for each live var in live variable set after machine inst
783 for( ; LIt != LVSetAft.end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000784 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000785 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000786
787 // LR can be null if it is a const since a const
788 // doesn't have a dominating def - see Assumptions above
Brian Gaekeaf843702003-10-22 20:22:53 +0000789 if (LR) {
790 if (! LR->isMarkedForSpill()) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000791 assert(LR->hasColor() && "LR is neither spilled nor colored?");
792 unsigned RCID = LR->getRegClassID();
793 unsigned Color = LR->getColor();
794
795 if (MRI.isRegVolatile(RCID, Color) ) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000796 // if this is a call to the first-level reoptimizer
797 // instrumentation entry point, and the register is not
798 // modified by call, don't save and restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000799 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
800 continue;
801
802 // if the value is in both LV sets (i.e., live before and after
803 // the call machine instruction)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000804 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
805
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000806 // if we haven't already pushed this register...
Vikram S. Adve814030a2003-07-29 19:49:21 +0000807 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000808 unsigned RegType = MRI.getRegTypeForLR(LR);
809
810 // Now get two instructions - to push on stack and pop from stack
811 // and add them to InstrnsBefore and InstrnsAfter of the
812 // call instruction
Vikram S. Adve814030a2003-07-29 19:49:21 +0000813 int StackOff =
Brian Gaeke4efe3422003-09-21 01:23:46 +0000814 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000815
816 //---- Insert code for pushing the reg on stack ----------
817
818 std::vector<MachineInstr*> AdIBef, AdIAft;
819
820 // We may need a scratch register to copy the saved value
821 // to/from memory. This may itself have to insert code to
822 // free up a scratch register. Any such code should go before
823 // the save code. The scratch register, if any, is by default
824 // temporary and not "used" by the instruction unless the
825 // copy code itself decides to keep the value in the scratch reg.
826 int scratchRegType = -1;
827 int scratchReg = -1;
828 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
829 { // Find a register not live in the LVSet before CallMI
830 const ValueSet &LVSetBef =
831 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
832 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
833 CallMI, AdIBef, AdIAft);
834 assert(scratchReg != MRI.getInvalidRegNum());
835 }
836
837 if (AdIBef.size() > 0)
838 instrnsBefore.insert(instrnsBefore.end(),
839 AdIBef.begin(), AdIBef.end());
840
841 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
842 StackOff, RegType, scratchReg);
843
844 if (AdIAft.size() > 0)
845 instrnsBefore.insert(instrnsBefore.end(),
846 AdIAft.begin(), AdIAft.end());
847
848 //---- Insert code for popping the reg from the stack ----------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000849 AdIBef.clear();
850 AdIAft.clear();
851
852 // We may need a scratch register to copy the saved value
853 // from memory. This may itself have to insert code to
854 // free up a scratch register. Any such code should go
855 // after the save code. As above, scratch is not marked "used".
Vikram S. Adve814030a2003-07-29 19:49:21 +0000856 scratchRegType = -1;
857 scratchReg = -1;
858 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
859 { // Find a register not live in the LVSet after CallMI
860 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
861 CallMI, AdIBef, AdIAft);
862 assert(scratchReg != MRI.getInvalidRegNum());
863 }
864
865 if (AdIBef.size() > 0)
866 instrnsAfter.insert(instrnsAfter.end(),
867 AdIBef.begin(), AdIBef.end());
868
869 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
870 Reg, RegType, scratchReg);
871
872 if (AdIAft.size() > 0)
873 instrnsAfter.insert(instrnsAfter.end(),
874 AdIAft.begin(), AdIAft.end());
875
876 PushedRegSet.insert(Reg);
877
878 if(DEBUG_RA) {
879 std::cerr << "\nFor call inst:" << *CallMI;
880 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
881 for_each(instrnsBefore.begin(), instrnsBefore.end(),
882 std::mem_fun(&MachineInstr::dump));
883 std::cerr << " -and After:\n\t ";
884 for_each(instrnsAfter.begin(), instrnsAfter.end(),
885 std::mem_fun(&MachineInstr::dump));
886 }
887 } // if not already pushed
Vikram S. Adve814030a2003-07-29 19:49:21 +0000888 } // if LR has a volatile color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000889 } // if LR has color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000890 } // if there is a LR for Var
Vikram S. Adve814030a2003-07-29 19:49:21 +0000891 } // for each value in the LV set after instruction
892}
893
894
Brian Gaekeaf843702003-10-22 20:22:53 +0000895/// Returns the unified register number of a temporary register to be used
896/// BEFORE MInst. If no register is available, it will pick one and modify
897/// MIBef and MIAft to contain instructions used to free up this returned
898/// register.
899///
Vikram S. Advef5af6362002-07-08 23:15:32 +0000900int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
901 const ValueSet *LVSetBef,
902 MachineInstr *MInst,
903 std::vector<MachineInstr*>& MIBef,
904 std::vector<MachineInstr*>& MIAft) {
Chris Lattner133f0792002-10-28 04:45:29 +0000905 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000906
Brian Gaekeaf843702003-10-22 20:22:53 +0000907 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000908
909 if (RegU == -1) {
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000910 // we couldn't find an unused register. Generate code to free up a reg by
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000911 // saving it on stack and restoring after the instruction
Vikram S. Advef5af6362002-07-08 23:15:32 +0000912
Brian Gaeke4efe3422003-09-21 01:23:46 +0000913 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve12af1642001-11-08 04:48:50 +0000914
Vikram S. Advebc001b22003-07-25 21:06:09 +0000915 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000916
Vikram S. Advef5af6362002-07-08 23:15:32 +0000917 // Check if we need a scratch register to copy this register to memory.
918 int scratchRegType = -1;
Brian Gaekeaf843702003-10-22 20:22:53 +0000919 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
Chris Lattner133f0792002-10-28 04:45:29 +0000920 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
921 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000922 assert(scratchReg != MRI.getInvalidRegNum());
923
924 // We may as well hold the value in the scratch register instead
925 // of copying it to memory and back. But we have to mark the
926 // register as used by this instruction, so it does not get used
927 // as a scratch reg. by another operand or anyone else.
Chris Lattner3fd1f5b2003-08-05 22:11:13 +0000928 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000929 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
930 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
Brian Gaekeaf843702003-10-22 20:22:53 +0000931 } else { // the register can be copied directly to/from memory so do it.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000932 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
933 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
Brian Gaekeaf843702003-10-22 20:22:53 +0000934 }
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000935 }
Vikram S. Advef5af6362002-07-08 23:15:32 +0000936
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000937 return RegU;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000938}
939
Vikram S. Adve814030a2003-07-29 19:49:21 +0000940
Brian Gaekeaf843702003-10-22 20:22:53 +0000941/// Returns the register-class register number of a new unused register that
942/// can be used to accommodate a temporary value. May be called repeatedly
943/// for a single MachineInstr. On each call, it finds a register which is not
944/// live at that instruction and which is not used by any spilled operands of
945/// that instruction.
946///
947int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000948 const MachineInstr *MInst,
949 const ValueSet* LVSetBef) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000950 RC->clearColorsUsed(); // Reset array
Vikram S. Adve814030a2003-07-29 19:49:21 +0000951
952 if (LVSetBef == NULL) {
953 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
954 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
955 }
956
Chris Lattner296b7732002-02-05 02:52:05 +0000957 ValueSet::const_iterator LIt = LVSetBef->begin();
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000958
959 // for each live var in live variable set after machine inst
Chris Lattner7e708292002-06-25 16:13:24 +0000960 for ( ; LIt != LVSetBef->end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000961 // Get the live range corresponding to live var, and its RegClass
Brian Gaeke4efe3422003-09-21 01:23:46 +0000962 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000963
964 // LR can be null if it is a const since a const
965 // doesn't have a dominating def - see Assumptions above
Vikram S. Advebc001b22003-07-25 21:06:09 +0000966 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
967 RC->markColorsUsed(LRofLV->getColor(),
968 MRI.getRegTypeForLR(LRofLV), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000969 }
970
971 // It is possible that one operand of this MInst was already spilled
972 // and it received some register temporarily. If that's the case,
973 // it is recorded in machine operand. We must skip such registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000974 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000975
Vikram S. Advebc001b22003-07-25 21:06:09 +0000976 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
977 if (unusedReg >= 0)
978 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
979
Chris Lattner85c54652002-05-23 15:50:03 +0000980 return -1;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000981}
982
983
Brian Gaekeaf843702003-10-22 20:22:53 +0000984/// Return the unified register number of a register in class RC which is not
985/// used by any operands of MInst.
986///
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000987int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +0000988 const int RegType,
Chris Lattner85c54652002-05-23 15:50:03 +0000989 const MachineInstr *MInst) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000990 RC->clearColorsUsed();
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000991
Vikram S. Advebc001b22003-07-25 21:06:09 +0000992 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000993
Vikram S. Advebc001b22003-07-25 21:06:09 +0000994 // find the first unused color
995 int unusedReg = RC->getUnusedColor(RegType);
996 assert(unusedReg >= 0 &&
997 "FATAL: No free register could be found in reg class!!");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000998
Vikram S. Advebc001b22003-07-25 21:06:09 +0000999 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001000}
1001
1002
Brian Gaekeaf843702003-10-22 20:22:53 +00001003/// Modify the IsColorUsedArr of register class RC, by setting the bits
1004/// corresponding to register RegNo. This is a helper method of
1005/// setRelRegsUsedByThisInst().
1006///
Chris Lattner3bed95b2003-08-05 21:55:58 +00001007static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
Brian Gaeke498231b2004-06-03 02:45:09 +00001008 const SparcV9RegInfo &TRI) {
Chris Lattner3bed95b2003-08-05 21:55:58 +00001009 unsigned classId = 0;
1010 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1011 if (RC->getID() == classId)
1012 RC->markColorsUsed(classRegNum, RegType, RegType);
1013}
1014
1015void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
Brian Gaekeaf843702003-10-22 20:22:53 +00001016 const MachineInstr *MI) {
Chris Lattner3bed95b2003-08-05 21:55:58 +00001017 assert(OperandsColoredMap[MI] == true &&
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001018 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1019 "are marked for an instruction.");
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001020
Brian Gaekeaf843702003-10-22 20:22:53 +00001021 // Add the registers already marked as used by the instruction. Both
1022 // explicit and implicit operands are set.
Chris Lattner3bed95b2003-08-05 21:55:58 +00001023 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1024 if (MI->getOperand(i).hasAllocatedReg())
Alkis Evlogimenosbe766c72004-02-13 21:01:20 +00001025 markRegisterUsed(MI->getOperand(i).getReg(), RC, RegType,MRI);
Chris Lattner3bed95b2003-08-05 21:55:58 +00001026
1027 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1028 if (MI->getImplicitOp(i).hasAllocatedReg())
Alkis Evlogimenosbe766c72004-02-13 21:01:20 +00001029 markRegisterUsed(MI->getImplicitOp(i).getReg(), RC, RegType,MRI);
Chris Lattner3bed95b2003-08-05 21:55:58 +00001030
Chris Lattner3fd1f5b2003-08-05 22:11:13 +00001031 // Add all of the scratch registers that are used to save values across the
1032 // instruction (e.g., for saving state register values).
1033 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1034 IR = ScratchRegsUsed.equal_range(MI);
1035 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1036 markRegisterUsed(I->second, RC, RegType, MRI);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001037
Vikram S. Advef5af6362002-07-08 23:15:32 +00001038 // If there are implicit references, mark their allocated regs as well
Chris Lattner3bed95b2003-08-05 21:55:58 +00001039 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
Vikram S. Advef5af6362002-07-08 23:15:32 +00001040 if (const LiveRange*
Brian Gaeke4efe3422003-09-21 01:23:46 +00001041 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
Vikram S. Advef5af6362002-07-08 23:15:32 +00001042 if (LRofImpRef->hasColor())
1043 // this implicit reference is in a LR that received a color
Vikram S. Advebc001b22003-07-25 21:06:09 +00001044 RC->markColorsUsed(LRofImpRef->getColor(),
1045 MRI.getRegTypeForLR(LRofImpRef), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001046}
1047
1048
Brian Gaekeaf843702003-10-22 20:22:53 +00001049/// If there are delay slots for an instruction, the instructions added after
1050/// it must really go after the delayed instruction(s). So, we Move the
1051/// InstrAfter of that instruction to the corresponding delayed instruction
1052/// using the following method.
1053///
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001054void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1055 const MachineInstr *DelayedMI)
1056{
Vikram S. Advefeb32982003-08-12 22:22:24 +00001057 // "added after" instructions of the original instr
1058 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1059
1060 if (DEBUG_RA && OrigAft.size() > 0) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001061 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1062 std::cerr << " to last delay slot instrn: " << *DelayedMI;
Vikram S. Adve814030a2003-07-29 19:49:21 +00001063 }
1064
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001065 // "added after" instructions of the delayed instr
Vikram S. Adve814030a2003-07-29 19:49:21 +00001066 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001067
1068 // go thru all the "added after instructions" of the original instruction
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001069 // and append them to the "added after instructions" of the delayed
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001070 // instructions
Chris Lattner697954c2002-01-20 22:54:45 +00001071 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001072
1073 // empty the "added after instructions" of the original instruction
1074 OrigAft.clear();
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001075}
Ruchira Sasanka0931a012001-09-15 19:06:58 +00001076
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001077
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001078void PhyRegAlloc::colorIncomingArgs()
1079{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001080 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
Vikram S. Adve814030a2003-07-29 19:49:21 +00001081 AddedInstrAtEntry.InstrnsAfter);
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001082}
1083
Ruchira Sasankae727f852001-09-18 22:43:57 +00001084
Brian Gaekeaf843702003-10-22 20:22:53 +00001085/// Determine whether the suggested color of each live range is really usable,
1086/// and then call its setSuggestedColorUsable() method to record the answer. A
1087/// suggested color is NOT usable when the suggested color is volatile AND
1088/// when there are call interferences.
1089///
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001090void PhyRegAlloc::markUnusableSugColors()
1091{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001092 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1093 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001094
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001095 for (; HMI != HMIEnd ; ++HMI ) {
1096 if (HMI->first) {
1097 LiveRange *L = HMI->second; // get the LiveRange
Brian Gaeke59b1c562003-09-24 17:50:28 +00001098 if (L && L->hasSuggestedColor ())
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001099 L->setSuggestedColorUsable
1100 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1101 && L->isCallInterference ()));
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001102 }
1103 } // for all LR's in hash map
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001104}
1105
1106
Brian Gaekeaf843702003-10-22 20:22:53 +00001107/// For each live range that is spilled, allocates a new spill position on the
1108/// stack, and set the stack offsets of the live range that will be spilled to
1109/// that position. This must be called just after coloring the LRs.
1110///
Chris Lattner37730942002-02-05 03:52:29 +00001111void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001112 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001113
Brian Gaeke4efe3422003-09-21 01:23:46 +00001114 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1115 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001116
Chris Lattner7e708292002-06-25 16:13:24 +00001117 for ( ; HMI != HMIEnd ; ++HMI) {
Chris Lattner37730942002-02-05 03:52:29 +00001118 if (HMI->first && HMI->second) {
Vikram S. Adve3bf08922003-07-10 19:42:55 +00001119 LiveRange *L = HMI->second; // get the LiveRange
1120 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
Brian Gaeke4efe3422003-09-21 01:23:46 +00001121 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001122 L->setSpillOffFromFP(stackOffset);
1123 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001124 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001125 << ": stack-offset = " << stackOffset << "\n";
1126 }
Chris Lattner37730942002-02-05 03:52:29 +00001127 }
1128 } // for all LR's in hash map
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001129}
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001130
Brian Gaeke874f4232003-09-21 02:50:21 +00001131
Brian Gaeke21390412003-11-10 00:05:26 +00001132void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
Brian Gaeke54a76b82004-03-08 23:22:02 +00001133 const Value *V, int Insn, int Opnd) {
Brian Gaeke21390412003-11-10 00:05:26 +00001134 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V);
1135 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();
1136 AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated;
1137 int Placement = -1;
1138 if ((HMI != HMIEnd) && HMI->second) {
1139 LiveRange *L = HMI->second;
1140 assert ((L->hasColor () || L->isMarkedForSpill ())
1141 && "Live range exists but not colored or spilled");
1142 if (L->hasColor ()) {
1143 AllocState = AllocInfo::Allocated;
1144 Placement = MRI.getUnifiedRegNum (L->getRegClassID (),
1145 L->getColor ());
1146 } else if (L->isMarkedForSpill ()) {
1147 AllocState = AllocInfo::Spilled;
1148 assert (L->hasSpillOffset ()
1149 && "Live range marked for spill but has no spill offset");
1150 Placement = L->getSpillOffFromFP ();
1151 }
1152 }
1153 state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement));
1154}
1155
1156
Brian Gaekeaf843702003-10-22 20:22:53 +00001157/// Save the global register allocation decisions made by the register
1158/// allocator so that they can be accessed later (sort of like "poor man's
1159/// debug info").
1160///
1161void PhyRegAlloc::saveState () {
Brian Gaeke537132b2003-10-23 20:32:55 +00001162 std::vector<AllocInfo> &state = FnAllocState[Fn];
Brian Gaeke54a76b82004-03-08 23:22:02 +00001163 unsigned ArgNum = 0;
1164 // Arguments encoded as instruction # -1
1165 for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1166 const Argument *Arg = &*i;
1167 saveStateForValue (state, Arg, -1, ArgNum);
1168 ++ArgNum;
1169 }
Brian Gaeke25d4b542004-05-30 07:08:43 +00001170 unsigned InstCount = 0;
Brian Gaeke54a76b82004-03-08 23:22:02 +00001171 // Instructions themselves encoded as operand # -1
Brian Gaeke3ceac852003-10-30 21:21:33 +00001172 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
Brian Gaeke25d4b542004-05-30 07:08:43 +00001173 const Instruction *Inst = &*II;
1174 saveStateForValue (state, Inst, InstCount, -1);
1175 if (isa<PHINode> (Inst)) {
1176 MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get(Inst);
1177 // Last instr should be the copy...figure out what reg it is reading from
1178 if (Value *PhiCpRes = MCforPN.back()->getOperand(0).getVRegValueOrNull()){
1179 if (DEBUG_RA)
1180 std::cerr << "Found Phi copy result: " << PhiCpRes->getName()
1181 << " in: " << *MCforPN.back() << "\n";
1182 saveStateForValue (state, PhiCpRes, InstCount, -2);
1183 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001184 }
Brian Gaeke25d4b542004-05-30 07:08:43 +00001185 ++InstCount;
Brian Gaeke3ceac852003-10-30 21:21:33 +00001186 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001187}
1188
Brian Gaeke537132b2003-10-23 20:32:55 +00001189
Brian Gaekea7afac22004-05-30 04:22:24 +00001190/// Dump the saved state filled in by saveState() out to stderr. Only
1191/// used when debugging.
Brian Gaekeaf843702003-10-22 20:22:53 +00001192///
Brian Gaekea7afac22004-05-30 04:22:24 +00001193void PhyRegAlloc::dumpSavedState () {
Brian Gaeke3ceac852003-10-30 21:21:33 +00001194 std::vector<AllocInfo> &state = FnAllocState[Fn];
Brian Gaekecf68bd52004-03-11 06:45:52 +00001195 int ArgNum = 0;
1196 for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1197 const Argument *Arg = &*i;
1198 std::cerr << "Argument: " << *Arg << "\n"
1199 << "FnAllocState:\n";
1200 for (unsigned i = 0; i < state.size (); ++i) {
1201 AllocInfo &S = state[i];
1202 if (S.Instruction == -1 && S.Operand == ArgNum)
1203 std::cerr << " " << S << "\n";
1204 }
1205 std::cerr << "----------\n";
1206 ++ArgNum;
1207 }
Brian Gaeke54a76b82004-03-08 23:22:02 +00001208 int Insn = 0;
Brian Gaeke3ceac852003-10-30 21:21:33 +00001209 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00001210 const Instruction *I = &*II;
Brian Gaeke3ceac852003-10-30 21:21:33 +00001211 MachineCodeForInstruction &Instrs = MachineCodeForInstruction::get (I);
Brian Gaekecf68bd52004-03-11 06:45:52 +00001212 std::cerr << "Instruction: " << *I
Brian Gaeke3ceac852003-10-30 21:21:33 +00001213 << "MachineCodeForInstruction:\n";
1214 for (unsigned i = 0, n = Instrs.size (); i != n; ++i)
Brian Gaekecf68bd52004-03-11 06:45:52 +00001215 std::cerr << " " << *Instrs[i];
Brian Gaeke3ceac852003-10-30 21:21:33 +00001216 std::cerr << "FnAllocState:\n";
1217 for (unsigned i = 0; i < state.size (); ++i) {
1218 AllocInfo &S = state[i];
Brian Gaeke97374d42004-01-28 19:05:43 +00001219 if (Insn == S.Instruction)
1220 std::cerr << " " << S << "\n";
Brian Gaeke3ceac852003-10-30 21:21:33 +00001221 }
1222 std::cerr << "----------\n";
1223 ++Insn;
1224 }
Brian Gaekeaf843702003-10-22 20:22:53 +00001225}
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001226
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001227
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001228bool PhyRegAlloc::doFinalization (Module &M) {
Brian Gaekecf68bd52004-03-11 06:45:52 +00001229 if (SaveRegAllocState) finishSavingState (M);
1230 return false;
1231}
1232
1233
1234/// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1235/// Constant and stuffing it inside the Module.
1236///
1237/// FIXME: There should be other, better ways of storing the saved
1238/// state; this one is cumbersome and does not work well with the JIT.
1239///
1240void PhyRegAlloc::finishSavingState (Module &M) {
Brian Gaekec760d642004-03-11 19:46:30 +00001241 if (DEBUG_RA)
1242 std::cerr << "---- Saving reg. alloc state; SaveStateToModule = "
1243 << SaveStateToModule << " ----\n";
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001244
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001245 // If saving state into the module, just copy new elements to the
1246 // correct global.
Brian Gaeke8fc49342003-10-24 21:21:58 +00001247 if (!SaveStateToModule) {
1248 ExportedFnAllocState = FnAllocState;
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001249 // FIXME: should ONLY copy new elements in FnAllocState
Brian Gaekecf68bd52004-03-11 06:45:52 +00001250 return;
Brian Gaeke8fc49342003-10-24 21:21:58 +00001251 }
1252
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001253 // Convert FnAllocState to a single Constant array and add it
1254 // to the Module.
1255 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1256 std::vector<const Type *> TV;
1257 TV.push_back (Type::UIntTy);
1258 TV.push_back (AT);
1259 PointerType *PT = PointerType::get (StructType::get (TV));
1260
1261 std::vector<Constant *> allstate;
1262 for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1263 Function *F = I;
Brian Gaeke55766e12003-11-04 22:42:41 +00001264 if (F->isExternal ()) continue;
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001265 if (FnAllocState.find (F) == FnAllocState.end ()) {
1266 allstate.push_back (ConstantPointerNull::get (PT));
1267 } else {
Brian Gaeke537132b2003-10-23 20:32:55 +00001268 std::vector<AllocInfo> &state = FnAllocState[F];
Brian Gaeke60a3c552003-10-22 20:44:23 +00001269
1270 // Convert state into an LLVM ConstantArray, and put it in a
1271 // ConstantStruct (named S) along with its size.
Brian Gaeke537132b2003-10-23 20:32:55 +00001272 std::vector<Constant *> stateConstants;
1273 for (unsigned i = 0, s = state.size (); i != s; ++i)
1274 stateConstants.push_back (state[i].toConstant ());
1275 unsigned Size = stateConstants.size ();
Brian Gaeke60a3c552003-10-22 20:44:23 +00001276 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1277 std::vector<const Type *> TV;
1278 TV.push_back (Type::UIntTy);
1279 TV.push_back (AT);
1280 StructType *ST = StructType::get (TV);
1281 std::vector<Constant *> CV;
1282 CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
Brian Gaeke537132b2003-10-23 20:32:55 +00001283 CV.push_back (ConstantArray::get (AT, stateConstants));
Brian Gaeke60a3c552003-10-22 20:44:23 +00001284 Constant *S = ConstantStruct::get (ST, CV);
1285
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001286 GlobalVariable *GV =
Brian Gaeke60a3c552003-10-22 20:44:23 +00001287 new GlobalVariable (ST, true,
1288 GlobalValue::InternalLinkage, S,
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001289 F->getName () + ".regAllocState", &M);
Brian Gaeke60a3c552003-10-22 20:44:23 +00001290
Brian Gaeke21390412003-11-10 00:05:26 +00001291 // Have: { uint, [Size x { uint, int, uint, int }] } *
1292 // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
Reid Spencer518310c2004-07-18 00:44:37 +00001293 Constant *CE = ConstantExpr::getCast (GV, PT);
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001294 allstate.push_back (CE);
1295 }
1296 }
1297
1298 unsigned Size = allstate.size ();
1299 // Final structure type is:
Brian Gaeke21390412003-11-10 00:05:26 +00001300 // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001301 std::vector<const Type *> TV2;
1302 TV2.push_back (Type::UIntTy);
1303 ArrayType *AT2 = ArrayType::get (PT, Size);
1304 TV2.push_back (AT2);
1305 StructType *ST2 = StructType::get (TV2);
1306 std::vector<Constant *> CV2;
1307 CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1308 CV2.push_back (ConstantArray::get (AT2, allstate));
Brian Gaekee9414ca2003-11-10 07:12:01 +00001309 new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001310 ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1311 &M);
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001312}
1313
1314
Brian Gaekeaf843702003-10-22 20:22:53 +00001315/// Allocate registers for the machine code previously generated for F using
1316/// the graph-coloring algorithm.
1317///
Brian Gaeke4efe3422003-09-21 01:23:46 +00001318bool PhyRegAlloc::runOnFunction (Function &F) {
1319 if (DEBUG_RA)
1320 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1321
1322 Fn = &F;
1323 MF = &MachineFunction::get (Fn);
1324 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1325 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1326 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1327
1328 // Create each RegClass for the target machine and add it to the
1329 // RegClassList. This must be done before calling constructLiveRanges().
1330 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
Chris Lattnerd029cd22004-06-02 05:55:25 +00001331 RegClassList.push_back (new RegClass (Fn, TM.getRegInfo(),
1332 MRI.getMachineRegClass(rc)));
Brian Gaeke4efe3422003-09-21 01:23:46 +00001333
1334 LRI->constructLiveRanges(); // create LR info
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001335 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
Brian Gaeke4efe3422003-09-21 01:23:46 +00001336 LRI->printLiveRanges();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001337
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001338 createIGNodeListsAndIGs(); // create IGNode list and IGs
1339
1340 buildInterferenceGraphs(); // build IGs in all reg classes
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001341
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001342 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001343 // print all LRs in all reg classes
Chris Lattner7e708292002-06-25 16:13:24 +00001344 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1345 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001346
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001347 // print IGs in all register classes
Chris Lattner7e708292002-06-25 16:13:24 +00001348 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1349 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001350 }
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001351
Brian Gaeke4efe3422003-09-21 01:23:46 +00001352 LRI->coalesceLRs(); // coalesce all live ranges
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +00001353
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001354 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001355 // print all LRs in all reg classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001356 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1357 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001358
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001359 // print IGs in all register classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001360 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1361 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001362 }
1363
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001364 // mark un-usable suggested color before graph coloring algorithm.
1365 // When this is done, the graph coloring algo will not reserve
1366 // suggested color unnecessarily - they can be used by another LR
1367 markUnusableSugColors();
1368
1369 // color all register classes using the graph coloring algo
Chris Lattner7e708292002-06-25 16:13:24 +00001370 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerf726e772002-10-28 19:22:04 +00001371 RegClassList[rc]->colorAllRegs();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001372
Misha Brukman37f92e22003-09-11 22:34:13 +00001373 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1374 // a position for such spilled LRs
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001375 allocateStackSpace4SpilledLRs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001376
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001377 // Reset the temp. area on the stack before use by the first instruction.
1378 // This will also happen after updating each instruction.
Brian Gaeke4efe3422003-09-21 01:23:46 +00001379 MF->getInfo()->popAllTempValues();
Ruchira Sasankaf90870f2001-11-15 22:02:06 +00001380
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001381 // color incoming args - if the correct color was not received
1382 // insert code to copy to the correct register
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001383 colorIncomingArgs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001384
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001385 // Save register allocation state for this function in a Constant.
Brian Gaeke14068d92004-03-10 22:01:59 +00001386 if (SaveRegAllocState) {
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001387 saveState();
Brian Gaekeaf843702003-10-22 20:22:53 +00001388 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001389
Brian Gaeke60a3c552003-10-22 20:44:23 +00001390 // Now update the machine code with register names and add any additional
1391 // code inserted by the register allocator to the instruction stream.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001392 updateMachineCode();
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001393
Brian Gaekea7afac22004-05-30 04:22:24 +00001394 if (SaveRegAllocState) {
1395 if (DEBUG_RA) // Check our work.
1396 dumpSavedState ();
1397 if (!SaveStateToModule)
1398 finishSavingState (const_cast<Module&> (*Fn->getParent ()));
1399 }
1400
Chris Lattner045e7c82001-09-19 16:26:23 +00001401 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001402 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
Brian Gaeke4efe3422003-09-21 01:23:46 +00001403 MF->dump();
Chris Lattner045e7c82001-09-19 16:26:23 +00001404 }
Brian Gaeke4efe3422003-09-21 01:23:46 +00001405
1406 // Tear down temporary data structures
1407 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1408 delete RegClassList[rc];
1409 RegClassList.clear ();
1410 AddedInstrMap.clear ();
1411 OperandsColoredMap.clear ();
1412 ScratchRegsUsed.clear ();
1413 AddedInstrAtEntry.clear ();
1414 delete LRI;
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001415
Brian Gaeke4efe3422003-09-21 01:23:46 +00001416 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1417 return false; // Function was not modified
1418}
Brian Gaeked0fde302003-11-11 22:41:34 +00001419
1420} // End llvm namespace