Only call verifySavedState if SaveRegAllocState is set AND debugging flag is on.
[oota-llvm.git] / lib / Target / SparcV9 / RegAlloc / PhyRegAlloc.cpp
1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
2 // 
3 //                     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 // 
10 // 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.
20 // 
21 //===----------------------------------------------------------------------===//
22
23 #include "AllocInfo.h"
24 #include "IGNode.h"
25 #include "PhyRegAlloc.h"
26 #include "RegAllocCommon.h"
27 #include "RegClass.h"
28 #include "../LiveVar/FunctionLiveVarInfo.h"
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/iOther.h"
32 #include "llvm/Module.h"
33 #include "llvm/Type.h"
34 #include "llvm/Analysis/LoopInfo.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 "../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"
48 #include <cmath>
49
50 namespace llvm {
51
52 RegAllocDebugLevel_t DEBUG_RA;
53
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.
56 ///
57 PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
58 const bool SaveStateToModule = true;
59
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"),
63         cl::values(
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"),
70                    0));
71
72 static cl::opt<bool>
73 SaveRegAllocState("save-ra-state", cl::Hidden,
74                   cl::desc("write reg. allocator state into module"));
75
76 FunctionPass *getRegisterAllocator(TargetMachine &T) {
77   return new PhyRegAlloc (T);
78 }
79
80 void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
81   AU.addRequired<LoopInfo> ();
82   AU.addRequired<FunctionLiveVarInfo> ();
83 }
84
85
86 /// Initialize interference graphs (one in each reg class) and IGNodeLists
87 /// (one in each IG). The actual nodes will be pushed later.
88 ///
89 void PhyRegAlloc::createIGNodeListsAndIGs() {
90   if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
91
92   LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();   
93   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();   
94
95   for (; HMI != HMIEnd ; ++HMI ) {
96     if (HMI->first) { 
97       LiveRange *L = HMI->second;   // get the LiveRange
98       if (!L) { 
99         if (DEBUG_RA)
100           std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
101                << RAV(HMI->first) << "****\n";
102         continue;
103       }
104
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
110       }
111     }
112   }
113     
114   // init RegClassList
115   for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
116     RegClassList[rc]->createInterferenceGraph();
117
118   if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
119 }
120
121
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
125 /// instruction.
126 ///
127 void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
128                                   bool isCallInst) {
129   ValueSet::const_iterator LIt = LVSet->begin();
130
131   // get the live range of instruction
132   const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );   
133
134   IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
135   assert( IGNodeOfDef );
136
137   RegClass *const RCOfDef = LROfDef->getRegClass(); 
138
139   // for each live var in live variable set
140   for ( ; LIt != LVSet->end(); ++LIt) {
141
142     if (DEBUG_RA >= RA_DEBUG_Verbose)
143       std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
144
145     //  get the live range corresponding to live var
146     LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
147
148     // LROfVar can be null if it is a const since a const 
149     // doesn't have a dominating def - see Assumptions above
150     if (LROfVar)
151       if (LROfDef != LROfVar)                  // do not set interf for same LR
152         if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
153           RCOfDef->setInterference( LROfDef, LROfVar);  
154   }
155 }
156
157
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).
162 ///
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;
167
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) {
171
172     //  get the live range corresponding to live var
173     LiveRange *const LR = LRI->getLiveRangeForValue(*LIt ); 
174
175     // LR can be null if it is a const since a const 
176     // doesn't have a dominating def - see Assumptions above
177     if (LR ) {  
178       if (DEBUG_RA >= RA_DEBUG_Interference) {
179         std::cerr << "\n\tLR after Call: ";
180         printSet(*LR);
181       }
182       LR->setCallInterference();
183       if (DEBUG_RA >= RA_DEBUG_Interference) {
184         std::cerr << "\n  ++After adding call interference for LR: " ;
185         printSet(*LR);
186       }
187     }
188
189   }
190
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);
197   
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();
202   }
203
204   // If the CALL is an indirect call, find the LR of the function pointer.
205   // That has a call interference because it conflicts with outgoing args.
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();
210   }
211 }
212
213
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
216 /// over the code).
217 ///
218 void PhyRegAlloc::buildInterferenceGraphs() {
219   if (DEBUG_RA >= RA_DEBUG_Interference)
220     std::cerr << "Creating interference graphs ...\n";
221
222   unsigned BBLoopDepthCost;
223   for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
224        BBI != BBE; ++BBI) {
225     const MachineBasicBlock &MBB = *BBI;
226     const BasicBlock *BB = MBB.getBasicBlock();
227
228     // find the 10^(loop_depth) of this BB 
229     BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
230
231     // get the iterator for machine instructions
232     MachineBasicBlock::const_iterator MII = MBB.begin();
233
234     // iterate over all the machine instructions in BB
235     for ( ; MII != MBB.end(); ++MII) {
236       const MachineInstr *MInst = MII;
237
238       // get the LV set after the instruction
239       const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
240       bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpcode());
241
242       if (isCallInst) {
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);
248       }
249
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);
255
256         // Calculate the spill cost of each live range
257         LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
258         if (LR) LR->addSpillCost(BBLoopDepthCost);
259       } 
260
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);
267
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 );
274
275     } // for all machine instructions in BB
276   } // for all BBs in function
277
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();          
281
282   if (DEBUG_RA >= RA_DEBUG_Interference)
283     std::cerr << "Interference graphs calculated!\n";
284 }
285
286
287 /// Mark all operands of the given MachineInstr as interfering with one
288 /// another.
289 ///
290 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
291   bool setInterf = false;
292
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");
298
299     MachineInstr::const_val_op_iterator It2 = It1;
300     for (++It2; It2 != ItE; ++It2) {
301       const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2); 
302
303       if (LROfOp2) {
304         RegClass *RCOfOp1 = LROfOp1->getRegClass(); 
305         RegClass *RCOfOp2 = LROfOp2->getRegClass(); 
306  
307         if (RCOfOp1 == RCOfOp2 ){ 
308           RCOfOp1->setInterference( LROfOp1, LROfOp2 );  
309           setInterf = true;
310         }
311       } // if Op2 has a LR
312     } // for all other defs in machine instr
313   } // for all operands in an instruction
314
315   if (!setInterf && MInst->getNumOperands() > 2) {
316     std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
317     std::cerr << *MInst;
318     assert(0 && "Interf not set for pseudo instr with > 2 operands" );
319   }
320
321
322
323 /// Add interferences for incoming arguments to a function.
324 ///
325 void PhyRegAlloc::addInterferencesForArgs() {
326   // get the InSet of root BB
327   const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());  
328
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);
332     
333     if (DEBUG_RA >= RA_DEBUG_Interference)
334       std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
335   }
336 }
337
338
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.
342 ///
343
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);
348   ++MII;
349 }
350
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);
356 }
357
358 // used by: updateMachineCode (2 times)
359 inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
360                                 MachineBasicBlock& MBB,
361                                 MachineBasicBlock::iterator& MII,
362                                 const std::string& msg) {
363   if (!IBef.empty()) {
364       MachineInstr* OrigMI = MII;
365       std::vector<MachineInstr *>::iterator AdIt; 
366       for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
367           if (DEBUG_RA) {
368             if (OrigMI) std::cerr << "For MInst:\n  " << *OrigMI;
369             std::cerr << msg << "PREPENDed instr:\n  " << **AdIt << "\n";
370           }
371           InsertBefore(*AdIt, MBB, MII);
372         }
373     }
374 }
375
376 // used by: updateMachineCode (1 time)
377 inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
378                                MachineBasicBlock& MBB,
379                                MachineBasicBlock::iterator& MII,
380                                const std::string& msg) {
381   if (!IAft.empty()) {
382       MachineInstr* OrigMI = MII;
383       std::vector<MachineInstr *>::iterator AdIt; 
384       for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
385           if (DEBUG_RA) {
386             if (OrigMI) std::cerr << "For MInst:\n  " << *OrigMI;
387             std::cerr << msg << "APPENDed instr:\n  "  << **AdIt << "\n";
388           }
389           InsertAfter(*AdIt, MBB, MII);
390         }
391     }
392 }
393
394 /// Set the registers for operands in the given MachineInstr, if a register was
395 /// successfully allocated.  Return true if any of its operands has been marked
396 /// for spill.
397 ///
398 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
399 {
400   bool instrNeedsSpills = false;
401
402   // First, set the registers for operands in the machine instruction
403   // if a register was successfully allocated.  Do this first because we
404   // will need to know which registers are already used by this instr'n.
405   for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
406       MachineOperand& Op = MInst->getOperand(OpNum);
407       if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
408           Op.getType() ==  MachineOperand::MO_CCRegister) {
409           const Value *const Val =  Op.getVRegValue();
410           if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
411             // Remember if any operand needs spilling
412             instrNeedsSpills |= LR->isMarkedForSpill();
413
414             // An operand may have a color whether or not it needs spilling
415             if (LR->hasColor())
416               MInst->SetRegForOperand(OpNum,
417                           MRI.getUnifiedRegNum(LR->getRegClassID(),
418                                                LR->getColor()));
419           }
420         }
421     } // for each operand
422
423   return instrNeedsSpills;
424 }
425
426 /// Mark allocated registers (using markAllocatedRegs()) on the instruction
427 /// that MII points to. Then, if it's a call instruction, insert caller-saving
428 /// code before and after it. Finally, insert spill code before and after it,
429 /// using insertCode4SpilledLR().
430 ///
431 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
432                                     MachineBasicBlock &MBB) {
433   MachineInstr* MInst = MII;
434   unsigned Opcode = MInst->getOpcode();
435
436   // Reset tmp stack positions so they can be reused for each machine instr.
437   MF->getInfo()->popAllTempValues();  
438
439   // Mark the operands for which regs have been allocated.
440   bool instrNeedsSpills = markAllocatedRegs(MII);
441
442 #ifndef NDEBUG
443   // Mark that the operands have been updated.  Later,
444   // setRelRegsUsedByThisInst() is called to find registers used by each
445   // MachineInst, and it should not be used for an instruction until
446   // this is done.  This flag just serves as a sanity check.
447   OperandsColoredMap[MInst] = true;
448 #endif
449
450   // Now insert caller-saving code before/after the call.
451   // Do this before inserting spill code since some registers must be
452   // used by save/restore and spill code should not use those registers.
453   if (TM.getInstrInfo().isCall(Opcode)) {
454     AddedInstrns &AI = AddedInstrMap[MInst];
455     insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
456                            MBB.getBasicBlock());
457   }
458
459   // Now insert spill code for remaining operands not allocated to
460   // registers.  This must be done even for call return instructions
461   // since those are not handled by the special code above.
462   if (instrNeedsSpills)
463     for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
464         MachineOperand& Op = MInst->getOperand(OpNum);
465         if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
466             Op.getType() ==  MachineOperand::MO_CCRegister) {
467             const Value* Val = Op.getVRegValue();
468             if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
469               if (LR->isMarkedForSpill())
470                 insertCode4SpilledLR(LR, MII, MBB, OpNum);
471           }
472       } // for each operand
473 }
474
475 /// Iterate over all the MachineBasicBlocks in the current function and set
476 /// the allocated registers for each instruction (using updateInstruction()),
477 /// after register allocation is complete. Then move code out of delay slots.
478 ///
479 void PhyRegAlloc::updateMachineCode()
480 {
481   // Insert any instructions needed at method entry
482   MachineBasicBlock::iterator MII = MF->front().begin();
483   PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
484                       "At function entry: \n");
485   assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
486          "InstrsAfter should be unnecessary since we are just inserting at "
487          "the function entry point here.");
488   
489   for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
490        BBI != BBE; ++BBI) {
491     MachineBasicBlock &MBB = *BBI;
492
493     // Iterate over all machine instructions in BB and mark operands with
494     // their assigned registers or insert spill code, as appropriate. 
495     // Also, fix operands of call/return instructions.
496     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
497       if (! TM.getInstrInfo().isDummyPhiInstr(MII->getOpcode()))
498         updateInstruction(MII, MBB);
499
500     // Now, move code out of delay slots of branches and returns if needed.
501     // (Also, move "after" code from calls to the last delay slot instruction.)
502     // Moving code out of delay slots is needed in 2 situations:
503     // (1) If this is a branch and it needs instructions inserted after it,
504     //     move any existing instructions out of the delay slot so that the
505     //     instructions can go into the delay slot.  This only supports the
506     //     case that #instrsAfter <= #delay slots.
507     // 
508     // (2) If any instruction in the delay slot needs
509     //     instructions inserted, move it out of the delay slot and before the
510     //     branch because putting code before or after it would be VERY BAD!
511     // 
512     // If the annul bit of the branch is set, neither of these is legal!
513     // If so, we need to handle spill differently but annulling is not yet used.
514     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
515       if (unsigned delaySlots =
516           TM.getInstrInfo().getNumDelaySlots(MII->getOpcode())) { 
517           MachineBasicBlock::iterator DelaySlotMI = next(MII);
518           assert(DelaySlotMI != MBB.end() && "no instruction for delay slot");
519           
520           // Check the 2 conditions above:
521           // (1) Does a branch need instructions added after it?
522           // (2) O/w does delay slot instr. need instrns before or after?
523           bool isBranch = (TM.getInstrInfo().isBranch(MII->getOpcode()) ||
524                            TM.getInstrInfo().isReturn(MII->getOpcode()));
525           bool cond1 = (isBranch &&
526                         AddedInstrMap.count(MII) &&
527                         AddedInstrMap[MII].InstrnsAfter.size() > 0);
528           bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
529                         (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
530                          AddedInstrMap[DelaySlotMI].InstrnsAfter.size()  > 0));
531
532           if (cond1 || cond2) {
533               assert(delaySlots==1 &&
534                      "InsertBefore does not yet handle >1 delay slots!");
535
536               if (DEBUG_RA) {
537                 std::cerr << "\nRegAlloc: Moved instr. with added code: "
538                      << *DelaySlotMI
539                      << "           out of delay slots of instr: " << *MII;
540               }
541
542               // move instruction before branch
543               MBB.insert(MII, MBB.remove(DelaySlotMI));
544
545               // On cond1 we are done (we already moved the
546               // instruction out of the delay slot). On cond2 we need
547               // to insert a nop in place of the moved instruction
548               if (cond2) {
549                 MBB.insert(MII, BuildMI(TM.getInstrInfo().getNOPOpCode(),1));
550               }
551             }
552           else {
553             // For non-branch instr with delay slots (probably a call), move
554             // InstrAfter to the instr. in the last delay slot.
555             MachineBasicBlock::iterator tmp = next(MII, delaySlots);
556             move2DelayedInstr(MII, tmp);
557           }
558       }
559
560     // Finally iterate over all instructions in BB and insert before/after
561     for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
562       MachineInstr *MInst = MII; 
563
564       // do not process Phis
565       if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpcode()))
566         continue;
567
568       // if there are any added instructions...
569       if (AddedInstrMap.count(MInst)) {
570         AddedInstrns &CallAI = AddedInstrMap[MInst];
571
572 #ifndef NDEBUG
573         bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpcode()) ||
574                          TM.getInstrInfo().isReturn(MInst->getOpcode()));
575         assert((!isBranch ||
576                 AddedInstrMap[MInst].InstrnsAfter.size() <=
577                 TM.getInstrInfo().getNumDelaySlots(MInst->getOpcode())) &&
578                "Cannot put more than #delaySlots instrns after "
579                "branch or return! Need to handle temps differently.");
580 #endif
581
582 #ifndef NDEBUG
583         // Temporary sanity checking code to detect whether the same machine
584         // instruction is ever inserted twice before/after a call.
585         // I suspect this is happening but am not sure. --Vikram, 7/1/03.
586         std::set<const MachineInstr*> instrsSeen;
587         for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
588           assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
589                  "Duplicate machine instruction in InstrnsBefore!");
590           instrsSeen.insert(CallAI.InstrnsBefore[i]);
591         } 
592         for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
593           assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
594                  "Duplicate machine instruction in InstrnsBefore/After!");
595           instrsSeen.insert(CallAI.InstrnsAfter[i]);
596         } 
597 #endif
598
599         // Now add the instructions before/after this MI.
600         // We do this here to ensure that spill for an instruction is inserted
601         // as close as possible to an instruction (see above insertCode4Spill)
602         if (! CallAI.InstrnsBefore.empty())
603           PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
604         
605         if (! CallAI.InstrnsAfter.empty())
606           AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
607
608       } // if there are any added instructions
609     } // for each machine instruction
610   }
611 }
612
613
614 /// Insert spill code for AN operand whose LR was spilled.  May be called
615 /// repeatedly for a single MachineInstr if it has many spilled operands. On
616 /// each call, it finds a register which is not live at that instruction and
617 /// also which is not used by other spilled operands of the same
618 /// instruction. Then it uses this register temporarily to accommodate the
619 /// spilled value.
620 ///
621 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR, 
622                                        MachineBasicBlock::iterator& MII,
623                                        MachineBasicBlock &MBB,
624                                        const unsigned OpNum) {
625   MachineInstr *MInst = MII;
626   const BasicBlock *BB = MBB.getBasicBlock();
627
628   assert((! TM.getInstrInfo().isCall(MInst->getOpcode()) || OpNum == 0) &&
629          "Outgoing arg of a call must be handled elsewhere (func arg ok)");
630   assert(! TM.getInstrInfo().isReturn(MInst->getOpcode()) &&
631          "Return value of a ret must be handled elsewhere");
632
633   MachineOperand& Op = MInst->getOperand(OpNum);
634   bool isDef =  Op.isDef();
635   bool isUse = Op.isUse();
636   unsigned RegType = MRI.getRegTypeForLR(LR);
637   int SpillOff = LR->getSpillOffFromFP();
638   RegClass *RC = LR->getRegClass();
639
640   // Get the live-variable set to find registers free before this instr.
641   const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
642
643 #ifndef NDEBUG
644   // If this instr. is in the delay slot of a branch or return, we need to
645   // include all live variables before that branch or return -- we don't want to
646   // trample those!  Verify that the set is included in the LV set before MInst.
647   if (MII != MBB.begin()) {
648     MachineBasicBlock::iterator PredMI = prior(MII);
649     if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpcode()))
650       assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
651              .empty() && "Live-var set before branch should be included in "
652              "live-var set of each delay slot instruction!");
653   }
654 #endif
655
656   MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
657   
658   std::vector<MachineInstr*> MIBef, MIAft;
659   std::vector<MachineInstr*> AdIMid;
660   
661   // Choose a register to hold the spilled value, if one was not preallocated.
662   // This may insert code before and after MInst to free up the value.  If so,
663   // this code should be first/last in the spill sequence before/after MInst.
664   int TmpRegU=(LR->hasColor()
665                ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
666                : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
667   
668   // Set the operand first so that it this register does not get used
669   // as a scratch register for later calls to getUsableUniRegAtMI below
670   MInst->SetRegForOperand(OpNum, TmpRegU);
671   
672   // get the added instructions for this instruction
673   AddedInstrns &AI = AddedInstrMap[MInst];
674
675   // We may need a scratch register to copy the spilled value to/from memory.
676   // This may itself have to insert code to free up a scratch register.  
677   // Any such code should go before (after) the spill code for a load (store).
678   // The scratch reg is not marked as used because it is only used
679   // for the copy and not used across MInst.
680   int scratchRegType = -1;
681   int scratchReg = -1;
682   if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
683       scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
684                                        MInst, MIBef, MIAft);
685       assert(scratchReg != MRI.getInvalidRegNum());
686     }
687   
688   if (isUse) {
689     // for a USE, we have to load the value of LR from stack to a TmpReg
690     // and use the TmpReg as one operand of instruction
691     
692     // actual loading instruction(s)
693     MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
694                     RegType, scratchReg);
695     
696     // the actual load should be after the instructions to free up TmpRegU
697     MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
698     AdIMid.clear();
699   }
700   
701   if (isDef) {   // if this is a Def
702     // for a DEF, we have to store the value produced by this instruction
703     // on the stack position allocated for this LR
704     
705     // actual storing instruction(s)
706     MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
707                     RegType, scratchReg);
708     
709     MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
710   }  // if !DEF
711   
712   // Finally, insert the entire spill code sequences before/after MInst
713   AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
714   AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
715   
716   if (DEBUG_RA) {
717     std::cerr << "\nFor Inst:\n  " << *MInst;
718     std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
719     std::cerr << "; added Instructions:";
720     for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
721     for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
722   }
723 }
724
725
726 /// Insert caller saving/restoring instructions before/after a call machine
727 /// instruction (before or after any other instructions that were inserted for
728 /// the call).
729 ///
730 void
731 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
732                                     std::vector<MachineInstr*> &instrnsAfter,
733                                     MachineInstr *CallMI, 
734                                     const BasicBlock *BB) {
735   assert(TM.getInstrInfo().isCall(CallMI->getOpcode()));
736   
737   // hash set to record which registers were saved/restored
738   hash_set<unsigned> PushedRegSet;
739
740   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
741   
742   // if the call is to a instrumentation function, do not insert save and
743   // restore instructions the instrumentation function takes care of save
744   // restore for volatile regs.
745   //
746   // FIXME: this should be made general, not specific to the reoptimizer!
747   const Function *Callee = argDesc->getCallInst()->getCalledFunction();
748   bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
749
750   // Now check if the call has a return value (using argDesc) and if so,
751   // find the LR of the TmpInstruction representing the return value register.
752   // (using the last or second-last *implicit operand* of the call MI).
753   // Insert it to to the PushedRegSet since we must not save that register
754   // and restore it after the call.
755   // We do this because, we look at the LV set *after* the instruction
756   // to determine, which LRs must be saved across calls. The return value
757   // of the call is live in this set - but we must not save/restore it.
758   if (const Value *origRetVal = argDesc->getReturnValue()) {
759     unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
760                              (argDesc->getIndirectFuncPtr()? 1 : 2));
761     const TmpInstruction* tmpRetVal =
762       cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
763     assert(tmpRetVal->getOperand(0) == origRetVal &&
764            tmpRetVal->getType() == origRetVal->getType() &&
765            "Wrong implicit ref?");
766     LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
767     assert(RetValLR && "No LR for RetValue of call");
768
769     if (! RetValLR->isMarkedForSpill())
770       PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
771                                                RetValLR->getColor()));
772   }
773
774   const ValueSet &LVSetAft =  LVI->getLiveVarSetAfterMInst(CallMI, BB);
775   ValueSet::const_iterator LIt = LVSetAft.begin();
776
777   // for each live var in live variable set after machine inst
778   for( ; LIt != LVSetAft.end(); ++LIt) {
779     // get the live range corresponding to live var
780     LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
781
782     // LR can be null if it is a const since a const 
783     // doesn't have a dominating def - see Assumptions above
784     if (LR) {  
785       if (! LR->isMarkedForSpill()) {
786         assert(LR->hasColor() && "LR is neither spilled nor colored?");
787         unsigned RCID = LR->getRegClassID();
788         unsigned Color = LR->getColor();
789
790         if (MRI.isRegVolatile(RCID, Color) ) {
791           // if this is a call to the first-level reoptimizer
792           // instrumentation entry point, and the register is not
793           // modified by call, don't save and restore it.
794           if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
795             continue;
796
797           // if the value is in both LV sets (i.e., live before and after 
798           // the call machine instruction)
799           unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
800           
801           // if we haven't already pushed this register...
802           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
803             unsigned RegType = MRI.getRegTypeForLR(LR);
804
805             // Now get two instructions - to push on stack and pop from stack
806             // and add them to InstrnsBefore and InstrnsAfter of the
807             // call instruction
808             int StackOff =
809               MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
810             
811             //---- Insert code for pushing the reg on stack ----------
812             
813             std::vector<MachineInstr*> AdIBef, AdIAft;
814             
815             // We may need a scratch register to copy the saved value
816             // to/from memory.  This may itself have to insert code to
817             // free up a scratch register.  Any such code should go before
818             // the save code.  The scratch register, if any, is by default
819             // temporary and not "used" by the instruction unless the
820             // copy code itself decides to keep the value in the scratch reg.
821             int scratchRegType = -1;
822             int scratchReg = -1;
823             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
824               { // Find a register not live in the LVSet before CallMI
825                 const ValueSet &LVSetBef =
826                   LVI->getLiveVarSetBeforeMInst(CallMI, BB);
827                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
828                                                  CallMI, AdIBef, AdIAft);
829                 assert(scratchReg != MRI.getInvalidRegNum());
830               }
831             
832             if (AdIBef.size() > 0)
833               instrnsBefore.insert(instrnsBefore.end(),
834                                    AdIBef.begin(), AdIBef.end());
835             
836             MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
837                             StackOff, RegType, scratchReg);
838             
839             if (AdIAft.size() > 0)
840               instrnsBefore.insert(instrnsBefore.end(),
841                                    AdIAft.begin(), AdIAft.end());
842             
843             //---- Insert code for popping the reg from the stack ----------
844             AdIBef.clear();
845             AdIAft.clear();
846             
847             // We may need a scratch register to copy the saved value
848             // from memory.  This may itself have to insert code to
849             // free up a scratch register.  Any such code should go
850             // after the save code.  As above, scratch is not marked "used".
851             scratchRegType = -1;
852             scratchReg = -1;
853             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
854               { // Find a register not live in the LVSet after CallMI
855                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
856                                                  CallMI, AdIBef, AdIAft);
857                 assert(scratchReg != MRI.getInvalidRegNum());
858               }
859             
860             if (AdIBef.size() > 0)
861               instrnsAfter.insert(instrnsAfter.end(),
862                                   AdIBef.begin(), AdIBef.end());
863             
864             MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
865                             Reg, RegType, scratchReg);
866             
867             if (AdIAft.size() > 0)
868               instrnsAfter.insert(instrnsAfter.end(),
869                                   AdIAft.begin(), AdIAft.end());
870             
871             PushedRegSet.insert(Reg);
872             
873             if(DEBUG_RA) {
874               std::cerr << "\nFor call inst:" << *CallMI;
875               std::cerr << " -inserted caller saving instrs: Before:\n\t ";
876               for_each(instrnsBefore.begin(), instrnsBefore.end(),
877                        std::mem_fun(&MachineInstr::dump));
878               std::cerr << " -and After:\n\t ";
879               for_each(instrnsAfter.begin(), instrnsAfter.end(),
880                        std::mem_fun(&MachineInstr::dump));
881             }       
882           } // if not already pushed
883         } // if LR has a volatile color
884       } // if LR has color
885     } // if there is a LR for Var
886   } // for each value in the LV set after instruction
887 }
888
889
890 /// Returns the unified register number of a temporary register to be used
891 /// BEFORE MInst. If no register is available, it will pick one and modify
892 /// MIBef and MIAft to contain instructions used to free up this returned
893 /// register.
894 ///
895 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
896                                      const ValueSet *LVSetBef,
897                                      MachineInstr *MInst, 
898                                      std::vector<MachineInstr*>& MIBef,
899                                      std::vector<MachineInstr*>& MIAft) {
900   RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
901   
902   int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
903   
904   if (RegU == -1) {
905     // we couldn't find an unused register. Generate code to free up a reg by
906     // saving it on stack and restoring after the instruction
907     
908     int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
909     
910     RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
911     
912     // Check if we need a scratch register to copy this register to memory.
913     int scratchRegType = -1;
914     if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
915         int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
916                                              MInst, MIBef, MIAft);
917         assert(scratchReg != MRI.getInvalidRegNum());
918         
919         // We may as well hold the value in the scratch register instead
920         // of copying it to memory and back.  But we have to mark the
921         // register as used by this instruction, so it does not get used
922         // as a scratch reg. by another operand or anyone else.
923         ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
924         MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
925         MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
926     } else { // the register can be copied directly to/from memory so do it.
927         MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
928         MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
929     }
930   }
931   
932   return RegU;
933 }
934
935
936 /// Returns the register-class register number of a new unused register that
937 /// can be used to accommodate a temporary value.  May be called repeatedly
938 /// for a single MachineInstr.  On each call, it finds a register which is not
939 /// live at that instruction and which is not used by any spilled operands of
940 /// that instruction.
941 ///
942 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
943                                      const MachineInstr *MInst,
944                                      const ValueSet* LVSetBef) {
945   RC->clearColorsUsed();     // Reset array
946
947   if (LVSetBef == NULL) {
948       LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
949       assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
950   }
951
952   ValueSet::const_iterator LIt = LVSetBef->begin();
953
954   // for each live var in live variable set after machine inst
955   for ( ; LIt != LVSetBef->end(); ++LIt) {
956     // Get the live range corresponding to live var, and its RegClass
957     LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );    
958
959     // LR can be null if it is a const since a const 
960     // doesn't have a dominating def - see Assumptions above
961     if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
962       RC->markColorsUsed(LRofLV->getColor(),
963                          MRI.getRegTypeForLR(LRofLV), RegType);
964   }
965
966   // It is possible that one operand of this MInst was already spilled
967   // and it received some register temporarily. If that's the case,
968   // it is recorded in machine operand. We must skip such registers.
969   setRelRegsUsedByThisInst(RC, RegType, MInst);
970
971   int unusedReg = RC->getUnusedColor(RegType);   // find first unused color
972   if (unusedReg >= 0)
973     return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
974
975   return -1;
976 }
977
978
979 /// Return the unified register number of a register in class RC which is not
980 /// used by any operands of MInst.
981 ///
982 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC, 
983                                             const int RegType,
984                                             const MachineInstr *MInst) {
985   RC->clearColorsUsed();
986
987   setRelRegsUsedByThisInst(RC, RegType, MInst);
988
989   // find the first unused color
990   int unusedReg = RC->getUnusedColor(RegType);
991   assert(unusedReg >= 0 &&
992          "FATAL: No free register could be found in reg class!!");
993
994   return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
995 }
996
997
998 /// Modify the IsColorUsedArr of register class RC, by setting the bits
999 /// corresponding to register RegNo. This is a helper method of
1000 /// setRelRegsUsedByThisInst().
1001 ///
1002 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1003                              const TargetRegInfo &TRI) {
1004   unsigned classId = 0;
1005   int classRegNum = TRI.getClassRegNum(RegNo, classId);
1006   if (RC->getID() == classId)
1007     RC->markColorsUsed(classRegNum, RegType, RegType);
1008 }
1009
1010 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1011                                            const MachineInstr *MI) {
1012   assert(OperandsColoredMap[MI] == true &&
1013          "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1014          "are marked for an instruction.");
1015
1016   // Add the registers already marked as used by the instruction. Both
1017   // explicit and implicit operands are set.
1018   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1019     if (MI->getOperand(i).hasAllocatedReg())
1020       markRegisterUsed(MI->getOperand(i).getReg(), RC, RegType,MRI);
1021
1022   for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1023     if (MI->getImplicitOp(i).hasAllocatedReg())
1024       markRegisterUsed(MI->getImplicitOp(i).getReg(), RC, RegType,MRI);
1025
1026   // Add all of the scratch registers that are used to save values across the
1027   // instruction (e.g., for saving state register values).
1028   std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1029     IR = ScratchRegsUsed.equal_range(MI);
1030   for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1031     markRegisterUsed(I->second, RC, RegType, MRI);
1032
1033   // If there are implicit references, mark their allocated regs as well
1034   for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1035     if (const LiveRange*
1036         LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))    
1037       if (LRofImpRef->hasColor())
1038         // this implicit reference is in a LR that received a color
1039         RC->markColorsUsed(LRofImpRef->getColor(),
1040                            MRI.getRegTypeForLR(LRofImpRef), RegType);
1041 }
1042
1043
1044 /// If there are delay slots for an instruction, the instructions added after
1045 /// it must really go after the delayed instruction(s).  So, we Move the
1046 /// InstrAfter of that instruction to the corresponding delayed instruction
1047 /// using the following method.
1048 ///
1049 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1050                                     const MachineInstr *DelayedMI)
1051 {
1052   // "added after" instructions of the original instr
1053   std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1054
1055   if (DEBUG_RA && OrigAft.size() > 0) {
1056     std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1057     std::cerr << "         to last delay slot instrn: " << *DelayedMI;
1058   }
1059
1060   // "added after" instructions of the delayed instr
1061   std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1062
1063   // go thru all the "added after instructions" of the original instruction
1064   // and append them to the "added after instructions" of the delayed
1065   // instructions
1066   DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1067
1068   // empty the "added after instructions" of the original instruction
1069   OrigAft.clear();
1070 }
1071
1072
1073 void PhyRegAlloc::colorIncomingArgs()
1074 {
1075   MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1076                       AddedInstrAtEntry.InstrnsAfter);
1077 }
1078
1079
1080 /// Determine whether the suggested color of each live range is really usable,
1081 /// and then call its setSuggestedColorUsable() method to record the answer. A
1082 /// suggested color is NOT usable when the suggested color is volatile AND
1083 /// when there are call interferences.
1084 ///
1085 void PhyRegAlloc::markUnusableSugColors()
1086 {
1087   LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();   
1088   LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();   
1089
1090   for (; HMI != HMIEnd ; ++HMI ) {
1091     if (HMI->first) { 
1092       LiveRange *L = HMI->second;      // get the LiveRange
1093       if (L && L->hasSuggestedColor ())
1094         L->setSuggestedColorUsable
1095           (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1096              && L->isCallInterference ()));
1097     }
1098   } // for all LR's in hash map
1099 }
1100
1101
1102 /// For each live range that is spilled, allocates a new spill position on the
1103 /// stack, and set the stack offsets of the live range that will be spilled to
1104 /// that position. This must be called just after coloring the LRs.
1105 ///
1106 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1107   if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1108
1109   LiveRangeMapType::const_iterator HMI    = LRI->getLiveRangeMap()->begin();   
1110   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();   
1111
1112   for ( ; HMI != HMIEnd ; ++HMI) {
1113     if (HMI->first && HMI->second) {
1114       LiveRange *L = HMI->second;       // get the LiveRange
1115       if (L->isMarkedForSpill()) {      // NOTE: allocating size of long Type **
1116         int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
1117         L->setSpillOffFromFP(stackOffset);
1118         if (DEBUG_RA)
1119           std::cerr << "  LR# " << L->getUserIGNode()->getIndex()
1120                << ": stack-offset = " << stackOffset << "\n";
1121       }
1122     }
1123   } // for all LR's in hash map
1124 }
1125
1126
1127 void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
1128                                      const Value *V, int Insn, int Opnd) {
1129   LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V); 
1130   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();   
1131   AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated; 
1132   int Placement = -1; 
1133   if ((HMI != HMIEnd) && HMI->second) { 
1134     LiveRange *L = HMI->second; 
1135     assert ((L->hasColor () || L->isMarkedForSpill ()) 
1136             && "Live range exists but not colored or spilled"); 
1137     if (L->hasColor ()) { 
1138       AllocState = AllocInfo::Allocated; 
1139       Placement = MRI.getUnifiedRegNum (L->getRegClassID (), 
1140                                         L->getColor ()); 
1141     } else if (L->isMarkedForSpill ()) { 
1142       AllocState = AllocInfo::Spilled; 
1143       assert (L->hasSpillOffset () 
1144               && "Live range marked for spill but has no spill offset"); 
1145       Placement = L->getSpillOffFromFP (); 
1146     } 
1147   } 
1148   state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement)); 
1149 }
1150
1151
1152 /// Save the global register allocation decisions made by the register
1153 /// allocator so that they can be accessed later (sort of like "poor man's
1154 /// debug info").
1155 ///
1156 void PhyRegAlloc::saveState () {
1157   std::vector<AllocInfo> &state = FnAllocState[Fn];
1158   unsigned ArgNum = 0;
1159   // Arguments encoded as instruction # -1
1160   for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1161     const Argument *Arg = &*i;
1162     saveStateForValue (state, Arg, -1, ArgNum);
1163     ++ArgNum;
1164   }
1165   unsigned Insn = 0;
1166   // Instructions themselves encoded as operand # -1
1167   for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
1168     saveStateForValue (state, (*II), Insn, -1);
1169     for (unsigned i = 0; i < (*II)->getNumOperands (); ++i) {
1170       const Value *V = (*II)->getOperand (i);
1171       // Don't worry about it unless it's something whose reg. we'll need. 
1172       if (!isa<Argument> (V) && !isa<Instruction> (V)) 
1173         continue; 
1174       saveStateForValue (state, V, Insn, i);
1175     }
1176     ++Insn;
1177   }
1178 }
1179
1180
1181 /// Check the saved state filled in by saveState(), and abort if it looks
1182 /// wrong. Only used when debugging. FIXME: Currently it just prints out
1183 /// the state, which isn't quite as useful.
1184 ///
1185 void PhyRegAlloc::verifySavedState () {
1186   std::vector<AllocInfo> &state = FnAllocState[Fn];
1187   int Insn = 0;
1188   for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II) {
1189     const Instruction *I = *II;
1190     MachineCodeForInstruction &Instrs = MachineCodeForInstruction::get (I);
1191     std::cerr << "Instruction:\n" << "  " << *I << "\n"
1192               << "MachineCodeForInstruction:\n";
1193     for (unsigned i = 0, n = Instrs.size (); i != n; ++i)
1194       std::cerr << "  " << *Instrs[i] << "\n";
1195     std::cerr << "FnAllocState:\n";
1196     for (unsigned i = 0; i < state.size (); ++i) {
1197       AllocInfo &S = state[i];
1198       if (Insn == S.Instruction)
1199         std::cerr << "  " << S << "\n";
1200     }
1201     std::cerr << "----------\n";
1202     ++Insn;
1203   }
1204 }
1205
1206
1207 /// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1208 /// Constant and stuffing it inside the Module. (NOTE: Soon, there will be
1209 /// other, better ways of storing the saved state; this one is cumbersome and
1210 /// does not work well with the JIT.)
1211 ///
1212 bool PhyRegAlloc::doFinalization (Module &M) { 
1213   if (!SaveRegAllocState)
1214     return false; // Nothing to do here, unless we're saving state.
1215
1216   // If saving state into the module, just copy new elements to the
1217   // correct global.
1218   if (!SaveStateToModule) {
1219     ExportedFnAllocState = FnAllocState;
1220     // FIXME: should ONLY copy new elements in FnAllocState
1221     return false;
1222   }
1223
1224   // Convert FnAllocState to a single Constant array and add it
1225   // to the Module.
1226   ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1227   std::vector<const Type *> TV;
1228   TV.push_back (Type::UIntTy);
1229   TV.push_back (AT);
1230   PointerType *PT = PointerType::get (StructType::get (TV));
1231
1232   std::vector<Constant *> allstate;
1233   for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1234     Function *F = I;
1235     if (F->isExternal ()) continue;
1236     if (FnAllocState.find (F) == FnAllocState.end ()) {
1237       allstate.push_back (ConstantPointerNull::get (PT));
1238     } else {
1239       std::vector<AllocInfo> &state = FnAllocState[F];
1240
1241       // Convert state into an LLVM ConstantArray, and put it in a
1242       // ConstantStruct (named S) along with its size.
1243       std::vector<Constant *> stateConstants;
1244       for (unsigned i = 0, s = state.size (); i != s; ++i)
1245         stateConstants.push_back (state[i].toConstant ());
1246       unsigned Size = stateConstants.size ();
1247       ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1248       std::vector<const Type *> TV;
1249       TV.push_back (Type::UIntTy);
1250       TV.push_back (AT);
1251       StructType *ST = StructType::get (TV);
1252       std::vector<Constant *> CV;
1253       CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
1254       CV.push_back (ConstantArray::get (AT, stateConstants));
1255       Constant *S = ConstantStruct::get (ST, CV);
1256
1257       GlobalVariable *GV =
1258         new GlobalVariable (ST, true,
1259                             GlobalValue::InternalLinkage, S,
1260                             F->getName () + ".regAllocState", &M);
1261
1262       // Have: { uint, [Size x { uint, int, uint, int }] } *
1263       // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
1264       Constant *CE = ConstantExpr::getCast (ConstantPointerRef::get (GV), PT);
1265       allstate.push_back (CE);
1266     }
1267   }
1268
1269   unsigned Size = allstate.size ();
1270   // Final structure type is:
1271   // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
1272   std::vector<const Type *> TV2;
1273   TV2.push_back (Type::UIntTy);
1274   ArrayType *AT2 = ArrayType::get (PT, Size);
1275   TV2.push_back (AT2);
1276   StructType *ST2 = StructType::get (TV2);
1277   std::vector<Constant *> CV2;
1278   CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1279   CV2.push_back (ConstantArray::get (AT2, allstate));
1280   new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
1281                       ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1282                       &M);
1283   return false; // No error.
1284 }
1285
1286
1287 /// Allocate registers for the machine code previously generated for F using
1288 /// the graph-coloring algorithm.
1289 ///
1290 bool PhyRegAlloc::runOnFunction (Function &F) { 
1291   if (DEBUG_RA) 
1292     std::cerr << "\n********* Function "<< F.getName () << " ***********\n"; 
1293  
1294   Fn = &F; 
1295   MF = &MachineFunction::get (Fn); 
1296   LVI = &getAnalysis<FunctionLiveVarInfo> (); 
1297   LRI = new LiveRangeInfo (Fn, TM, RegClassList); 
1298   LoopDepthCalc = &getAnalysis<LoopInfo> (); 
1299  
1300   // Create each RegClass for the target machine and add it to the 
1301   // RegClassList.  This must be done before calling constructLiveRanges().
1302   for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)   
1303     RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (), 
1304                                           MRI.getMachineRegClass (rc))); 
1305      
1306   LRI->constructLiveRanges();            // create LR info
1307   if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1308     LRI->printLiveRanges();
1309   
1310   createIGNodeListsAndIGs();            // create IGNode list and IGs
1311
1312   buildInterferenceGraphs();            // build IGs in all reg classes
1313   
1314   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1315     // print all LRs in all reg classes
1316     for ( unsigned rc=0; rc < NumOfRegClasses  ; rc++)  
1317       RegClassList[rc]->printIGNodeList(); 
1318     
1319     // print IGs in all register classes
1320     for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1321       RegClassList[rc]->printIG();       
1322   }
1323
1324   LRI->coalesceLRs();                    // coalesce all live ranges
1325
1326   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1327     // print all LRs in all reg classes
1328     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1329       RegClassList[rc]->printIGNodeList();
1330     
1331     // print IGs in all register classes
1332     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1333       RegClassList[rc]->printIG();
1334   }
1335
1336   // mark un-usable suggested color before graph coloring algorithm.
1337   // When this is done, the graph coloring algo will not reserve
1338   // suggested color unnecessarily - they can be used by another LR
1339   markUnusableSugColors(); 
1340
1341   // color all register classes using the graph coloring algo
1342   for (unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1343     RegClassList[rc]->colorAllRegs();    
1344
1345   // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1346   // a position for such spilled LRs
1347   allocateStackSpace4SpilledLRs();
1348
1349   // Reset the temp. area on the stack before use by the first instruction.
1350   // This will also happen after updating each instruction.
1351   MF->getInfo()->popAllTempValues();
1352
1353   // color incoming args - if the correct color was not received
1354   // insert code to copy to the correct register
1355   colorIncomingArgs();
1356
1357   // Save register allocation state for this function in a Constant.
1358   if (SaveRegAllocState) {
1359     saveState();
1360     if (DEBUG_RA) { // Check our work.
1361       verifySavedState ();
1362     }
1363   }
1364
1365   // Now update the machine code with register names and add any additional
1366   // code inserted by the register allocator to the instruction stream.
1367   updateMachineCode(); 
1368
1369   if (DEBUG_RA) {
1370     std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1371     MF->dump();
1372   }
1373  
1374   // Tear down temporary data structures 
1375   for (unsigned rc = 0; rc < NumOfRegClasses; ++rc) 
1376     delete RegClassList[rc]; 
1377   RegClassList.clear (); 
1378   AddedInstrMap.clear (); 
1379   OperandsColoredMap.clear (); 
1380   ScratchRegsUsed.clear (); 
1381   AddedInstrAtEntry.clear (); 
1382   delete LRI;
1383
1384   if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n"; 
1385   return false;     // Function was not modified
1386
1387
1388 } // End llvm namespace