1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Traditional graph-coloring global register allocator currently used
11 // by the SPARC back-end.
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.
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.
21 //===----------------------------------------------------------------------===//
23 #include "AllocInfo.h"
25 #include "PhyRegAlloc.h"
26 #include "RegAllocCommon.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/iOther.h"
31 #include "llvm/Module.h"
32 #include "llvm/Type.h"
33 #include "llvm/Analysis/LoopInfo.h"
34 #include "llvm/CodeGen/FunctionLiveVarInfo.h"
35 #include "llvm/CodeGen/InstrSelection.h"
36 #include "llvm/CodeGen/MachineCodeForInstruction.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionInfo.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineInstrAnnot.h"
42 #include "llvm/CodeGen/Passes.h"
43 #include "llvm/Support/InstIterator.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "Support/CommandLine.h"
46 #include "Support/SetOperations.h"
47 #include "Support/STLExtras.h"
52 RegAllocDebugLevel_t DEBUG_RA;
54 /// The reoptimizer wants to be able to grovel through the register
55 /// allocator's state after it has done its job. This is a hack.
57 PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
58 const bool SaveStateToModule = true;
60 static cl::opt<RegAllocDebugLevel_t, true>
61 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
62 cl::desc("enable register allocation debugging information"),
64 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
65 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
66 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
67 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
68 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
69 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
73 SaveRegAllocState("save-ra-state", cl::Hidden,
74 cl::desc("write reg. allocator state into module"));
76 FunctionPass *getRegisterAllocator(TargetMachine &T) {
77 return new PhyRegAlloc (T);
80 void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
81 AU.addRequired<LoopInfo> ();
82 AU.addRequired<FunctionLiveVarInfo> ();
86 /// Initialize interference graphs (one in each reg class) and IGNodeLists
87 /// (one in each IG). The actual nodes will be pushed later.
89 void PhyRegAlloc::createIGNodeListsAndIGs() {
90 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
92 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
93 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
95 for (; HMI != HMIEnd ; ++HMI ) {
97 LiveRange *L = HMI->second; // get the LiveRange
100 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
101 << RAV(HMI->first) << "****\n";
105 // if the Value * is not null, and LR is not yet written to the IGNodeList
106 if (!(L->getUserIGNode()) ) {
107 RegClass *const RC = // RegClass of first value in the LR
108 RegClassList[ L->getRegClassID() ];
109 RC->addLRToIG(L); // add this LR to an IG
115 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
116 RegClassList[rc]->createInterferenceGraph();
118 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
122 /// Add all interferences for a given instruction. Interference occurs only
123 /// if the LR of Def (Inst or Arg) is of the same reg class as that of live
124 /// var. The live var passed to this function is the LVset AFTER the
127 void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
129 ValueSet::const_iterator LIt = LVSet->begin();
131 // get the live range of instruction
132 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
134 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
135 assert( IGNodeOfDef );
137 RegClass *const RCOfDef = LROfDef->getRegClass();
139 // for each live var in live variable set
140 for ( ; LIt != LVSet->end(); ++LIt) {
142 if (DEBUG_RA >= RA_DEBUG_Verbose)
143 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
145 // get the live range corresponding to live var
146 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
148 // LROfVar can be null if it is a const since a const
149 // doesn't have a dominating def - see Assumptions above
151 if (LROfDef != LROfVar) // do not set interf for same LR
152 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
153 RCOfDef->setInterference( LROfDef, LROfVar);
158 /// For a call instruction, this method sets the CallInterference flag in
159 /// the LR of each variable live in the Live Variable Set live after the
160 /// call instruction (except the return value of the call instruction - since
161 /// the return value does not interfere with that call itself).
163 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
164 const ValueSet *LVSetAft) {
165 if (DEBUG_RA >= RA_DEBUG_Interference)
166 std::cerr << "\n For call inst: " << *MInst;
168 // for each live var in live variable set after machine inst
169 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
170 LIt != LEnd; ++LIt) {
172 // get the live range corresponding to live var
173 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
175 // LR can be null if it is a const since a const
176 // doesn't have a dominating def - see Assumptions above
178 if (DEBUG_RA >= RA_DEBUG_Interference) {
179 std::cerr << "\n\tLR after Call: ";
182 LR->setCallInterference();
183 if (DEBUG_RA >= RA_DEBUG_Interference) {
184 std::cerr << "\n ++After adding call interference for LR: " ;
191 // Now find the LR of the return value of the call
192 // We do this because, we look at the LV set *after* the instruction
193 // to determine, which LRs must be saved across calls. The return value
194 // of the call is live in this set - but it does not interfere with call
195 // (i.e., we can allocate a volatile register to the return value)
196 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
198 if (const Value *RetVal = argDesc->getReturnValue()) {
199 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
200 assert( RetValLR && "No LR for RetValue of call");
201 RetValLR->clearCallInterference();
204 // If the CALL is an indirect call, find the LR of the function pointer.
205 // That has a call interference because it conflicts with outgoing args.
206 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
207 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
208 assert( AddrValLR && "No LR for indirect addr val of call");
209 AddrValLR->setCallInterference();
214 /// Create interferences in the IG of each RegClass, and calculate the spill
215 /// cost of each Live Range (it is done in this method to save another pass
218 void PhyRegAlloc::buildInterferenceGraphs() {
219 if (DEBUG_RA >= RA_DEBUG_Interference)
220 std::cerr << "Creating interference graphs ...\n";
222 unsigned BBLoopDepthCost;
223 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
225 const MachineBasicBlock &MBB = *BBI;
226 const BasicBlock *BB = MBB.getBasicBlock();
228 // find the 10^(loop_depth) of this BB
229 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
231 // get the iterator for machine instructions
232 MachineBasicBlock::const_iterator MII = MBB.begin();
234 // iterate over all the machine instructions in BB
235 for ( ; MII != MBB.end(); ++MII) {
236 const MachineInstr *MInst = *MII;
238 // get the LV set after the instruction
239 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
240 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
243 // set the isCallInterference flag of each live range which extends
244 // across this call instruction. This information is used by graph
245 // coloring algorithm to avoid allocating volatile colors to live ranges
246 // that span across calls (since they have to be saved/restored)
247 setCallInterferences(MInst, &LVSetAI);
250 // iterate over all MI operands to find defs
251 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
252 OpE = MInst->end(); OpI != OpE; ++OpI) {
253 if (OpI.isDef()) // create a new LR since def
254 addInterference(*OpI, &LVSetAI, isCallInst);
256 // Calculate the spill cost of each live range
257 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
258 if (LR) LR->addSpillCost(BBLoopDepthCost);
261 // Mark all operands of pseudo-instructions as interfering with one
262 // another. This must be done because pseudo-instructions may be
263 // expanded to multiple instructions by the assembler, so all the
264 // operands must get distinct registers.
265 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
266 addInterf4PseudoInstr(MInst);
268 // Also add interference for any implicit definitions in a machine
269 // instr (currently, only calls have this).
270 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
271 for (unsigned z=0; z < NumOfImpRefs; z++)
272 if (MInst->getImplicitOp(z).isDef())
273 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
275 } // for all machine instructions in BB
276 } // for all BBs in function
278 // add interferences for function arguments. Since there are no explicit
279 // defs in the function for args, we have to add them manually
280 addInterferencesForArgs();
282 if (DEBUG_RA >= RA_DEBUG_Interference)
283 std::cerr << "Interference graphs calculated!\n";
287 /// Mark all operands of the given MachineInstr as interfering with one
290 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
291 bool setInterf = false;
293 // iterate over MI operands to find defs
294 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
295 ItE = MInst->end(); It1 != ItE; ++It1) {
296 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
297 assert((LROfOp1 || It1.isDef()) && "No LR for Def in PSEUDO insruction");
299 MachineInstr::const_val_op_iterator It2 = It1;
300 for (++It2; It2 != ItE; ++It2) {
301 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
304 RegClass *RCOfOp1 = LROfOp1->getRegClass();
305 RegClass *RCOfOp2 = LROfOp2->getRegClass();
307 if (RCOfOp1 == RCOfOp2 ){
308 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
312 } // for all other defs in machine instr
313 } // for all operands in an instruction
315 if (!setInterf && MInst->getNumOperands() > 2) {
316 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
318 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
323 /// Add interferences for incoming arguments to a function.
325 void PhyRegAlloc::addInterferencesForArgs() {
326 // get the InSet of root BB
327 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
329 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
330 // add interferences between args and LVars at start
331 addInterference(AI, &InSet, false);
333 if (DEBUG_RA >= RA_DEBUG_Interference)
334 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
339 /// The following are utility functions used solely by updateMachineCode and
340 /// the functions that it calls. They should probably be folded back into
341 /// updateMachineCode at some point.
344 // used by: updateMachineCode (1 time), PrependInstructions (1 time)
345 inline void InsertBefore(MachineInstr* newMI, MachineBasicBlock& MBB,
346 MachineBasicBlock::iterator& MII) {
347 MII = MBB.insert(MII, newMI);
351 // used by: AppendInstructions (1 time)
352 inline void InsertAfter(MachineInstr* newMI, MachineBasicBlock& MBB,
353 MachineBasicBlock::iterator& MII) {
354 ++MII; // insert before the next instruction
355 MII = MBB.insert(MII, newMI);
358 // used by: updateMachineCode (1 time)
359 inline void DeleteInstruction(MachineBasicBlock& MBB,
360 MachineBasicBlock::iterator& MII) {
361 MII = MBB.erase(MII);
364 // used by: updateMachineCode (1 time)
365 inline void SubstituteInPlace(MachineInstr* newMI, MachineBasicBlock& MBB,
366 MachineBasicBlock::iterator MII) {
370 // used by: updateMachineCode (2 times)
371 inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
372 MachineBasicBlock& MBB,
373 MachineBasicBlock::iterator& MII,
374 const std::string& msg) {
376 MachineInstr* OrigMI = *MII;
377 std::vector<MachineInstr *>::iterator AdIt;
378 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
380 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
381 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
383 InsertBefore(*AdIt, MBB, MII);
388 // used by: updateMachineCode (1 time)
389 inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
390 MachineBasicBlock& MBB,
391 MachineBasicBlock::iterator& MII,
392 const std::string& msg) {
394 MachineInstr* OrigMI = *MII;
395 std::vector<MachineInstr *>::iterator AdIt;
396 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
398 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
399 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
401 InsertAfter(*AdIt, MBB, MII);
406 /// Set the registers for operands in the given MachineInstr, if a register was
407 /// successfully allocated. Return true if any of its operands has been marked
410 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
412 bool instrNeedsSpills = false;
414 // First, set the registers for operands in the machine instruction
415 // if a register was successfully allocated. Do this first because we
416 // will need to know which registers are already used by this instr'n.
417 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
418 MachineOperand& Op = MInst->getOperand(OpNum);
419 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
420 Op.getType() == MachineOperand::MO_CCRegister) {
421 const Value *const Val = Op.getVRegValue();
422 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
423 // Remember if any operand needs spilling
424 instrNeedsSpills |= LR->isMarkedForSpill();
426 // An operand may have a color whether or not it needs spilling
428 MInst->SetRegForOperand(OpNum,
429 MRI.getUnifiedRegNum(LR->getRegClassID(),
433 } // for each operand
435 return instrNeedsSpills;
438 /// Mark allocated registers (using markAllocatedRegs()) on the instruction
439 /// that MII points to. Then, if it's a call instruction, insert caller-saving
440 /// code before and after it. Finally, insert spill code before and after it,
441 /// using insertCode4SpilledLR().
443 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
444 MachineBasicBlock &MBB) {
445 MachineInstr* MInst = *MII;
446 unsigned Opcode = MInst->getOpCode();
448 // Reset tmp stack positions so they can be reused for each machine instr.
449 MF->getInfo()->popAllTempValues();
451 // Mark the operands for which regs have been allocated.
452 bool instrNeedsSpills = markAllocatedRegs(*MII);
455 // Mark that the operands have been updated. Later,
456 // setRelRegsUsedByThisInst() is called to find registers used by each
457 // MachineInst, and it should not be used for an instruction until
458 // this is done. This flag just serves as a sanity check.
459 OperandsColoredMap[MInst] = true;
462 // Now insert caller-saving code before/after the call.
463 // Do this before inserting spill code since some registers must be
464 // used by save/restore and spill code should not use those registers.
465 if (TM.getInstrInfo().isCall(Opcode)) {
466 AddedInstrns &AI = AddedInstrMap[MInst];
467 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
468 MBB.getBasicBlock());
471 // Now insert spill code for remaining operands not allocated to
472 // registers. This must be done even for call return instructions
473 // since those are not handled by the special code above.
474 if (instrNeedsSpills)
475 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
476 MachineOperand& Op = MInst->getOperand(OpNum);
477 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
478 Op.getType() == MachineOperand::MO_CCRegister) {
479 const Value* Val = Op.getVRegValue();
480 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
481 if (LR->isMarkedForSpill())
482 insertCode4SpilledLR(LR, MII, MBB, OpNum);
484 } // for each operand
487 /// Iterate over all the MachineBasicBlocks in the current function and set
488 /// the allocated registers for each instruction (using updateInstruction()),
489 /// after register allocation is complete. Then move code out of delay slots.
491 void PhyRegAlloc::updateMachineCode()
493 // Insert any instructions needed at method entry
494 MachineBasicBlock::iterator MII = MF->front().begin();
495 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
496 "At function entry: \n");
497 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
498 "InstrsAfter should be unnecessary since we are just inserting at "
499 "the function entry point here.");
501 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
503 MachineBasicBlock &MBB = *BBI;
505 // Iterate over all machine instructions in BB and mark operands with
506 // their assigned registers or insert spill code, as appropriate.
507 // Also, fix operands of call/return instructions.
508 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
509 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
510 updateInstruction(MII, MBB);
512 // Now, move code out of delay slots of branches and returns if needed.
513 // (Also, move "after" code from calls to the last delay slot instruction.)
514 // Moving code out of delay slots is needed in 2 situations:
515 // (1) If this is a branch and it needs instructions inserted after it,
516 // move any existing instructions out of the delay slot so that the
517 // instructions can go into the delay slot. This only supports the
518 // case that #instrsAfter <= #delay slots.
520 // (2) If any instruction in the delay slot needs
521 // instructions inserted, move it out of the delay slot and before the
522 // branch because putting code before or after it would be VERY BAD!
524 // If the annul bit of the branch is set, neither of these is legal!
525 // If so, we need to handle spill differently but annulling is not yet used.
526 for (MachineBasicBlock::iterator MII = MBB.begin();
527 MII != MBB.end(); ++MII)
528 if (unsigned delaySlots =
529 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode())) {
530 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
532 // Check the 2 conditions above:
533 // (1) Does a branch need instructions added after it?
534 // (2) O/w does delay slot instr. need instrns before or after?
535 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
536 TM.getInstrInfo().isReturn(MInst->getOpCode()));
537 bool cond1 = (isBranch &&
538 AddedInstrMap.count(MInst) &&
539 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
540 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
541 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
542 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
544 if (cond1 || cond2) {
545 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
546 "FIXME: Moving an annulled delay slot instruction!");
547 assert(delaySlots==1 &&
548 "InsertBefore does not yet handle >1 delay slots!");
549 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
551 // In case (1), delete it and don't replace with anything!
552 // Otherwise (i.e., case (2) only) replace it with a NOP.
554 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
555 --MII; // reset MII for ++MII of loop
558 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
559 MBB, MII+1); // replace with NOP
562 std::cerr << "\nRegAlloc: Moved instr. with added code: "
564 << " out of delay slots of instr: " << *MInst;
568 // For non-branch instr with delay slots (probably a call), move
569 // InstrAfter to the instr. in the last delay slot.
570 move2DelayedInstr(*MII, *(MII+delaySlots));
573 // Finally iterate over all instructions in BB and insert before/after
574 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
575 MachineInstr *MInst = *MII;
577 // do not process Phis
578 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
581 // if there are any added instructions...
582 if (AddedInstrMap.count(MInst)) {
583 AddedInstrns &CallAI = AddedInstrMap[MInst];
586 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
587 TM.getInstrInfo().isReturn(MInst->getOpCode()));
589 AddedInstrMap[MInst].InstrnsAfter.size() <=
590 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
591 "Cannot put more than #delaySlots instrns after "
592 "branch or return! Need to handle temps differently.");
596 // Temporary sanity checking code to detect whether the same machine
597 // instruction is ever inserted twice before/after a call.
598 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
599 std::set<const MachineInstr*> instrsSeen;
600 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
601 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
602 "Duplicate machine instruction in InstrnsBefore!");
603 instrsSeen.insert(CallAI.InstrnsBefore[i]);
605 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
606 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
607 "Duplicate machine instruction in InstrnsBefore/After!");
608 instrsSeen.insert(CallAI.InstrnsAfter[i]);
612 // Now add the instructions before/after this MI.
613 // We do this here to ensure that spill for an instruction is inserted
614 // as close as possible to an instruction (see above insertCode4Spill)
615 if (! CallAI.InstrnsBefore.empty())
616 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
618 if (! CallAI.InstrnsAfter.empty())
619 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
621 } // if there are any added instructions
622 } // for each machine instruction
627 /// Insert spill code for AN operand whose LR was spilled. May be called
628 /// repeatedly for a single MachineInstr if it has many spilled operands. On
629 /// each call, it finds a register which is not live at that instruction and
630 /// also which is not used by other spilled operands of the same
631 /// instruction. Then it uses this register temporarily to accommodate the
634 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
635 MachineBasicBlock::iterator& MII,
636 MachineBasicBlock &MBB,
637 const unsigned OpNum) {
638 MachineInstr *MInst = *MII;
639 const BasicBlock *BB = MBB.getBasicBlock();
641 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
642 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
643 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
644 "Return value of a ret must be handled elsewhere");
646 MachineOperand& Op = MInst->getOperand(OpNum);
647 bool isDef = Op.isDef();
648 bool isUse = Op.isUse();
649 unsigned RegType = MRI.getRegTypeForLR(LR);
650 int SpillOff = LR->getSpillOffFromFP();
651 RegClass *RC = LR->getRegClass();
653 // Get the live-variable set to find registers free before this instr.
654 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
657 // If this instr. is in the delay slot of a branch or return, we need to
658 // include all live variables before that branch or return -- we don't want to
659 // trample those! Verify that the set is included in the LV set before MInst.
660 if (MII != MBB.begin()) {
661 MachineInstr *PredMI = *(MII-1);
662 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
663 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
664 .empty() && "Live-var set before branch should be included in "
665 "live-var set of each delay slot instruction!");
669 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
671 std::vector<MachineInstr*> MIBef, MIAft;
672 std::vector<MachineInstr*> AdIMid;
674 // Choose a register to hold the spilled value, if one was not preallocated.
675 // This may insert code before and after MInst to free up the value. If so,
676 // this code should be first/last in the spill sequence before/after MInst.
677 int TmpRegU=(LR->hasColor()
678 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
679 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
681 // Set the operand first so that it this register does not get used
682 // as a scratch register for later calls to getUsableUniRegAtMI below
683 MInst->SetRegForOperand(OpNum, TmpRegU);
685 // get the added instructions for this instruction
686 AddedInstrns &AI = AddedInstrMap[MInst];
688 // We may need a scratch register to copy the spilled value to/from memory.
689 // This may itself have to insert code to free up a scratch register.
690 // Any such code should go before (after) the spill code for a load (store).
691 // The scratch reg is not marked as used because it is only used
692 // for the copy and not used across MInst.
693 int scratchRegType = -1;
695 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
696 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
697 MInst, MIBef, MIAft);
698 assert(scratchReg != MRI.getInvalidRegNum());
702 // for a USE, we have to load the value of LR from stack to a TmpReg
703 // and use the TmpReg as one operand of instruction
705 // actual loading instruction(s)
706 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
707 RegType, scratchReg);
709 // the actual load should be after the instructions to free up TmpRegU
710 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
714 if (isDef) { // if this is a Def
715 // for a DEF, we have to store the value produced by this instruction
716 // on the stack position allocated for this LR
718 // actual storing instruction(s)
719 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
720 RegType, scratchReg);
722 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
725 // Finally, insert the entire spill code sequences before/after MInst
726 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
727 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
730 std::cerr << "\nFor Inst:\n " << *MInst;
731 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
732 std::cerr << "; added Instructions:";
733 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
734 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
739 /// Insert caller saving/restoring instructions before/after a call machine
740 /// instruction (before or after any other instructions that were inserted for
744 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
745 std::vector<MachineInstr*> &instrnsAfter,
746 MachineInstr *CallMI,
747 const BasicBlock *BB) {
748 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
750 // hash set to record which registers were saved/restored
751 hash_set<unsigned> PushedRegSet;
753 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
755 // if the call is to a instrumentation function, do not insert save and
756 // restore instructions the instrumentation function takes care of save
757 // restore for volatile regs.
759 // FIXME: this should be made general, not specific to the reoptimizer!
760 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
761 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
763 // Now check if the call has a return value (using argDesc) and if so,
764 // find the LR of the TmpInstruction representing the return value register.
765 // (using the last or second-last *implicit operand* of the call MI).
766 // Insert it to to the PushedRegSet since we must not save that register
767 // and restore it after the call.
768 // We do this because, we look at the LV set *after* the instruction
769 // to determine, which LRs must be saved across calls. The return value
770 // of the call is live in this set - but we must not save/restore it.
771 if (const Value *origRetVal = argDesc->getReturnValue()) {
772 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
773 (argDesc->getIndirectFuncPtr()? 1 : 2));
774 const TmpInstruction* tmpRetVal =
775 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
776 assert(tmpRetVal->getOperand(0) == origRetVal &&
777 tmpRetVal->getType() == origRetVal->getType() &&
778 "Wrong implicit ref?");
779 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
780 assert(RetValLR && "No LR for RetValue of call");
782 if (! RetValLR->isMarkedForSpill())
783 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
784 RetValLR->getColor()));
787 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
788 ValueSet::const_iterator LIt = LVSetAft.begin();
790 // for each live var in live variable set after machine inst
791 for( ; LIt != LVSetAft.end(); ++LIt) {
792 // get the live range corresponding to live var
793 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
795 // LR can be null if it is a const since a const
796 // doesn't have a dominating def - see Assumptions above
798 if (! LR->isMarkedForSpill()) {
799 assert(LR->hasColor() && "LR is neither spilled nor colored?");
800 unsigned RCID = LR->getRegClassID();
801 unsigned Color = LR->getColor();
803 if (MRI.isRegVolatile(RCID, Color) ) {
804 // if this is a call to the first-level reoptimizer
805 // instrumentation entry point, and the register is not
806 // modified by call, don't save and restore it.
807 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
810 // if the value is in both LV sets (i.e., live before and after
811 // the call machine instruction)
812 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
814 // if we haven't already pushed this register...
815 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
816 unsigned RegType = MRI.getRegTypeForLR(LR);
818 // Now get two instructions - to push on stack and pop from stack
819 // and add them to InstrnsBefore and InstrnsAfter of the
822 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
824 //---- Insert code for pushing the reg on stack ----------
826 std::vector<MachineInstr*> AdIBef, AdIAft;
828 // We may need a scratch register to copy the saved value
829 // to/from memory. This may itself have to insert code to
830 // free up a scratch register. Any such code should go before
831 // the save code. The scratch register, if any, is by default
832 // temporary and not "used" by the instruction unless the
833 // copy code itself decides to keep the value in the scratch reg.
834 int scratchRegType = -1;
836 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
837 { // Find a register not live in the LVSet before CallMI
838 const ValueSet &LVSetBef =
839 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
840 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
841 CallMI, AdIBef, AdIAft);
842 assert(scratchReg != MRI.getInvalidRegNum());
845 if (AdIBef.size() > 0)
846 instrnsBefore.insert(instrnsBefore.end(),
847 AdIBef.begin(), AdIBef.end());
849 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
850 StackOff, RegType, scratchReg);
852 if (AdIAft.size() > 0)
853 instrnsBefore.insert(instrnsBefore.end(),
854 AdIAft.begin(), AdIAft.end());
856 //---- Insert code for popping the reg from the stack ----------
860 // We may need a scratch register to copy the saved value
861 // from memory. This may itself have to insert code to
862 // free up a scratch register. Any such code should go
863 // after the save code. As above, scratch is not marked "used".
866 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
867 { // Find a register not live in the LVSet after CallMI
868 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
869 CallMI, AdIBef, AdIAft);
870 assert(scratchReg != MRI.getInvalidRegNum());
873 if (AdIBef.size() > 0)
874 instrnsAfter.insert(instrnsAfter.end(),
875 AdIBef.begin(), AdIBef.end());
877 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
878 Reg, RegType, scratchReg);
880 if (AdIAft.size() > 0)
881 instrnsAfter.insert(instrnsAfter.end(),
882 AdIAft.begin(), AdIAft.end());
884 PushedRegSet.insert(Reg);
887 std::cerr << "\nFor call inst:" << *CallMI;
888 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
889 for_each(instrnsBefore.begin(), instrnsBefore.end(),
890 std::mem_fun(&MachineInstr::dump));
891 std::cerr << " -and After:\n\t ";
892 for_each(instrnsAfter.begin(), instrnsAfter.end(),
893 std::mem_fun(&MachineInstr::dump));
895 } // if not already pushed
896 } // if LR has a volatile color
898 } // if there is a LR for Var
899 } // for each value in the LV set after instruction
903 /// Returns the unified register number of a temporary register to be used
904 /// BEFORE MInst. If no register is available, it will pick one and modify
905 /// MIBef and MIAft to contain instructions used to free up this returned
908 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
909 const ValueSet *LVSetBef,
911 std::vector<MachineInstr*>& MIBef,
912 std::vector<MachineInstr*>& MIAft) {
913 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
915 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
918 // we couldn't find an unused register. Generate code to free up a reg by
919 // saving it on stack and restoring after the instruction
921 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
923 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
925 // Check if we need a scratch register to copy this register to memory.
926 int scratchRegType = -1;
927 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
928 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
929 MInst, MIBef, MIAft);
930 assert(scratchReg != MRI.getInvalidRegNum());
932 // We may as well hold the value in the scratch register instead
933 // of copying it to memory and back. But we have to mark the
934 // register as used by this instruction, so it does not get used
935 // as a scratch reg. by another operand or anyone else.
936 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
937 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
938 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
939 } else { // the register can be copied directly to/from memory so do it.
940 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
941 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
949 /// Returns the register-class register number of a new unused register that
950 /// can be used to accommodate a temporary value. May be called repeatedly
951 /// for a single MachineInstr. On each call, it finds a register which is not
952 /// live at that instruction and which is not used by any spilled operands of
953 /// that instruction.
955 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
956 const MachineInstr *MInst,
957 const ValueSet* LVSetBef) {
958 RC->clearColorsUsed(); // Reset array
960 if (LVSetBef == NULL) {
961 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
962 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
965 ValueSet::const_iterator LIt = LVSetBef->begin();
967 // for each live var in live variable set after machine inst
968 for ( ; LIt != LVSetBef->end(); ++LIt) {
969 // Get the live range corresponding to live var, and its RegClass
970 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
972 // LR can be null if it is a const since a const
973 // doesn't have a dominating def - see Assumptions above
974 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
975 RC->markColorsUsed(LRofLV->getColor(),
976 MRI.getRegTypeForLR(LRofLV), RegType);
979 // It is possible that one operand of this MInst was already spilled
980 // and it received some register temporarily. If that's the case,
981 // it is recorded in machine operand. We must skip such registers.
982 setRelRegsUsedByThisInst(RC, RegType, MInst);
984 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
986 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
992 /// Return the unified register number of a register in class RC which is not
993 /// used by any operands of MInst.
995 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
997 const MachineInstr *MInst) {
998 RC->clearColorsUsed();
1000 setRelRegsUsedByThisInst(RC, RegType, MInst);
1002 // find the first unused color
1003 int unusedReg = RC->getUnusedColor(RegType);
1004 assert(unusedReg >= 0 &&
1005 "FATAL: No free register could be found in reg class!!");
1007 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1011 /// Modify the IsColorUsedArr of register class RC, by setting the bits
1012 /// corresponding to register RegNo. This is a helper method of
1013 /// setRelRegsUsedByThisInst().
1015 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1016 const TargetRegInfo &TRI) {
1017 unsigned classId = 0;
1018 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1019 if (RC->getID() == classId)
1020 RC->markColorsUsed(classRegNum, RegType, RegType);
1023 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1024 const MachineInstr *MI) {
1025 assert(OperandsColoredMap[MI] == true &&
1026 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1027 "are marked for an instruction.");
1029 // Add the registers already marked as used by the instruction. Both
1030 // explicit and implicit operands are set.
1031 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1032 if (MI->getOperand(i).hasAllocatedReg())
1033 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1035 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1036 if (MI->getImplicitOp(i).hasAllocatedReg())
1037 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1040 // Add all of the scratch registers that are used to save values across the
1041 // instruction (e.g., for saving state register values).
1042 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1043 IR = ScratchRegsUsed.equal_range(MI);
1044 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1045 markRegisterUsed(I->second, RC, RegType, MRI);
1047 // If there are implicit references, mark their allocated regs as well
1048 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1049 if (const LiveRange*
1050 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
1051 if (LRofImpRef->hasColor())
1052 // this implicit reference is in a LR that received a color
1053 RC->markColorsUsed(LRofImpRef->getColor(),
1054 MRI.getRegTypeForLR(LRofImpRef), RegType);
1058 /// If there are delay slots for an instruction, the instructions added after
1059 /// it must really go after the delayed instruction(s). So, we Move the
1060 /// InstrAfter of that instruction to the corresponding delayed instruction
1061 /// using the following method.
1063 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1064 const MachineInstr *DelayedMI)
1066 // "added after" instructions of the original instr
1067 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1069 if (DEBUG_RA && OrigAft.size() > 0) {
1070 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1071 std::cerr << " to last delay slot instrn: " << *DelayedMI;
1074 // "added after" instructions of the delayed instr
1075 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1077 // go thru all the "added after instructions" of the original instruction
1078 // and append them to the "added after instructions" of the delayed
1080 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1082 // empty the "added after instructions" of the original instruction
1087 void PhyRegAlloc::colorIncomingArgs()
1089 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1090 AddedInstrAtEntry.InstrnsAfter);
1094 /// Determine whether the suggested color of each live range is really usable,
1095 /// and then call its setSuggestedColorUsable() method to record the answer. A
1096 /// suggested color is NOT usable when the suggested color is volatile AND
1097 /// when there are call interferences.
1099 void PhyRegAlloc::markUnusableSugColors()
1101 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1102 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
1104 for (; HMI != HMIEnd ; ++HMI ) {
1106 LiveRange *L = HMI->second; // get the LiveRange
1107 if (L && L->hasSuggestedColor ())
1108 L->setSuggestedColorUsable
1109 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1110 && L->isCallInterference ()));
1112 } // for all LR's in hash map
1116 /// For each live range that is spilled, allocates a new spill position on the
1117 /// stack, and set the stack offsets of the live range that will be spilled to
1118 /// that position. This must be called just after coloring the LRs.
1120 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1121 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1123 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1124 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
1126 for ( ; HMI != HMIEnd ; ++HMI) {
1127 if (HMI->first && HMI->second) {
1128 LiveRange *L = HMI->second; // get the LiveRange
1129 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1130 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
1131 L->setSpillOffFromFP(stackOffset);
1133 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
1134 << ": stack-offset = " << stackOffset << "\n";
1137 } // for all LR's in hash map
1141 void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
1142 const Value *V, unsigned Insn, int Opnd) {
1143 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V);
1144 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();
1145 AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated;
1147 if ((HMI != HMIEnd) && HMI->second) {
1148 LiveRange *L = HMI->second;
1149 assert ((L->hasColor () || L->isMarkedForSpill ())
1150 && "Live range exists but not colored or spilled");
1151 if (L->hasColor ()) {
1152 AllocState = AllocInfo::Allocated;
1153 Placement = MRI.getUnifiedRegNum (L->getRegClassID (),
1155 } else if (L->isMarkedForSpill ()) {
1156 AllocState = AllocInfo::Spilled;
1157 assert (L->hasSpillOffset ()
1158 && "Live range marked for spill but has no spill offset");
1159 Placement = L->getSpillOffFromFP ();
1162 state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement));
1166 /// Save the global register allocation decisions made by the register
1167 /// allocator so that they can be accessed later (sort of like "poor man's
1170 void PhyRegAlloc::saveState () {
1171 std::vector<AllocInfo> &state = FnAllocState[Fn];
1173 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
1174 saveStateForValue (state, (*II), Insn, -1);
1175 for (unsigned i = 0; i < (*II)->getNumOperands (); ++i) {
1176 const Value *V = (*II)->getOperand (i);
1177 // Don't worry about it unless it's something whose reg. we'll need.
1178 if (!isa<Argument> (V) && !isa<Instruction> (V))
1180 saveStateForValue (state, V, Insn, i);
1187 /// Check the saved state filled in by saveState(), and abort if it looks
1188 /// wrong. Only used when debugging. FIXME: Currently it just prints out
1189 /// the state, which isn't quite as useful.
1191 void PhyRegAlloc::verifySavedState () {
1192 std::vector<AllocInfo> &state = FnAllocState[Fn];
1194 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II) {
1195 const Instruction *I = *II;
1196 MachineCodeForInstruction &Instrs = MachineCodeForInstruction::get (I);
1197 std::cerr << "Instruction:\n" << " " << *I << "\n"
1198 << "MachineCodeForInstruction:\n";
1199 for (unsigned i = 0, n = Instrs.size (); i != n; ++i)
1200 std::cerr << " " << *Instrs[i] << "\n";
1201 std::cerr << "FnAllocState:\n";
1202 for (unsigned i = 0; i < state.size (); ++i) {
1203 AllocInfo &S = state[i];
1204 if (Insn == S.Instruction) {
1205 std::cerr << " (Instruction " << S.Instruction
1206 << ", Operand " << S.Operand
1207 << ", AllocState " << S.allocStateToString ()
1208 << ", Placement " << S.Placement << ")\n";
1211 std::cerr << "----------\n";
1217 /// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1218 /// Constant and stuffing it inside the Module. (NOTE: Soon, there will be
1219 /// other, better ways of storing the saved state; this one is cumbersome and
1220 /// does not work well with the JIT.)
1222 bool PhyRegAlloc::doFinalization (Module &M) {
1223 if (!SaveRegAllocState)
1224 return false; // Nothing to do here, unless we're saving state.
1226 // If saving state into the module, just copy new elements to the
1228 if (!SaveStateToModule) {
1229 ExportedFnAllocState = FnAllocState;
1230 // FIXME: should ONLY copy new elements in FnAllocState
1234 // Convert FnAllocState to a single Constant array and add it
1236 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1237 std::vector<const Type *> TV;
1238 TV.push_back (Type::UIntTy);
1240 PointerType *PT = PointerType::get (StructType::get (TV));
1242 std::vector<Constant *> allstate;
1243 for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1245 if (F->isExternal ()) continue;
1246 if (FnAllocState.find (F) == FnAllocState.end ()) {
1247 allstate.push_back (ConstantPointerNull::get (PT));
1249 std::vector<AllocInfo> &state = FnAllocState[F];
1251 // Convert state into an LLVM ConstantArray, and put it in a
1252 // ConstantStruct (named S) along with its size.
1253 std::vector<Constant *> stateConstants;
1254 for (unsigned i = 0, s = state.size (); i != s; ++i)
1255 stateConstants.push_back (state[i].toConstant ());
1256 unsigned Size = stateConstants.size ();
1257 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1258 std::vector<const Type *> TV;
1259 TV.push_back (Type::UIntTy);
1261 StructType *ST = StructType::get (TV);
1262 std::vector<Constant *> CV;
1263 CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
1264 CV.push_back (ConstantArray::get (AT, stateConstants));
1265 Constant *S = ConstantStruct::get (ST, CV);
1267 GlobalVariable *GV =
1268 new GlobalVariable (ST, true,
1269 GlobalValue::InternalLinkage, S,
1270 F->getName () + ".regAllocState", &M);
1272 // Have: { uint, [Size x { uint, int, uint, int }] } *
1273 // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
1274 Constant *CE = ConstantExpr::getCast (ConstantPointerRef::get (GV), PT);
1275 allstate.push_back (CE);
1279 unsigned Size = allstate.size ();
1280 // Final structure type is:
1281 // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
1282 std::vector<const Type *> TV2;
1283 TV2.push_back (Type::UIntTy);
1284 ArrayType *AT2 = ArrayType::get (PT, Size);
1285 TV2.push_back (AT2);
1286 StructType *ST2 = StructType::get (TV2);
1287 std::vector<Constant *> CV2;
1288 CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1289 CV2.push_back (ConstantArray::get (AT2, allstate));
1290 new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
1291 ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1293 return false; // No error.
1297 /// Allocate registers for the machine code previously generated for F using
1298 /// the graph-coloring algorithm.
1300 bool PhyRegAlloc::runOnFunction (Function &F) {
1302 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1305 MF = &MachineFunction::get (Fn);
1306 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1307 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1308 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1310 // Create each RegClass for the target machine and add it to the
1311 // RegClassList. This must be done before calling constructLiveRanges().
1312 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1313 RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (),
1314 MRI.getMachineRegClass (rc)));
1316 LRI->constructLiveRanges(); // create LR info
1317 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1318 LRI->printLiveRanges();
1320 createIGNodeListsAndIGs(); // create IGNode list and IGs
1322 buildInterferenceGraphs(); // build IGs in all reg classes
1324 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1325 // print all LRs in all reg classes
1326 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1327 RegClassList[rc]->printIGNodeList();
1329 // print IGs in all register classes
1330 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1331 RegClassList[rc]->printIG();
1334 LRI->coalesceLRs(); // coalesce all live ranges
1336 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1337 // print all LRs in all reg classes
1338 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1339 RegClassList[rc]->printIGNodeList();
1341 // print IGs in all register classes
1342 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1343 RegClassList[rc]->printIG();
1346 // mark un-usable suggested color before graph coloring algorithm.
1347 // When this is done, the graph coloring algo will not reserve
1348 // suggested color unnecessarily - they can be used by another LR
1349 markUnusableSugColors();
1351 // color all register classes using the graph coloring algo
1352 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1353 RegClassList[rc]->colorAllRegs();
1355 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1356 // a position for such spilled LRs
1357 allocateStackSpace4SpilledLRs();
1359 // Reset the temp. area on the stack before use by the first instruction.
1360 // This will also happen after updating each instruction.
1361 MF->getInfo()->popAllTempValues();
1363 // color incoming args - if the correct color was not received
1364 // insert code to copy to the correct register
1365 colorIncomingArgs();
1367 // Save register allocation state for this function in a Constant.
1368 if (SaveRegAllocState)
1370 if (DEBUG_RA) { // Check our work.
1371 verifySavedState ();
1374 // Now update the machine code with register names and add any additional
1375 // code inserted by the register allocator to the instruction stream.
1376 updateMachineCode();
1379 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1383 // Tear down temporary data structures
1384 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1385 delete RegClassList[rc];
1386 RegClassList.clear ();
1387 AddedInstrMap.clear ();
1388 OperandsColoredMap.clear ();
1389 ScratchRegsUsed.clear ();
1390 AddedInstrAtEntry.clear ();
1393 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1394 return false; // Function was not modified
1397 } // End llvm namespace