blob: 38ef2acc67aedc0eddd53e60d2824b5079c4e5e2 [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"
Chris Lattner9670eec2004-07-29 17:11:37 +000032#include "llvm/Instructions.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000033#include "llvm/Module.h"
34#include "llvm/Type.h"
35#include "llvm/Analysis/LoopInfo.h"
Chris Lattner797c1362003-09-30 20:13:59 +000036#include "llvm/CodeGen/InstrSelection.h"
Brian Gaeke3ceac852003-10-30 21:21:33 +000037#include "llvm/CodeGen/MachineCodeForInstruction.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000038#include "llvm/CodeGen/MachineFunction.h"
39#include "llvm/CodeGen/MachineFunctionInfo.h"
Brian Gaeke874f4232003-09-21 02:50:21 +000040#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerf6ee49f2003-01-15 18:08:07 +000041#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner08d49632004-02-29 19:12:51 +000042#include "../MachineInstrAnnot.h"
Chris Lattner797c1362003-09-30 20:13:59 +000043#include "llvm/CodeGen/Passes.h"
Chris Lattner797c1362003-09-30 20:13:59 +000044#include "llvm/Support/InstIterator.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000045#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner4bc23482002-09-15 07:07:55 +000046#include "Support/CommandLine.h"
Misha Brukman396c8c32003-10-23 18:06:27 +000047#include "Support/SetOperations.h"
48#include "Support/STLExtras.h"
Brian Gaekebd353fb2003-09-21 03:57:37 +000049#include <cmath>
Reid Spencer954da372004-07-04 12:19:56 +000050#include <iostream>
Vikram S. Adve12af1642001-11-08 04:48:50 +000051
Brian Gaeked0fde302003-11-11 22:41:34 +000052namespace llvm {
53
Chris Lattner70e60cb2002-05-22 17:08:27 +000054RegAllocDebugLevel_t DEBUG_RA;
Vikram S. Adve39c94e12002-09-14 23:05:33 +000055
Chris Lattner5ff62e92002-07-22 02:10:13 +000056static cl::opt<RegAllocDebugLevel_t, true>
57DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
58 cl::desc("enable register allocation debugging information"),
59 cl::values(
Vikram S. Adve39c94e12002-09-14 23:05:33 +000060 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
61 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
62 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
63 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
64 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
65 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
Chris Lattner4d143ee2004-07-16 00:08:28 +000066 clEnumValEnd));
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000067
Brian Gaeked1b36792004-03-10 22:21:03 +000068/// The reoptimizer wants to be able to grovel through the register
69/// allocator's state after it has done its job. This is a hack.
70///
71PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
72bool SaveRegAllocState = false;
73bool SaveStateToModule = true;
74static cl::opt<bool, true>
75SaveRegAllocStateOpt("save-ra-state", cl::Hidden,
76 cl::location (SaveRegAllocState),
77 cl::init(false),
Brian Gaeke59b1c562003-09-24 17:50:28 +000078 cl::desc("write reg. allocator state into module"));
79
Brian Gaekebf3c4cf2003-08-14 06:09:32 +000080FunctionPass *getRegisterAllocator(TargetMachine &T) {
Brian Gaeke4efe3422003-09-21 01:23:46 +000081 return new PhyRegAlloc (T);
Chris Lattner2f9b28e2002-02-04 15:54:09 +000082}
Chris Lattner6dd98a62002-02-04 00:33:08 +000083
Chris Lattner8474f6f2003-09-23 15:13:04 +000084void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo> ();
86 AU.addRequired<FunctionLiveVarInfo> ();
87}
88
89
Brian Gaekeaf843702003-10-22 20:22:53 +000090/// Initialize interference graphs (one in each reg class) and IGNodeLists
91/// (one in each IG). The actual nodes will be pushed later.
92///
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000093void PhyRegAlloc::createIGNodeListsAndIGs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +000094 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000095
Brian Gaeke4efe3422003-09-21 01:23:46 +000096 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
Brian Gaeke4efe3422003-09-21 01:23:46 +000097 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000098
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000099 for (; HMI != HMIEnd ; ++HMI ) {
100 if (HMI->first) {
101 LiveRange *L = HMI->second; // get the LiveRange
102 if (!L) {
Brian Gaekeeb8863d2004-03-29 21:58:41 +0000103 if (DEBUG_RA && !isa<ConstantIntegral> (HMI->first))
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000104 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000105 << RAV(HMI->first) << "****\n";
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000106 continue;
107 }
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000108
109 // if the Value * is not null, and LR is not yet written to the IGNodeList
Chris Lattner7e708292002-06-25 16:13:24 +0000110 if (!(L->getUserIGNode()) ) {
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000111 RegClass *const RC = // RegClass of first value in the LR
Brian Gaeke59b1c562003-09-24 17:50:28 +0000112 RegClassList[ L->getRegClassID() ];
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000113 RC->addLRToIG(L); // add this LR to an IG
114 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000115 }
116 }
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000117
118 // init RegClassList
Chris Lattner7e708292002-06-25 16:13:24 +0000119 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000120 RegClassList[rc]->createInterferenceGraph();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000121
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000122 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000123}
124
125
Brian Gaekeaf843702003-10-22 20:22:53 +0000126/// Add all interferences for a given instruction. Interference occurs only
127/// if the LR of Def (Inst or Arg) is of the same reg class as that of live
128/// var. The live var passed to this function is the LVset AFTER the
129/// instruction.
130///
131void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
Chris Lattner296b7732002-02-05 02:52:05 +0000132 bool isCallInst) {
Chris Lattner296b7732002-02-05 02:52:05 +0000133 ValueSet::const_iterator LIt = LVSet->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000134
135 // get the live range of instruction
Brian Gaeke4efe3422003-09-21 01:23:46 +0000136 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000137
138 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
139 assert( IGNodeOfDef );
140
141 RegClass *const RCOfDef = LROfDef->getRegClass();
142
143 // for each live var in live variable set
Chris Lattner7e708292002-06-25 16:13:24 +0000144 for ( ; LIt != LVSet->end(); ++LIt) {
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000145
Vikram S. Advef5af6362002-07-08 23:15:32 +0000146 if (DEBUG_RA >= RA_DEBUG_Verbose)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000147 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000148
149 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000150 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000151
152 // LROfVar can be null if it is a const since a const
153 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000154 if (LROfVar)
155 if (LROfDef != LROfVar) // do not set interf for same LR
156 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
157 RCOfDef->setInterference( LROfDef, LROfVar);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000158 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000159}
160
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000161
Brian Gaekeaf843702003-10-22 20:22:53 +0000162/// For a call instruction, this method sets the CallInterference flag in
163/// the LR of each variable live in the Live Variable Set live after the
164/// call instruction (except the return value of the call instruction - since
165/// the return value does not interfere with that call itself).
166///
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000167void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
Chris Lattner296b7732002-02-05 02:52:05 +0000168 const ValueSet *LVSetAft) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000169 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000170 std::cerr << "\n For call inst: " << *MInst;
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000171
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000172 // for each live var in live variable set after machine inst
Vikram S. Adve65b2f402003-07-02 01:24:00 +0000173 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
174 LIt != LEnd; ++LIt) {
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000175
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000176 // get the live range corresponding to live var
Brian Gaekea308f802004-07-29 06:43:09 +0000177 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000178
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000179 // LR can be null if it is a const since a const
180 // doesn't have a dominating def - see Assumptions above
Brian Gaekea308f802004-07-29 06:43:09 +0000181 if (LR) {
182 if (DEBUG_RA >= RA_DEBUG_Interference)
183 std::cerr << "\n\tLR after Call: " << *LR << "\n";
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000184 LR->setCallInterference();
Brian Gaekea308f802004-07-29 06:43:09 +0000185 if (DEBUG_RA >= RA_DEBUG_Interference)
186 std::cerr << "\n ++After adding call interference for LR: " << *LR << "\n";
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000187 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000188 }
189
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000190 // Now find the LR of the return value of the call
191 // We do this because, we look at the LV set *after* the instruction
192 // to determine, which LRs must be saved across calls. The return value
193 // of the call is live in this set - but it does not interfere with call
194 // (i.e., we can allocate a volatile register to the return value)
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000195 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
196
197 if (const Value *RetVal = argDesc->getReturnValue()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000198 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000199 assert( RetValLR && "No LR for RetValue of call");
200 RetValLR->clearCallInterference();
201 }
202
203 // If the CALL is an indirect call, find the LR of the function pointer.
204 // That has a call interference because it conflicts with outgoing args.
Chris Lattner7e708292002-06-25 16:13:24 +0000205 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000206 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000207 assert( AddrValLR && "No LR for indirect addr val of call");
208 AddrValLR->setCallInterference();
209 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000210}
211
212
Brian Gaekeaf843702003-10-22 20:22:53 +0000213/// Create interferences in the IG of each RegClass, and calculate the spill
214/// cost of each Live Range (it is done in this method to save another pass
215/// over the code).
216///
217void PhyRegAlloc::buildInterferenceGraphs() {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000218 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000219 std::cerr << "Creating interference graphs ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000220
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000221 unsigned BBLoopDepthCost;
Brian Gaeke4efe3422003-09-21 01:23:46 +0000222 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000223 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000224 const MachineBasicBlock &MBB = *BBI;
225 const BasicBlock *BB = MBB.getBasicBlock();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000226
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000227 // find the 10^(loop_depth) of this BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000228 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000229
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000230 // get the iterator for machine instructions
Chris Lattnerf726e772002-10-28 19:22:04 +0000231 MachineBasicBlock::const_iterator MII = MBB.begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000232
233 // iterate over all the machine instructions in BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000234 for ( ; MII != MBB.end(); ++MII) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000235 const MachineInstr *MInst = MII;
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000236
237 // get the LV set after the instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000238 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
Chris Lattnerd029cd22004-06-02 05:55:25 +0000239 bool isCallInst = TM.getInstrInfo()->isCall(MInst->getOpcode());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000240
Brian Gaekeaf843702003-10-22 20:22:53 +0000241 if (isCallInst) {
Misha Brukman37f92e22003-09-11 22:34:13 +0000242 // set the isCallInterference flag of each live range which extends
243 // across this call instruction. This information is used by graph
244 // coloring algorithm to avoid allocating volatile colors to live ranges
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000245 // that span across calls (since they have to be saved/restored)
Chris Lattner748697d2002-02-05 04:20:12 +0000246 setCallInterferences(MInst, &LVSetAI);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000247 }
248
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000249 // iterate over all MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000250 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
251 OpE = MInst->end(); OpI != OpE; ++OpI) {
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000252 if (OpI.isDef()) // create a new LR since def
Chris Lattner748697d2002-02-05 04:20:12 +0000253 addInterference(*OpI, &LVSetAI, isCallInst);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000254
255 // Calculate the spill cost of each live range
Brian Gaeke4efe3422003-09-21 01:23:46 +0000256 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
Chris Lattner2f898d22002-02-05 06:02:59 +0000257 if (LR) LR->addSpillCost(BBLoopDepthCost);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000258 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000259
Brian Gaekeaf843702003-10-22 20:22:53 +0000260 // Mark all operands of pseudo-instructions as interfering with one
261 // another. This must be done because pseudo-instructions may be
262 // expanded to multiple instructions by the assembler, so all the
263 // operands must get distinct registers.
Chris Lattnerd029cd22004-06-02 05:55:25 +0000264 if (TM.getInstrInfo()->isPseudoInstr(MInst->getOpcode()))
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000265 addInterf4PseudoInstr(MInst);
266
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000267 // Also add interference for any implicit definitions in a machine
268 // instr (currently, only calls have this).
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000269 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000270 for (unsigned z=0; z < NumOfImpRefs; z++)
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000271 if (MInst->getImplicitOp(z).isDef())
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000272 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +0000273
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000274 } // for all machine instructions in BB
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000275 } // for all BBs in function
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000276
Misha Brukman37f92e22003-09-11 22:34:13 +0000277 // add interferences for function arguments. Since there are no explicit
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000278 // defs in the function for args, we have to add them manually
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000279 addInterferencesForArgs();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000280
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000281 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000282 std::cerr << "Interference graphs calculated!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000283}
284
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000285
Brian Gaekeaf843702003-10-22 20:22:53 +0000286/// Mark all operands of the given MachineInstr as interfering with one
287/// another.
288///
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000289void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000290 bool setInterf = false;
291
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000292 // iterate over MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000293 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
294 ItE = MInst->end(); It1 != ItE; ++It1) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000295 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000296 assert((LROfOp1 || It1.isDef()) && "No LR for Def in PSEUDO insruction");
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000297
Chris Lattner2f898d22002-02-05 06:02:59 +0000298 MachineInstr::const_val_op_iterator It2 = It1;
Chris Lattner7e708292002-06-25 16:13:24 +0000299 for (++It2; It2 != ItE; ++It2) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000300 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000301
Chris Lattner2f898d22002-02-05 06:02:59 +0000302 if (LROfOp2) {
303 RegClass *RCOfOp1 = LROfOp1->getRegClass();
304 RegClass *RCOfOp2 = LROfOp2->getRegClass();
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000305
Chris Lattner7e708292002-06-25 16:13:24 +0000306 if (RCOfOp1 == RCOfOp2 ){
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000307 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000308 setInterf = true;
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000309 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000310 } // if Op2 has a LR
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000311 } // for all other defs in machine instr
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000312 } // for all operands in an instruction
313
Chris Lattner2f898d22002-02-05 06:02:59 +0000314 if (!setInterf && MInst->getNumOperands() > 2) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000315 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
316 std::cerr << *MInst;
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000317 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000318 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000319}
320
321
Brian Gaekeaf843702003-10-22 20:22:53 +0000322/// Add interferences for incoming arguments to a function.
323///
Chris Lattner296b7732002-02-05 02:52:05 +0000324void PhyRegAlloc::addInterferencesForArgs() {
325 // get the InSet of root BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000326 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000327
Chris Lattnerf726e772002-10-28 19:22:04 +0000328 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000329 // add interferences between args and LVars at start
330 addInterference(AI, &InSet, false);
331
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000332 if (DEBUG_RA >= RA_DEBUG_Interference)
Brian Gaekeaf843702003-10-22 20:22:53 +0000333 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000334 }
335}
336
337
Brian Gaekeaf843702003-10-22 20:22:53 +0000338/// The following are utility functions used solely by updateMachineCode and
339/// the functions that it calls. They should probably be folded back into
340/// updateMachineCode at some point.
341///
Vikram S. Adve48762092002-04-25 04:34:15 +0000342
Brian Gaekeaf843702003-10-22 20:22:53 +0000343// used by: updateMachineCode (1 time), PrependInstructions (1 time)
344inline void InsertBefore(MachineInstr* newMI, MachineBasicBlock& MBB,
345 MachineBasicBlock::iterator& MII) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000346 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000347 ++MII;
348}
349
Brian Gaekeaf843702003-10-22 20:22:53 +0000350// used by: AppendInstructions (1 time)
351inline void InsertAfter(MachineInstr* newMI, MachineBasicBlock& MBB,
352 MachineBasicBlock::iterator& MII) {
Vikram S. Advecb202e32002-10-11 16:12:40 +0000353 ++MII; // insert before the next instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000354 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000355}
356
Brian Gaekeaf843702003-10-22 20:22:53 +0000357// used by: updateMachineCode (2 times)
358inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
359 MachineBasicBlock& MBB,
360 MachineBasicBlock::iterator& MII,
361 const std::string& msg) {
362 if (!IBef.empty()) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000363 MachineInstr* OrigMI = MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000364 std::vector<MachineInstr *>::iterator AdIt;
Brian Gaekeaf843702003-10-22 20:22:53 +0000365 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000366 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000367 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
368 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000369 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000370 InsertBefore(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000371 }
372 }
373}
374
Brian Gaekeaf843702003-10-22 20:22:53 +0000375// used by: updateMachineCode (1 time)
376inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
377 MachineBasicBlock& MBB,
378 MachineBasicBlock::iterator& MII,
379 const std::string& msg) {
380 if (!IAft.empty()) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000381 MachineInstr* OrigMI = MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000382 std::vector<MachineInstr *>::iterator AdIt;
Brian Gaekeaf843702003-10-22 20:22:53 +0000383 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
Chris Lattner7e708292002-06-25 16:13:24 +0000384 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000385 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
386 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000387 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000388 InsertAfter(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000389 }
390 }
391}
392
Brian Gaekeaf843702003-10-22 20:22:53 +0000393/// Set the registers for operands in the given MachineInstr, if a register was
394/// successfully allocated. Return true if any of its operands has been marked
395/// for spill.
396///
Brian Gaeke4efe3422003-09-21 01:23:46 +0000397bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000398{
Vikram S. Adve814030a2003-07-29 19:49:21 +0000399 bool instrNeedsSpills = false;
400
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000401 // First, set the registers for operands in the machine instruction
402 // if a register was successfully allocated. Do this first because we
403 // will need to know which registers are already used by this instr'n.
Brian Gaekeaf843702003-10-22 20:22:53 +0000404 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000405 MachineOperand& Op = MInst->getOperand(OpNum);
406 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
Brian Gaekeaf843702003-10-22 20:22:53 +0000407 Op.getType() == MachineOperand::MO_CCRegister) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000408 const Value *const Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000409 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000410 // Remember if any operand needs spilling
411 instrNeedsSpills |= LR->isMarkedForSpill();
412
413 // An operand may have a color whether or not it needs spilling
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000414 if (LR->hasColor())
415 MInst->SetRegForOperand(OpNum,
Brian Gaeke59b1c562003-09-24 17:50:28 +0000416 MRI.getUnifiedRegNum(LR->getRegClassID(),
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000417 LR->getColor()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000418 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000419 }
420 } // for each operand
Vikram S. Adve814030a2003-07-29 19:49:21 +0000421
422 return instrNeedsSpills;
423}
424
Brian Gaekeaf843702003-10-22 20:22:53 +0000425/// Mark allocated registers (using markAllocatedRegs()) on the instruction
426/// that MII points to. Then, if it's a call instruction, insert caller-saving
427/// code before and after it. Finally, insert spill code before and after it,
428/// using insertCode4SpilledLR().
429///
Vikram S. Adve814030a2003-07-29 19:49:21 +0000430void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
Brian Gaekeaf843702003-10-22 20:22:53 +0000431 MachineBasicBlock &MBB) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000432 MachineInstr* MInst = MII;
Brian Gaeke12c1d2c2004-02-11 20:47:34 +0000433 unsigned Opcode = MInst->getOpcode();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000434
435 // Reset tmp stack positions so they can be reused for each machine instr.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000436 MF->getInfo()->popAllTempValues();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000437
438 // Mark the operands for which regs have been allocated.
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000439 bool instrNeedsSpills = markAllocatedRegs(MII);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000440
441#ifndef NDEBUG
442 // Mark that the operands have been updated. Later,
443 // setRelRegsUsedByThisInst() is called to find registers used by each
444 // MachineInst, and it should not be used for an instruction until
445 // this is done. This flag just serves as a sanity check.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000446 OperandsColoredMap[MInst] = true;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000447#endif
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000448
Vikram S. Advebc001b22003-07-25 21:06:09 +0000449 // Now insert caller-saving code before/after the call.
450 // Do this before inserting spill code since some registers must be
451 // used by save/restore and spill code should not use those registers.
Chris Lattnerd029cd22004-06-02 05:55:25 +0000452 if (TM.getInstrInfo()->isCall(Opcode)) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000453 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Adve814030a2003-07-29 19:49:21 +0000454 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
455 MBB.getBasicBlock());
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000456 }
Vikram S. Advebc001b22003-07-25 21:06:09 +0000457
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000458 // Now insert spill code for remaining operands not allocated to
459 // registers. This must be done even for call return instructions
460 // since those are not handled by the special code above.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000461 if (instrNeedsSpills)
Brian Gaekeaf843702003-10-22 20:22:53 +0000462 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000463 MachineOperand& Op = MInst->getOperand(OpNum);
464 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
Brian Gaekeaf843702003-10-22 20:22:53 +0000465 Op.getType() == MachineOperand::MO_CCRegister) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000466 const Value* Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000467 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000468 if (LR->isMarkedForSpill())
469 insertCode4SpilledLR(LR, MII, MBB, OpNum);
470 }
471 } // for each operand
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000472}
473
Brian Gaekeaf843702003-10-22 20:22:53 +0000474/// Iterate over all the MachineBasicBlocks in the current function and set
475/// the allocated registers for each instruction (using updateInstruction()),
476/// after register allocation is complete. Then move code out of delay slots.
477///
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000478void PhyRegAlloc::updateMachineCode()
479{
Chris Lattner7e708292002-06-25 16:13:24 +0000480 // Insert any instructions needed at method entry
Brian Gaeke4efe3422003-09-21 01:23:46 +0000481 MachineBasicBlock::iterator MII = MF->front().begin();
482 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
Chris Lattner7e708292002-06-25 16:13:24 +0000483 "At function entry: \n");
484 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
485 "InstrsAfter should be unnecessary since we are just inserting at "
486 "the function entry point here.");
Vikram S. Adve48762092002-04-25 04:34:15 +0000487
Brian Gaeke4efe3422003-09-21 01:23:46 +0000488 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000489 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000490 MachineBasicBlock &MBB = *BBI;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000491
492 // Iterate over all machine instructions in BB and mark operands with
493 // their assigned registers or insert spill code, as appropriate.
494 // Also, fix operands of call/return instructions.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000495 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
Chris Lattnerd029cd22004-06-02 05:55:25 +0000496 if (! TM.getInstrInfo()->isDummyPhiInstr(MII->getOpcode()))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000497 updateInstruction(MII, MBB);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000498
499 // Now, move code out of delay slots of branches and returns if needed.
500 // (Also, move "after" code from calls to the last delay slot instruction.)
501 // Moving code out of delay slots is needed in 2 situations:
502 // (1) If this is a branch and it needs instructions inserted after it,
503 // move any existing instructions out of the delay slot so that the
504 // instructions can go into the delay slot. This only supports the
505 // case that #instrsAfter <= #delay slots.
506 //
507 // (2) If any instruction in the delay slot needs
508 // instructions inserted, move it out of the delay slot and before the
509 // branch because putting code before or after it would be VERY BAD!
510 //
511 // If the annul bit of the branch is set, neither of these is legal!
512 // If so, we need to handle spill differently but annulling is not yet used.
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000513 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000514 if (unsigned delaySlots =
Chris Lattnerd029cd22004-06-02 05:55:25 +0000515 TM.getInstrInfo()->getNumDelaySlots(MII->getOpcode())) {
Alkis Evlogimenosf81af212004-02-14 01:18:34 +0000516 MachineBasicBlock::iterator DelaySlotMI = next(MII);
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000517 assert(DelaySlotMI != MBB.end() && "no instruction for delay slot");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000518
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000519 // Check the 2 conditions above:
520 // (1) Does a branch need instructions added after it?
521 // (2) O/w does delay slot instr. need instrns before or after?
Chris Lattnerd029cd22004-06-02 05:55:25 +0000522 bool isBranch = (TM.getInstrInfo()->isBranch(MII->getOpcode()) ||
523 TM.getInstrInfo()->isReturn(MII->getOpcode()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000524 bool cond1 = (isBranch &&
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000525 AddedInstrMap.count(MII) &&
526 AddedInstrMap[MII].InstrnsAfter.size() > 0);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000527 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
528 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
529 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000530
Brian Gaekeaf843702003-10-22 20:22:53 +0000531 if (cond1 || cond2) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000532 assert(delaySlots==1 &&
533 "InsertBefore does not yet handle >1 delay slots!");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000534
535 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000536 std::cerr << "\nRegAlloc: Moved instr. with added code: "
Vikram S. Adve814030a2003-07-29 19:49:21 +0000537 << *DelaySlotMI
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000538 << " out of delay slots of instr: " << *MII;
539 }
540
541 // move instruction before branch
Chris Lattnerb4186e02004-03-31 21:59:59 +0000542 MBB.insert(MII, MBB.remove(DelaySlotMI++));
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000543
544 // On cond1 we are done (we already moved the
545 // instruction out of the delay slot). On cond2 we need
546 // to insert a nop in place of the moved instruction
547 if (cond2) {
Brian Gaekec9989812004-07-27 17:43:24 +0000548 MBB.insert(MII, BuildMI(V9::NOP, 1));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000549 }
550 }
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000551 else {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000552 // For non-branch instr with delay slots (probably a call), move
553 // InstrAfter to the instr. in the last delay slot.
Alkis Evlogimenosf81af212004-02-14 01:18:34 +0000554 MachineBasicBlock::iterator tmp = next(MII, delaySlots);
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000555 move2DelayedInstr(MII, tmp);
556 }
557 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000558
559 // Finally iterate over all instructions in BB and insert before/after
Vikram S. Advebc001b22003-07-25 21:06:09 +0000560 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000561 MachineInstr *MInst = MII;
Vikram S. Advebc001b22003-07-25 21:06:09 +0000562
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000563 // do not process Phis
Chris Lattnerd029cd22004-06-02 05:55:25 +0000564 if (TM.getInstrInfo()->isDummyPhiInstr(MInst->getOpcode()))
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000565 continue;
566
Vikram S. Advebc001b22003-07-25 21:06:09 +0000567 // if there are any added instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000568 if (AddedInstrMap.count(MInst)) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000569 AddedInstrns &CallAI = AddedInstrMap[MInst];
570
571#ifndef NDEBUG
Chris Lattnerd029cd22004-06-02 05:55:25 +0000572 bool isBranch = (TM.getInstrInfo()->isBranch(MInst->getOpcode()) ||
573 TM.getInstrInfo()->isReturn(MInst->getOpcode()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000574 assert((!isBranch ||
575 AddedInstrMap[MInst].InstrnsAfter.size() <=
Chris Lattnerd029cd22004-06-02 05:55:25 +0000576 TM.getInstrInfo()->getNumDelaySlots(MInst->getOpcode())) &&
Vikram S. Adve814030a2003-07-29 19:49:21 +0000577 "Cannot put more than #delaySlots instrns after "
578 "branch or return! Need to handle temps differently.");
579#endif
580
581#ifndef NDEBUG
Vikram S. Advebc001b22003-07-25 21:06:09 +0000582 // Temporary sanity checking code to detect whether the same machine
583 // instruction is ever inserted twice before/after a call.
584 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000585 std::set<const MachineInstr*> instrsSeen;
586 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
587 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
588 "Duplicate machine instruction in InstrnsBefore!");
589 instrsSeen.insert(CallAI.InstrnsBefore[i]);
590 }
591 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
592 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
593 "Duplicate machine instruction in InstrnsBefore/After!");
594 instrsSeen.insert(CallAI.InstrnsAfter[i]);
595 }
596#endif
597
598 // Now add the instructions before/after this MI.
599 // We do this here to ensure that spill for an instruction is inserted
600 // as close as possible to an instruction (see above insertCode4Spill)
Vikram S. Advebc001b22003-07-25 21:06:09 +0000601 if (! CallAI.InstrnsBefore.empty())
602 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
603
604 if (! CallAI.InstrnsAfter.empty())
605 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
606
607 } // if there are any added instructions
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000608 } // for each machine instruction
Ruchira Sasanka0931a012001-09-15 19:06:58 +0000609 }
610}
611
612
Brian Gaekeaf843702003-10-22 20:22:53 +0000613/// Insert spill code for AN operand whose LR was spilled. May be called
614/// repeatedly for a single MachineInstr if it has many spilled operands. On
615/// each call, it finds a register which is not live at that instruction and
616/// also which is not used by other spilled operands of the same
617/// instruction. Then it uses this register temporarily to accommodate the
618/// spilled value.
619///
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000620void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000621 MachineBasicBlock::iterator& MII,
622 MachineBasicBlock &MBB,
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000623 const unsigned OpNum) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000624 MachineInstr *MInst = MII;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000625 const BasicBlock *BB = MBB.getBasicBlock();
626
Chris Lattnerd029cd22004-06-02 05:55:25 +0000627 assert((! TM.getInstrInfo()->isCall(MInst->getOpcode()) || OpNum == 0) &&
Vikram S. Advead9c9782002-09-28 17:02:40 +0000628 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
Chris Lattnerd029cd22004-06-02 05:55:25 +0000629 assert(! TM.getInstrInfo()->isReturn(MInst->getOpcode()) &&
Vikram S. Advead9c9782002-09-28 17:02:40 +0000630 "Return value of a ret must be handled elsewhere");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000631
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000632 MachineOperand& Op = MInst->getOperand(OpNum);
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000633 bool isDef = Op.isDef();
634 bool isUse = Op.isUse();
Vikram S. Advebc001b22003-07-25 21:06:09 +0000635 unsigned RegType = MRI.getRegTypeForLR(LR);
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000636 int SpillOff = LR->getSpillOffFromFP();
637 RegClass *RC = LR->getRegClass();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000638
639 // Get the live-variable set to find registers free before this instr.
Vikram S. Advefeb32982003-08-12 22:22:24 +0000640 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
641
642#ifndef NDEBUG
643 // If this instr. is in the delay slot of a branch or return, we need to
644 // include all live variables before that branch or return -- we don't want to
645 // trample those! Verify that the set is included in the LV set before MInst.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000646 if (MII != MBB.begin()) {
Alkis Evlogimenosf81af212004-02-14 01:18:34 +0000647 MachineBasicBlock::iterator PredMI = prior(MII);
Chris Lattnerd029cd22004-06-02 05:55:25 +0000648 if (unsigned DS = TM.getInstrInfo()->getNumDelaySlots(PredMI->getOpcode()))
Vikram S. Advefeb32982003-08-12 22:22:24 +0000649 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
650 .empty() && "Live-var set before branch should be included in "
651 "live-var set of each delay slot instruction!");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000652 }
Vikram S. Advefeb32982003-08-12 22:22:24 +0000653#endif
Vikram S. Adve00521d72001-11-12 23:26:35 +0000654
Brian Gaekeaf843702003-10-22 20:22:53 +0000655 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000656
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000657 std::vector<MachineInstr*> MIBef, MIAft;
658 std::vector<MachineInstr*> AdIMid;
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000659
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000660 // Choose a register to hold the spilled value, if one was not preallocated.
661 // This may insert code before and after MInst to free up the value. If so,
662 // this code should be first/last in the spill sequence before/after MInst.
663 int TmpRegU=(LR->hasColor()
Brian Gaeke59b1c562003-09-24 17:50:28 +0000664 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000665 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000666
Vikram S. Advef5af6362002-07-08 23:15:32 +0000667 // Set the operand first so that it this register does not get used
668 // as a scratch register for later calls to getUsableUniRegAtMI below
669 MInst->SetRegForOperand(OpNum, TmpRegU);
670
671 // get the added instructions for this instruction
Chris Lattner0b0ffa02002-04-09 05:13:04 +0000672 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Advef5af6362002-07-08 23:15:32 +0000673
674 // We may need a scratch register to copy the spilled value to/from memory.
675 // This may itself have to insert code to free up a scratch register.
676 // Any such code should go before (after) the spill code for a load (store).
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000677 // The scratch reg is not marked as used because it is only used
678 // for the copy and not used across MInst.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000679 int scratchRegType = -1;
680 int scratchReg = -1;
Brian Gaekeaf843702003-10-22 20:22:53 +0000681 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
Chris Lattner27a08932002-10-22 23:16:21 +0000682 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
683 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000684 assert(scratchReg != MRI.getInvalidRegNum());
Vikram S. Advef5af6362002-07-08 23:15:32 +0000685 }
686
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000687 if (isUse) {
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000688 // for a USE, we have to load the value of LR from stack to a TmpReg
689 // and use the TmpReg as one operand of instruction
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000690
Vikram S. Advef5af6362002-07-08 23:15:32 +0000691 // actual loading instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000692 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
693 RegType, scratchReg);
Ruchira Sasanka226f1f02001-11-08 19:11:30 +0000694
Vikram S. Advef5af6362002-07-08 23:15:32 +0000695 // the actual load should be after the instructions to free up TmpRegU
696 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
697 AdIMid.clear();
698 }
699
Alkis Evlogimenos4d7af652003-12-14 13:24:17 +0000700 if (isDef) { // if this is a Def
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000701 // for a DEF, we have to store the value produced by this instruction
702 // on the stack position allocated for this LR
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000703
Vikram S. Advef5af6362002-07-08 23:15:32 +0000704 // actual storing instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000705 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
706 RegType, scratchReg);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000707
Vikram S. Advef5af6362002-07-08 23:15:32 +0000708 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000709 } // if !DEF
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000710
Vikram S. Advef5af6362002-07-08 23:15:32 +0000711 // Finally, insert the entire spill code sequences before/after MInst
712 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
713 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
714
Chris Lattner7e708292002-06-25 16:13:24 +0000715 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000716 std::cerr << "\nFor Inst:\n " << *MInst;
717 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
718 std::cerr << "; added Instructions:";
Anand Shuklad58290e2002-07-09 19:18:56 +0000719 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
720 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
Chris Lattner7e708292002-06-25 16:13:24 +0000721 }
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000722}
723
724
Brian Gaekeaf843702003-10-22 20:22:53 +0000725/// Insert caller saving/restoring instructions before/after a call machine
726/// instruction (before or after any other instructions that were inserted for
727/// the call).
728///
Vikram S. Adve814030a2003-07-29 19:49:21 +0000729void
730PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
731 std::vector<MachineInstr*> &instrnsAfter,
732 MachineInstr *CallMI,
Brian Gaekeaf843702003-10-22 20:22:53 +0000733 const BasicBlock *BB) {
Chris Lattnerd029cd22004-06-02 05:55:25 +0000734 assert(TM.getInstrInfo()->isCall(CallMI->getOpcode()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000735
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000736 // hash set to record which registers were saved/restored
Vikram S. Adve814030a2003-07-29 19:49:21 +0000737 hash_set<unsigned> PushedRegSet;
738
739 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
740
741 // if the call is to a instrumentation function, do not insert save and
742 // restore instructions the instrumentation function takes care of save
743 // restore for volatile regs.
744 //
745 // FIXME: this should be made general, not specific to the reoptimizer!
Vikram S. Adve814030a2003-07-29 19:49:21 +0000746 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
747 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
748
749 // Now check if the call has a return value (using argDesc) and if so,
750 // find the LR of the TmpInstruction representing the return value register.
751 // (using the last or second-last *implicit operand* of the call MI).
752 // Insert it to to the PushedRegSet since we must not save that register
753 // and restore it after the call.
754 // We do this because, we look at the LV set *after* the instruction
755 // to determine, which LRs must be saved across calls. The return value
756 // of the call is live in this set - but we must not save/restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000757 if (const Value *origRetVal = argDesc->getReturnValue()) {
758 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
759 (argDesc->getIndirectFuncPtr()? 1 : 2));
760 const TmpInstruction* tmpRetVal =
761 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
762 assert(tmpRetVal->getOperand(0) == origRetVal &&
763 tmpRetVal->getType() == origRetVal->getType() &&
764 "Wrong implicit ref?");
Brian Gaeke4efe3422003-09-21 01:23:46 +0000765 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000766 assert(RetValLR && "No LR for RetValue of call");
767
768 if (! RetValLR->isMarkedForSpill())
769 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
770 RetValLR->getColor()));
771 }
772
773 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
774 ValueSet::const_iterator LIt = LVSetAft.begin();
775
776 // for each live var in live variable set after machine inst
777 for( ; LIt != LVSetAft.end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000778 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000779 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000780
781 // LR can be null if it is a const since a const
782 // doesn't have a dominating def - see Assumptions above
Brian Gaekeaf843702003-10-22 20:22:53 +0000783 if (LR) {
784 if (! LR->isMarkedForSpill()) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000785 assert(LR->hasColor() && "LR is neither spilled nor colored?");
786 unsigned RCID = LR->getRegClassID();
787 unsigned Color = LR->getColor();
788
789 if (MRI.isRegVolatile(RCID, Color) ) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000790 // if this is a call to the first-level reoptimizer
791 // instrumentation entry point, and the register is not
792 // modified by call, don't save and restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000793 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
794 continue;
795
796 // if the value is in both LV sets (i.e., live before and after
797 // the call machine instruction)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000798 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
799
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000800 // if we haven't already pushed this register...
Vikram S. Adve814030a2003-07-29 19:49:21 +0000801 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000802 unsigned RegType = MRI.getRegTypeForLR(LR);
803
804 // Now get two instructions - to push on stack and pop from stack
805 // and add them to InstrnsBefore and InstrnsAfter of the
806 // call instruction
Vikram S. Adve814030a2003-07-29 19:49:21 +0000807 int StackOff =
Brian Gaeke4efe3422003-09-21 01:23:46 +0000808 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000809
810 //---- Insert code for pushing the reg on stack ----------
811
812 std::vector<MachineInstr*> AdIBef, AdIAft;
813
814 // We may need a scratch register to copy the saved value
815 // to/from memory. This may itself have to insert code to
816 // free up a scratch register. Any such code should go before
817 // the save code. The scratch register, if any, is by default
818 // temporary and not "used" by the instruction unless the
819 // copy code itself decides to keep the value in the scratch reg.
820 int scratchRegType = -1;
821 int scratchReg = -1;
822 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
823 { // Find a register not live in the LVSet before CallMI
824 const ValueSet &LVSetBef =
825 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
826 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
827 CallMI, AdIBef, AdIAft);
828 assert(scratchReg != MRI.getInvalidRegNum());
829 }
830
831 if (AdIBef.size() > 0)
832 instrnsBefore.insert(instrnsBefore.end(),
833 AdIBef.begin(), AdIBef.end());
834
835 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
836 StackOff, RegType, scratchReg);
837
838 if (AdIAft.size() > 0)
839 instrnsBefore.insert(instrnsBefore.end(),
840 AdIAft.begin(), AdIAft.end());
841
842 //---- Insert code for popping the reg from the stack ----------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000843 AdIBef.clear();
844 AdIAft.clear();
845
846 // We may need a scratch register to copy the saved value
847 // from memory. This may itself have to insert code to
848 // free up a scratch register. Any such code should go
849 // after the save code. As above, scratch is not marked "used".
Vikram S. Adve814030a2003-07-29 19:49:21 +0000850 scratchRegType = -1;
851 scratchReg = -1;
852 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
853 { // Find a register not live in the LVSet after CallMI
854 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
855 CallMI, AdIBef, AdIAft);
856 assert(scratchReg != MRI.getInvalidRegNum());
857 }
858
859 if (AdIBef.size() > 0)
860 instrnsAfter.insert(instrnsAfter.end(),
861 AdIBef.begin(), AdIBef.end());
862
863 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
864 Reg, RegType, scratchReg);
865
866 if (AdIAft.size() > 0)
867 instrnsAfter.insert(instrnsAfter.end(),
868 AdIAft.begin(), AdIAft.end());
869
870 PushedRegSet.insert(Reg);
871
872 if(DEBUG_RA) {
873 std::cerr << "\nFor call inst:" << *CallMI;
874 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
875 for_each(instrnsBefore.begin(), instrnsBefore.end(),
876 std::mem_fun(&MachineInstr::dump));
877 std::cerr << " -and After:\n\t ";
878 for_each(instrnsAfter.begin(), instrnsAfter.end(),
879 std::mem_fun(&MachineInstr::dump));
880 }
881 } // if not already pushed
Vikram S. Adve814030a2003-07-29 19:49:21 +0000882 } // if LR has a volatile color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000883 } // if LR has color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000884 } // if there is a LR for Var
Vikram S. Adve814030a2003-07-29 19:49:21 +0000885 } // for each value in the LV set after instruction
886}
887
888
Brian Gaekeaf843702003-10-22 20:22:53 +0000889/// Returns the unified register number of a temporary register to be used
890/// BEFORE MInst. If no register is available, it will pick one and modify
891/// MIBef and MIAft to contain instructions used to free up this returned
892/// register.
893///
Vikram S. Advef5af6362002-07-08 23:15:32 +0000894int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
895 const ValueSet *LVSetBef,
896 MachineInstr *MInst,
897 std::vector<MachineInstr*>& MIBef,
898 std::vector<MachineInstr*>& MIAft) {
Chris Lattner133f0792002-10-28 04:45:29 +0000899 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000900
Brian Gaekeaf843702003-10-22 20:22:53 +0000901 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000902
903 if (RegU == -1) {
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000904 // we couldn't find an unused register. Generate code to free up a reg by
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000905 // saving it on stack and restoring after the instruction
Vikram S. Advef5af6362002-07-08 23:15:32 +0000906
Brian Gaeke4efe3422003-09-21 01:23:46 +0000907 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve12af1642001-11-08 04:48:50 +0000908
Vikram S. Advebc001b22003-07-25 21:06:09 +0000909 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000910
Vikram S. Advef5af6362002-07-08 23:15:32 +0000911 // Check if we need a scratch register to copy this register to memory.
912 int scratchRegType = -1;
Brian Gaekeaf843702003-10-22 20:22:53 +0000913 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
Chris Lattner133f0792002-10-28 04:45:29 +0000914 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
915 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000916 assert(scratchReg != MRI.getInvalidRegNum());
917
918 // We may as well hold the value in the scratch register instead
919 // of copying it to memory and back. But we have to mark the
920 // register as used by this instruction, so it does not get used
921 // as a scratch reg. by another operand or anyone else.
Chris Lattner3fd1f5b2003-08-05 22:11:13 +0000922 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000923 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
924 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
Brian Gaekeaf843702003-10-22 20:22:53 +0000925 } else { // the register can be copied directly to/from memory so do it.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000926 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
927 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
Brian Gaekeaf843702003-10-22 20:22:53 +0000928 }
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000929 }
Vikram S. Advef5af6362002-07-08 23:15:32 +0000930
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000931 return RegU;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000932}
933
Vikram S. Adve814030a2003-07-29 19:49:21 +0000934
Brian Gaekeaf843702003-10-22 20:22:53 +0000935/// Returns the register-class register number of a new unused register that
936/// can be used to accommodate a temporary value. May be called repeatedly
937/// for a single MachineInstr. On each call, it finds a register which is not
938/// live at that instruction and which is not used by any spilled operands of
939/// that instruction.
940///
941int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000942 const MachineInstr *MInst,
943 const ValueSet* LVSetBef) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000944 RC->clearColorsUsed(); // Reset array
Vikram S. Adve814030a2003-07-29 19:49:21 +0000945
946 if (LVSetBef == NULL) {
947 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
948 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
949 }
950
Chris Lattner296b7732002-02-05 02:52:05 +0000951 ValueSet::const_iterator LIt = LVSetBef->begin();
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000952
953 // for each live var in live variable set after machine inst
Chris Lattner7e708292002-06-25 16:13:24 +0000954 for ( ; LIt != LVSetBef->end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000955 // Get the live range corresponding to live var, and its RegClass
Brian Gaeke4efe3422003-09-21 01:23:46 +0000956 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000957
958 // LR can be null if it is a const since a const
959 // doesn't have a dominating def - see Assumptions above
Vikram S. Advebc001b22003-07-25 21:06:09 +0000960 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
961 RC->markColorsUsed(LRofLV->getColor(),
962 MRI.getRegTypeForLR(LRofLV), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000963 }
964
965 // It is possible that one operand of this MInst was already spilled
966 // and it received some register temporarily. If that's the case,
967 // it is recorded in machine operand. We must skip such registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000968 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000969
Vikram S. Advebc001b22003-07-25 21:06:09 +0000970 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
971 if (unusedReg >= 0)
972 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
973
Chris Lattner85c54652002-05-23 15:50:03 +0000974 return -1;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000975}
976
977
Brian Gaekeaf843702003-10-22 20:22:53 +0000978/// Return the unified register number of a register in class RC which is not
979/// used by any operands of MInst.
980///
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000981int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +0000982 const int RegType,
Chris Lattner85c54652002-05-23 15:50:03 +0000983 const MachineInstr *MInst) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000984 RC->clearColorsUsed();
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000985
Vikram S. Advebc001b22003-07-25 21:06:09 +0000986 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000987
Vikram S. Advebc001b22003-07-25 21:06:09 +0000988 // find the first unused color
989 int unusedReg = RC->getUnusedColor(RegType);
990 assert(unusedReg >= 0 &&
991 "FATAL: No free register could be found in reg class!!");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000992
Vikram S. Advebc001b22003-07-25 21:06:09 +0000993 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000994}
995
996
Brian Gaekeaf843702003-10-22 20:22:53 +0000997/// Modify the IsColorUsedArr of register class RC, by setting the bits
998/// corresponding to register RegNo. This is a helper method of
999/// setRelRegsUsedByThisInst().
1000///
Chris Lattner3bed95b2003-08-05 21:55:58 +00001001static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
Brian Gaeke498231b2004-06-03 02:45:09 +00001002 const SparcV9RegInfo &TRI) {
Chris Lattner3bed95b2003-08-05 21:55:58 +00001003 unsigned classId = 0;
1004 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1005 if (RC->getID() == classId)
1006 RC->markColorsUsed(classRegNum, RegType, RegType);
1007}
1008
1009void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
Brian Gaekeaf843702003-10-22 20:22:53 +00001010 const MachineInstr *MI) {
Chris Lattner3bed95b2003-08-05 21:55:58 +00001011 assert(OperandsColoredMap[MI] == true &&
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001012 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1013 "are marked for an instruction.");
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001014
Brian Gaekeaf843702003-10-22 20:22:53 +00001015 // Add the registers already marked as used by the instruction. Both
1016 // explicit and implicit operands are set.
Chris Lattner3bed95b2003-08-05 21:55:58 +00001017 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1018 if (MI->getOperand(i).hasAllocatedReg())
Alkis Evlogimenosbe766c72004-02-13 21:01:20 +00001019 markRegisterUsed(MI->getOperand(i).getReg(), RC, RegType,MRI);
Chris Lattner3bed95b2003-08-05 21:55:58 +00001020
1021 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1022 if (MI->getImplicitOp(i).hasAllocatedReg())
Alkis Evlogimenosbe766c72004-02-13 21:01:20 +00001023 markRegisterUsed(MI->getImplicitOp(i).getReg(), RC, RegType,MRI);
Chris Lattner3bed95b2003-08-05 21:55:58 +00001024
Chris Lattner3fd1f5b2003-08-05 22:11:13 +00001025 // Add all of the scratch registers that are used to save values across the
1026 // instruction (e.g., for saving state register values).
1027 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1028 IR = ScratchRegsUsed.equal_range(MI);
1029 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1030 markRegisterUsed(I->second, RC, RegType, MRI);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001031
Vikram S. Advef5af6362002-07-08 23:15:32 +00001032 // If there are implicit references, mark their allocated regs as well
Chris Lattner3bed95b2003-08-05 21:55:58 +00001033 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
Vikram S. Advef5af6362002-07-08 23:15:32 +00001034 if (const LiveRange*
Brian Gaeke4efe3422003-09-21 01:23:46 +00001035 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
Vikram S. Advef5af6362002-07-08 23:15:32 +00001036 if (LRofImpRef->hasColor())
1037 // this implicit reference is in a LR that received a color
Vikram S. Advebc001b22003-07-25 21:06:09 +00001038 RC->markColorsUsed(LRofImpRef->getColor(),
1039 MRI.getRegTypeForLR(LRofImpRef), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001040}
1041
1042
Brian Gaekeaf843702003-10-22 20:22:53 +00001043/// If there are delay slots for an instruction, the instructions added after
1044/// it must really go after the delayed instruction(s). So, we Move the
1045/// InstrAfter of that instruction to the corresponding delayed instruction
1046/// using the following method.
1047///
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001048void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1049 const MachineInstr *DelayedMI)
1050{
Vikram S. Advefeb32982003-08-12 22:22:24 +00001051 // "added after" instructions of the original instr
1052 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1053
1054 if (DEBUG_RA && OrigAft.size() > 0) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001055 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1056 std::cerr << " to last delay slot instrn: " << *DelayedMI;
Vikram S. Adve814030a2003-07-29 19:49:21 +00001057 }
1058
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001059 // "added after" instructions of the delayed instr
Vikram S. Adve814030a2003-07-29 19:49:21 +00001060 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001061
1062 // go thru all the "added after instructions" of the original instruction
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001063 // and append them to the "added after instructions" of the delayed
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001064 // instructions
Chris Lattner697954c2002-01-20 22:54:45 +00001065 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001066
1067 // empty the "added after instructions" of the original instruction
1068 OrigAft.clear();
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001069}
Ruchira Sasanka0931a012001-09-15 19:06:58 +00001070
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001071
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001072void PhyRegAlloc::colorIncomingArgs()
1073{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001074 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
Vikram S. Adve814030a2003-07-29 19:49:21 +00001075 AddedInstrAtEntry.InstrnsAfter);
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001076}
1077
Ruchira Sasankae727f852001-09-18 22:43:57 +00001078
Brian Gaekeaf843702003-10-22 20:22:53 +00001079/// Determine whether the suggested color of each live range is really usable,
1080/// and then call its setSuggestedColorUsable() method to record the answer. A
1081/// suggested color is NOT usable when the suggested color is volatile AND
1082/// when there are call interferences.
1083///
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001084void PhyRegAlloc::markUnusableSugColors()
1085{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001086 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1087 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001088
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001089 for (; HMI != HMIEnd ; ++HMI ) {
1090 if (HMI->first) {
1091 LiveRange *L = HMI->second; // get the LiveRange
Brian Gaeke59b1c562003-09-24 17:50:28 +00001092 if (L && L->hasSuggestedColor ())
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001093 L->setSuggestedColorUsable
1094 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1095 && L->isCallInterference ()));
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001096 }
1097 } // for all LR's in hash map
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001098}
1099
1100
Brian Gaekeaf843702003-10-22 20:22:53 +00001101/// For each live range that is spilled, allocates a new spill position on the
1102/// stack, and set the stack offsets of the live range that will be spilled to
1103/// that position. This must be called just after coloring the LRs.
1104///
Chris Lattner37730942002-02-05 03:52:29 +00001105void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001106 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001107
Brian Gaeke4efe3422003-09-21 01:23:46 +00001108 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1109 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001110
Chris Lattner7e708292002-06-25 16:13:24 +00001111 for ( ; HMI != HMIEnd ; ++HMI) {
Chris Lattner37730942002-02-05 03:52:29 +00001112 if (HMI->first && HMI->second) {
Vikram S. Adve3bf08922003-07-10 19:42:55 +00001113 LiveRange *L = HMI->second; // get the LiveRange
1114 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
Brian Gaeke4efe3422003-09-21 01:23:46 +00001115 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001116 L->setSpillOffFromFP(stackOffset);
1117 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001118 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001119 << ": stack-offset = " << stackOffset << "\n";
1120 }
Chris Lattner37730942002-02-05 03:52:29 +00001121 }
1122 } // for all LR's in hash map
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001123}
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001124
Brian Gaeke874f4232003-09-21 02:50:21 +00001125
Brian Gaeke21390412003-11-10 00:05:26 +00001126void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
Brian Gaeke54a76b82004-03-08 23:22:02 +00001127 const Value *V, int Insn, int Opnd) {
Brian Gaeke21390412003-11-10 00:05:26 +00001128 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V);
1129 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();
1130 AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated;
1131 int Placement = -1;
1132 if ((HMI != HMIEnd) && HMI->second) {
1133 LiveRange *L = HMI->second;
1134 assert ((L->hasColor () || L->isMarkedForSpill ())
1135 && "Live range exists but not colored or spilled");
1136 if (L->hasColor ()) {
1137 AllocState = AllocInfo::Allocated;
1138 Placement = MRI.getUnifiedRegNum (L->getRegClassID (),
1139 L->getColor ());
1140 } else if (L->isMarkedForSpill ()) {
1141 AllocState = AllocInfo::Spilled;
1142 assert (L->hasSpillOffset ()
1143 && "Live range marked for spill but has no spill offset");
1144 Placement = L->getSpillOffFromFP ();
1145 }
1146 }
1147 state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement));
1148}
1149
1150
Brian Gaekeaf843702003-10-22 20:22:53 +00001151/// Save the global register allocation decisions made by the register
1152/// allocator so that they can be accessed later (sort of like "poor man's
1153/// debug info").
1154///
1155void PhyRegAlloc::saveState () {
Brian Gaeke537132b2003-10-23 20:32:55 +00001156 std::vector<AllocInfo> &state = FnAllocState[Fn];
Brian Gaeke54a76b82004-03-08 23:22:02 +00001157 unsigned ArgNum = 0;
1158 // Arguments encoded as instruction # -1
1159 for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1160 const Argument *Arg = &*i;
1161 saveStateForValue (state, Arg, -1, ArgNum);
1162 ++ArgNum;
1163 }
Brian Gaeke25d4b542004-05-30 07:08:43 +00001164 unsigned InstCount = 0;
Brian Gaeke54a76b82004-03-08 23:22:02 +00001165 // Instructions themselves encoded as operand # -1
Brian Gaeke3ceac852003-10-30 21:21:33 +00001166 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
Brian Gaeke25d4b542004-05-30 07:08:43 +00001167 const Instruction *Inst = &*II;
1168 saveStateForValue (state, Inst, InstCount, -1);
1169 if (isa<PHINode> (Inst)) {
1170 MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get(Inst);
1171 // Last instr should be the copy...figure out what reg it is reading from
1172 if (Value *PhiCpRes = MCforPN.back()->getOperand(0).getVRegValueOrNull()){
1173 if (DEBUG_RA)
1174 std::cerr << "Found Phi copy result: " << PhiCpRes->getName()
1175 << " in: " << *MCforPN.back() << "\n";
1176 saveStateForValue (state, PhiCpRes, InstCount, -2);
1177 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001178 }
Brian Gaeke25d4b542004-05-30 07:08:43 +00001179 ++InstCount;
Brian Gaeke3ceac852003-10-30 21:21:33 +00001180 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001181}
1182
Brian Gaeke537132b2003-10-23 20:32:55 +00001183
Brian Gaekea7afac22004-05-30 04:22:24 +00001184/// Dump the saved state filled in by saveState() out to stderr. Only
1185/// used when debugging.
Brian Gaekeaf843702003-10-22 20:22:53 +00001186///
Brian Gaekea7afac22004-05-30 04:22:24 +00001187void PhyRegAlloc::dumpSavedState () {
Brian Gaeke3ceac852003-10-30 21:21:33 +00001188 std::vector<AllocInfo> &state = FnAllocState[Fn];
Brian Gaekecf68bd52004-03-11 06:45:52 +00001189 int ArgNum = 0;
1190 for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1191 const Argument *Arg = &*i;
1192 std::cerr << "Argument: " << *Arg << "\n"
1193 << "FnAllocState:\n";
1194 for (unsigned i = 0; i < state.size (); ++i) {
1195 AllocInfo &S = state[i];
1196 if (S.Instruction == -1 && S.Operand == ArgNum)
1197 std::cerr << " " << S << "\n";
1198 }
1199 std::cerr << "----------\n";
1200 ++ArgNum;
1201 }
Brian Gaeke54a76b82004-03-08 23:22:02 +00001202 int Insn = 0;
Brian Gaeke3ceac852003-10-30 21:21:33 +00001203 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00001204 const Instruction *I = &*II;
Brian Gaeke3ceac852003-10-30 21:21:33 +00001205 MachineCodeForInstruction &Instrs = MachineCodeForInstruction::get (I);
Brian Gaekecf68bd52004-03-11 06:45:52 +00001206 std::cerr << "Instruction: " << *I
Brian Gaeke3ceac852003-10-30 21:21:33 +00001207 << "MachineCodeForInstruction:\n";
1208 for (unsigned i = 0, n = Instrs.size (); i != n; ++i)
Brian Gaekecf68bd52004-03-11 06:45:52 +00001209 std::cerr << " " << *Instrs[i];
Brian Gaeke3ceac852003-10-30 21:21:33 +00001210 std::cerr << "FnAllocState:\n";
1211 for (unsigned i = 0; i < state.size (); ++i) {
1212 AllocInfo &S = state[i];
Brian Gaeke97374d42004-01-28 19:05:43 +00001213 if (Insn == S.Instruction)
1214 std::cerr << " " << S << "\n";
Brian Gaeke3ceac852003-10-30 21:21:33 +00001215 }
1216 std::cerr << "----------\n";
1217 ++Insn;
1218 }
Brian Gaekeaf843702003-10-22 20:22:53 +00001219}
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001220
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001221
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001222bool PhyRegAlloc::doFinalization (Module &M) {
Brian Gaekecf68bd52004-03-11 06:45:52 +00001223 if (SaveRegAllocState) finishSavingState (M);
1224 return false;
1225}
1226
1227
1228/// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1229/// Constant and stuffing it inside the Module.
1230///
1231/// FIXME: There should be other, better ways of storing the saved
1232/// state; this one is cumbersome and does not work well with the JIT.
1233///
1234void PhyRegAlloc::finishSavingState (Module &M) {
Brian Gaekec760d642004-03-11 19:46:30 +00001235 if (DEBUG_RA)
1236 std::cerr << "---- Saving reg. alloc state; SaveStateToModule = "
1237 << SaveStateToModule << " ----\n";
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001238
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001239 // If saving state into the module, just copy new elements to the
1240 // correct global.
Brian Gaeke8fc49342003-10-24 21:21:58 +00001241 if (!SaveStateToModule) {
1242 ExportedFnAllocState = FnAllocState;
Brian Gaekecce4e7a2003-11-04 18:25:56 +00001243 // FIXME: should ONLY copy new elements in FnAllocState
Brian Gaekecf68bd52004-03-11 06:45:52 +00001244 return;
Brian Gaeke8fc49342003-10-24 21:21:58 +00001245 }
1246
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001247 // Convert FnAllocState to a single Constant array and add it
1248 // to the Module.
1249 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1250 std::vector<const Type *> TV;
1251 TV.push_back (Type::UIntTy);
1252 TV.push_back (AT);
1253 PointerType *PT = PointerType::get (StructType::get (TV));
1254
1255 std::vector<Constant *> allstate;
1256 for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1257 Function *F = I;
Brian Gaeke55766e12003-11-04 22:42:41 +00001258 if (F->isExternal ()) continue;
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001259 if (FnAllocState.find (F) == FnAllocState.end ()) {
1260 allstate.push_back (ConstantPointerNull::get (PT));
1261 } else {
Brian Gaeke537132b2003-10-23 20:32:55 +00001262 std::vector<AllocInfo> &state = FnAllocState[F];
Brian Gaeke60a3c552003-10-22 20:44:23 +00001263
1264 // Convert state into an LLVM ConstantArray, and put it in a
1265 // ConstantStruct (named S) along with its size.
Brian Gaeke537132b2003-10-23 20:32:55 +00001266 std::vector<Constant *> stateConstants;
1267 for (unsigned i = 0, s = state.size (); i != s; ++i)
1268 stateConstants.push_back (state[i].toConstant ());
1269 unsigned Size = stateConstants.size ();
Brian Gaeke60a3c552003-10-22 20:44:23 +00001270 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1271 std::vector<const Type *> TV;
1272 TV.push_back (Type::UIntTy);
1273 TV.push_back (AT);
1274 StructType *ST = StructType::get (TV);
1275 std::vector<Constant *> CV;
1276 CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
Brian Gaeke537132b2003-10-23 20:32:55 +00001277 CV.push_back (ConstantArray::get (AT, stateConstants));
Brian Gaeke60a3c552003-10-22 20:44:23 +00001278 Constant *S = ConstantStruct::get (ST, CV);
1279
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001280 GlobalVariable *GV =
Brian Gaeke60a3c552003-10-22 20:44:23 +00001281 new GlobalVariable (ST, true,
1282 GlobalValue::InternalLinkage, S,
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001283 F->getName () + ".regAllocState", &M);
Brian Gaeke60a3c552003-10-22 20:44:23 +00001284
Brian Gaeke21390412003-11-10 00:05:26 +00001285 // Have: { uint, [Size x { uint, int, uint, int }] } *
1286 // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
Reid Spencer518310c2004-07-18 00:44:37 +00001287 Constant *CE = ConstantExpr::getCast (GV, PT);
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001288 allstate.push_back (CE);
1289 }
1290 }
1291
1292 unsigned Size = allstate.size ();
1293 // Final structure type is:
Brian Gaeke21390412003-11-10 00:05:26 +00001294 // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001295 std::vector<const Type *> TV2;
1296 TV2.push_back (Type::UIntTy);
1297 ArrayType *AT2 = ArrayType::get (PT, Size);
1298 TV2.push_back (AT2);
1299 StructType *ST2 = StructType::get (TV2);
1300 std::vector<Constant *> CV2;
1301 CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1302 CV2.push_back (ConstantArray::get (AT2, allstate));
Brian Gaekee9414ca2003-11-10 07:12:01 +00001303 new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001304 ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1305 &M);
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001306}
1307
1308
Brian Gaekeaf843702003-10-22 20:22:53 +00001309/// Allocate registers for the machine code previously generated for F using
1310/// the graph-coloring algorithm.
1311///
Brian Gaeke4efe3422003-09-21 01:23:46 +00001312bool PhyRegAlloc::runOnFunction (Function &F) {
1313 if (DEBUG_RA)
1314 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1315
1316 Fn = &F;
1317 MF = &MachineFunction::get (Fn);
1318 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1319 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1320 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1321
1322 // Create each RegClass for the target machine and add it to the
1323 // RegClassList. This must be done before calling constructLiveRanges().
1324 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
Chris Lattnerd029cd22004-06-02 05:55:25 +00001325 RegClassList.push_back (new RegClass (Fn, TM.getRegInfo(),
1326 MRI.getMachineRegClass(rc)));
Brian Gaeke4efe3422003-09-21 01:23:46 +00001327
1328 LRI->constructLiveRanges(); // create LR info
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001329 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
Brian Gaeke4efe3422003-09-21 01:23:46 +00001330 LRI->printLiveRanges();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001331
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001332 createIGNodeListsAndIGs(); // create IGNode list and IGs
1333
1334 buildInterferenceGraphs(); // build IGs in all reg classes
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001335
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001336 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001337 // print all LRs in all reg classes
Chris Lattner7e708292002-06-25 16:13:24 +00001338 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1339 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001340
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001341 // print IGs in all register classes
Chris Lattner7e708292002-06-25 16:13:24 +00001342 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1343 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001344 }
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001345
Brian Gaeke4efe3422003-09-21 01:23:46 +00001346 LRI->coalesceLRs(); // coalesce all live ranges
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +00001347
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001348 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001349 // print all LRs in all reg classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001350 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1351 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001352
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001353 // print IGs in all register classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001354 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1355 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001356 }
1357
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001358 // mark un-usable suggested color before graph coloring algorithm.
1359 // When this is done, the graph coloring algo will not reserve
1360 // suggested color unnecessarily - they can be used by another LR
1361 markUnusableSugColors();
1362
1363 // color all register classes using the graph coloring algo
Chris Lattner7e708292002-06-25 16:13:24 +00001364 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerf726e772002-10-28 19:22:04 +00001365 RegClassList[rc]->colorAllRegs();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001366
Misha Brukman37f92e22003-09-11 22:34:13 +00001367 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1368 // a position for such spilled LRs
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001369 allocateStackSpace4SpilledLRs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001370
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001371 // Reset the temp. area on the stack before use by the first instruction.
1372 // This will also happen after updating each instruction.
Brian Gaeke4efe3422003-09-21 01:23:46 +00001373 MF->getInfo()->popAllTempValues();
Ruchira Sasankaf90870f2001-11-15 22:02:06 +00001374
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001375 // color incoming args - if the correct color was not received
1376 // insert code to copy to the correct register
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001377 colorIncomingArgs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001378
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001379 // Save register allocation state for this function in a Constant.
Brian Gaeke14068d92004-03-10 22:01:59 +00001380 if (SaveRegAllocState) {
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001381 saveState();
Brian Gaekeaf843702003-10-22 20:22:53 +00001382 }
Brian Gaeke6a256cc2003-09-24 18:08:54 +00001383
Brian Gaeke60a3c552003-10-22 20:44:23 +00001384 // Now update the machine code with register names and add any additional
1385 // code inserted by the register allocator to the instruction stream.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001386 updateMachineCode();
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001387
Brian Gaekea7afac22004-05-30 04:22:24 +00001388 if (SaveRegAllocState) {
1389 if (DEBUG_RA) // Check our work.
1390 dumpSavedState ();
1391 if (!SaveStateToModule)
1392 finishSavingState (const_cast<Module&> (*Fn->getParent ()));
1393 }
1394
Chris Lattner045e7c82001-09-19 16:26:23 +00001395 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001396 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
Brian Gaeke4efe3422003-09-21 01:23:46 +00001397 MF->dump();
Chris Lattner045e7c82001-09-19 16:26:23 +00001398 }
Brian Gaeke4efe3422003-09-21 01:23:46 +00001399
1400 // Tear down temporary data structures
1401 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1402 delete RegClassList[rc];
1403 RegClassList.clear ();
1404 AddedInstrMap.clear ();
1405 OperandsColoredMap.clear ();
1406 ScratchRegsUsed.clear ();
1407 AddedInstrAtEntry.clear ();
1408 delete LRI;
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001409
Brian Gaeke4efe3422003-09-21 01:23:46 +00001410 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1411 return false; // Function was not modified
1412}
Brian Gaeked0fde302003-11-11 22:41:34 +00001413
1414} // End llvm namespace