Make EmitNode take a SDNode instead of a NodeInfo*
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a simple two pass scheduler.  The first pass attempts to push
11 // backward any lengthy instructions and critical paths.  The second pass packs
12 // instructions into semi-optimal time slots.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "sched"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetInstrItineraries.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Constant.h"
27 #include <iostream>
28 using namespace llvm;
29
30
31 /// CountResults - The results of target nodes have register or immediate
32 /// operands first, then an optional chain, and optional flag operands (which do
33 /// not go into the machine instrs.)
34 static unsigned CountResults(SDNode *Node) {
35   unsigned N = Node->getNumValues();
36   while (N && Node->getValueType(N - 1) == MVT::Flag)
37     --N;
38   if (N && Node->getValueType(N - 1) == MVT::Other)
39     --N;    // Skip over chain result.
40   return N;
41 }
42
43 /// CountOperands  The inputs to target nodes have any actual inputs first,
44 /// followed by an optional chain operand, then flag operands.  Compute the
45 /// number of actual operands that  will go into the machine instr.
46 static unsigned CountOperands(SDNode *Node) {
47   unsigned N = Node->getNumOperands();
48   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
49     --N;
50   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
51     --N; // Ignore chain if it exists.
52   return N;
53 }
54
55 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
56 /// 
57 void ScheduleDAG::PrepareNodeInfo() {
58   // Allocate node information
59   Info = new NodeInfo[NodeCount];
60
61   unsigned i = 0;
62   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
63        E = DAG.allnodes_end(); I != E; ++I, ++i) {
64     // Fast reference to node schedule info
65     NodeInfo* NI = &Info[i];
66     // Set up map
67     Map[I] = NI;
68     // Set node
69     NI->Node = I;
70     // Set pending visit count
71     NI->setPending(I->use_size());
72   }
73 }
74
75 /// IdentifyGroups - Put flagged nodes into groups.
76 ///
77 void ScheduleDAG::IdentifyGroups() {
78   for (unsigned i = 0, N = NodeCount; i < N; i++) {
79     NodeInfo* NI = &Info[i];
80     SDNode *Node = NI->Node;
81
82     // For each operand (in reverse to only look at flags)
83     for (unsigned N = Node->getNumOperands(); 0 < N--;) {
84       // Get operand
85       SDOperand Op = Node->getOperand(N);
86       // No more flags to walk
87       if (Op.getValueType() != MVT::Flag) break;
88       // Add to node group
89       AddToGroup(getNI(Op.Val), NI);
90       // Let everyone else know
91       HasGroups = true;
92     }
93   }
94 }
95
96 static unsigned CreateVirtualRegisters(MachineInstr *MI,
97                                        unsigned NumResults,
98                                        SSARegMap *RegMap,
99                                        const TargetInstrDescriptor &II) {
100   // Create the result registers for this node and add the result regs to
101   // the machine instruction.
102   const TargetOperandInfo *OpInfo = II.OpInfo;
103   unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
104   MI->addRegOperand(ResultReg, MachineOperand::Def);
105   for (unsigned i = 1; i != NumResults; ++i) {
106     assert(OpInfo[i].RegClass && "Isn't a register operand!");
107     MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
108                       MachineOperand::Def);
109   }
110   return ResultReg;
111 }
112
113 /// getVR - Return the virtual register corresponding to the specified result
114 /// of the specified node.
115 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
116   std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
117   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
118   return I->second + Op.ResNo;
119 }
120
121
122 /// AddOperand - Add the specified operand to the specified machine instr.  II
123 /// specifies the instruction information for the node, and IIOpNum is the
124 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
125 /// assertions only.
126 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
127                              unsigned IIOpNum,
128                              const TargetInstrDescriptor *II,
129                              std::map<SDNode*, unsigned> &VRBaseMap) {
130   if (Op.isTargetOpcode()) {
131     // Note that this case is redundant with the final else block, but we
132     // include it because it is the most common and it makes the logic
133     // simpler here.
134     assert(Op.getValueType() != MVT::Other &&
135            Op.getValueType() != MVT::Flag &&
136            "Chain and flag operands should occur at end of operand list!");
137     
138     // Get/emit the operand.
139     unsigned VReg = getVR(Op, VRBaseMap);
140     MI->addRegOperand(VReg, MachineOperand::Use);
141     
142     // Verify that it is right.
143     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
144     if (II) {
145       assert(II->OpInfo[IIOpNum].RegClass &&
146              "Don't have operand info for this instruction!");
147       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
148              "Register class of operand and regclass of use don't agree!");
149     }
150   } else if (ConstantSDNode *C =
151              dyn_cast<ConstantSDNode>(Op)) {
152     MI->addZeroExtImm64Operand(C->getValue());
153   } else if (RegisterSDNode*R =
154              dyn_cast<RegisterSDNode>(Op)) {
155     MI->addRegOperand(R->getReg(), MachineOperand::Use);
156   } else if (GlobalAddressSDNode *TGA =
157              dyn_cast<GlobalAddressSDNode>(Op)) {
158     MI->addGlobalAddressOperand(TGA->getGlobal(), false, TGA->getOffset());
159   } else if (BasicBlockSDNode *BB =
160              dyn_cast<BasicBlockSDNode>(Op)) {
161     MI->addMachineBasicBlockOperand(BB->getBasicBlock());
162   } else if (FrameIndexSDNode *FI =
163              dyn_cast<FrameIndexSDNode>(Op)) {
164     MI->addFrameIndexOperand(FI->getIndex());
165   } else if (ConstantPoolSDNode *CP = 
166              dyn_cast<ConstantPoolSDNode>(Op)) {
167     int Offset = CP->getOffset();
168     unsigned Align = CP->getAlignment();
169     // MachineConstantPool wants an explicit alignment.
170     if (Align == 0) {
171       if (CP->get()->getType() == Type::DoubleTy)
172         Align = 3;  // always 8-byte align doubles.
173       else
174         Align = TM.getTargetData()
175           .getTypeAlignmentShift(CP->get()->getType());
176     }
177     
178     unsigned Idx = ConstPool->getConstantPoolIndex(CP->get(), Align);
179     MI->addConstantPoolIndexOperand(Idx, Offset);
180   } else if (ExternalSymbolSDNode *ES = 
181              dyn_cast<ExternalSymbolSDNode>(Op)) {
182     MI->addExternalSymbolOperand(ES->getSymbol(), false);
183   } else {
184     assert(Op.getValueType() != MVT::Other &&
185            Op.getValueType() != MVT::Flag &&
186            "Chain and flag operands should occur at end of operand list!");
187     unsigned VReg = getVR(Op, VRBaseMap);
188     MI->addRegOperand(VReg, MachineOperand::Use);
189     
190     // Verify that it is right.
191     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
192     if (II) {
193       assert(II->OpInfo[IIOpNum].RegClass &&
194              "Don't have operand info for this instruction!");
195       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
196              "Register class of operand and regclass of use don't agree!");
197     }
198   }
199   
200 }
201
202
203 /// EmitNode - Generate machine code for an node and needed dependencies.
204 ///
205 void ScheduleDAG::EmitNode(SDNode *Node, 
206                            std::map<SDNode*, unsigned> &VRBaseMap) {
207   unsigned VRBase = 0;                 // First virtual register for node
208   
209   // If machine instruction
210   if (Node->isTargetOpcode()) {
211     unsigned Opc = Node->getTargetOpcode();
212     const TargetInstrDescriptor &II = TII->get(Opc);
213
214     unsigned NumResults = CountResults(Node);
215     unsigned NodeOperands = CountOperands(Node);
216     unsigned NumMIOperands = NodeOperands + NumResults;
217 #ifndef NDEBUG
218     assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
219            "#operands for dag node doesn't match .td file!"); 
220 #endif
221
222     // Create the new machine instruction.
223     MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
224     
225     // Add result register values for things that are defined by this
226     // instruction.
227     
228     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
229     // the CopyToReg'd destination register instead of creating a new vreg.
230     if (NumResults == 1) {
231       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
232            UI != E; ++UI) {
233         SDNode *Use = *UI;
234         if (Use->getOpcode() == ISD::CopyToReg && 
235             Use->getOperand(2).Val == Node) {
236           unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
237           if (MRegisterInfo::isVirtualRegister(Reg)) {
238             VRBase = Reg;
239             MI->addRegOperand(Reg, MachineOperand::Def);
240             break;
241           }
242         }
243       }
244     }
245     
246     // Otherwise, create new virtual registers.
247     if (NumResults && VRBase == 0)
248       VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
249     
250     // Emit all of the actual operands of this instruction, adding them to the
251     // instruction as appropriate.
252     for (unsigned i = 0; i != NodeOperands; ++i)
253       AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
254     
255     // Now that we have emitted all operands, emit this instruction itself.
256     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
257       BB->insert(BB->end(), MI);
258     } else {
259       // Insert this instruction into the end of the basic block, potentially
260       // taking some custom action.
261       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
262     }
263   } else {
264     switch (Node->getOpcode()) {
265     default:
266       Node->dump(); 
267       assert(0 && "This target-independent node should have been selected!");
268     case ISD::EntryToken: // fall thru
269     case ISD::TokenFactor:
270       break;
271     case ISD::CopyToReg: {
272       unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
273       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
274       if (InReg != DestReg)   // Coallesced away the copy?
275         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
276                           RegMap->getRegClass(InReg));
277       break;
278     }
279     case ISD::CopyFromReg: {
280       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
281       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
282         VRBase = SrcReg;  // Just use the input register directly!
283         break;
284       }
285
286       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
287       // the CopyToReg'd destination register instead of creating a new vreg.
288       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
289            UI != E; ++UI) {
290         SDNode *Use = *UI;
291         if (Use->getOpcode() == ISD::CopyToReg && 
292             Use->getOperand(2).Val == Node) {
293           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
294           if (MRegisterInfo::isVirtualRegister(DestReg)) {
295             VRBase = DestReg;
296             break;
297           }
298         }
299       }
300
301       // Figure out the register class to create for the destreg.
302       const TargetRegisterClass *TRC = 0;
303       if (VRBase) {
304         TRC = RegMap->getRegClass(VRBase);
305       } else {
306
307         // Pick the register class of the right type that contains this physreg.
308         for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
309              E = MRI->regclass_end(); I != E; ++I)
310           if ((*I)->hasType(Node->getValueType(0)) &&
311               (*I)->contains(SrcReg)) {
312             TRC = *I;
313             break;
314           }
315         assert(TRC && "Couldn't find register class for reg copy!");
316       
317         // Create the reg, emit the copy.
318         VRBase = RegMap->createVirtualRegister(TRC);
319       }
320       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
321       break;
322     }
323     case ISD::INLINEASM: {
324       unsigned NumOps = Node->getNumOperands();
325       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
326         --NumOps;  // Ignore the flag operand.
327       
328       // Create the inline asm machine instruction.
329       MachineInstr *MI =
330         new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
331
332       // Add the asm string as an external symbol operand.
333       const char *AsmStr =
334         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
335       MI->addExternalSymbolOperand(AsmStr, false);
336       
337       // Add all of the operand registers to the instruction.
338       for (unsigned i = 2; i != NumOps;) {
339         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
340         unsigned NumVals = Flags >> 3;
341         
342         MI->addZeroExtImm64Operand(Flags);
343         ++i;  // Skip the ID value.
344         
345         switch (Flags & 7) {
346         default: assert(0 && "Bad flags!");
347         case 1:  // Use of register.
348           for (; NumVals; --NumVals, ++i) {
349             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
350             MI->addMachineRegOperand(Reg, MachineOperand::Use);
351           }
352           break;
353         case 2:   // Def of register.
354           for (; NumVals; --NumVals, ++i) {
355             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
356             MI->addMachineRegOperand(Reg, MachineOperand::Def);
357           }
358           break;
359         case 3: { // Immediate.
360           assert(NumVals == 1 && "Unknown immediate value!");
361           uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
362           MI->addZeroExtImm64Operand(Val);
363           ++i;
364           break;
365         }
366         case 4:  // Addressing mode.
367           // The addressing mode has been selected, just add all of the
368           // operands to the machine instruction.
369           for (; NumVals; --NumVals, ++i)
370             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
371           break;
372         }
373       }
374       break;
375     }
376     }
377   }
378
379   assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
380   VRBaseMap[Node] = VRBase;
381 }
382
383 void ScheduleDAG::EmitNoop() {
384   TII->insertNoop(*BB, BB->end());
385 }
386
387 /// EmitAll - Emit all nodes in schedule sorted order.
388 ///
389 void ScheduleDAG::EmitAll() {
390   std::map<SDNode*, unsigned> VRBaseMap;
391   
392   // For each node in the ordering
393   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
394     // Get the scheduling info
395     NodeInfo *NI = Ordering[i];
396     if (NI->isInGroup()) {
397       NodeGroupIterator NGI(Ordering[i]);
398       while (NodeInfo *NI = NGI.next()) EmitNode(NI->Node, VRBaseMap);
399     } else {
400       EmitNode(NI->Node, VRBaseMap);
401     }
402   }
403 }
404
405 /// isFlagDefiner - Returns true if the node defines a flag result.
406 static bool isFlagDefiner(SDNode *A) {
407   unsigned N = A->getNumValues();
408   return N && A->getValueType(N - 1) == MVT::Flag;
409 }
410
411 /// isFlagUser - Returns true if the node uses a flag result.
412 ///
413 static bool isFlagUser(SDNode *A) {
414   unsigned N = A->getNumOperands();
415   return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
416 }
417
418 /// printNI - Print node info.
419 ///
420 void ScheduleDAG::printNI(std::ostream &O, NodeInfo *NI) const {
421 #ifndef NDEBUG
422   SDNode *Node = NI->Node;
423   O << " "
424     << std::hex << Node << std::dec
425     << ", Lat=" << NI->Latency
426     << ", Slot=" << NI->Slot
427     << ", ARITY=(" << Node->getNumOperands() << ","
428                    << Node->getNumValues() << ")"
429     << " " << Node->getOperationName(&DAG);
430   if (isFlagDefiner(Node)) O << "<#";
431   if (isFlagUser(Node)) O << ">#";
432 #endif
433 }
434
435 /// printChanges - Hilight changes in order caused by scheduling.
436 ///
437 void ScheduleDAG::printChanges(unsigned Index) const {
438 #ifndef NDEBUG
439   // Get the ordered node count
440   unsigned N = Ordering.size();
441   // Determine if any changes
442   unsigned i = 0;
443   for (; i < N; i++) {
444     NodeInfo *NI = Ordering[i];
445     if (NI->Preorder != i) break;
446   }
447   
448   if (i < N) {
449     std::cerr << Index << ". New Ordering\n";
450     
451     for (i = 0; i < N; i++) {
452       NodeInfo *NI = Ordering[i];
453       std::cerr << "  " << NI->Preorder << ". ";
454       printNI(std::cerr, NI);
455       std::cerr << "\n";
456       if (NI->isGroupDominator()) {
457         NodeGroup *Group = NI->Group;
458         for (NIIterator NII = Group->group_begin(), E = Group->group_end();
459              NII != E; NII++) {
460           std::cerr << "          ";
461           printNI(std::cerr, *NII);
462           std::cerr << "\n";
463         }
464       }
465     }
466   } else {
467     std::cerr << Index << ". No Changes\n";
468   }
469 #endif
470 }
471
472 /// print - Print ordering to specified output stream.
473 ///
474 void ScheduleDAG::print(std::ostream &O) const {
475 #ifndef NDEBUG
476   using namespace std;
477   O << "Ordering\n";
478   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
479     NodeInfo *NI = Ordering[i];
480     printNI(O, NI);
481     O << "\n";
482     if (NI->isGroupDominator()) {
483       NodeGroup *Group = NI->Group;
484       for (NIIterator NII = Group->group_begin(), E = Group->group_end();
485            NII != E; NII++) {
486         O << "    ";
487         printNI(O, *NII);
488         O << "\n";
489       }
490     }
491   }
492 #endif
493 }
494
495 void ScheduleDAG::dump(const char *tag) const {
496   std::cerr << tag; dump();
497 }
498
499 void ScheduleDAG::dump() const {
500   print(std::cerr);
501 }
502
503 /// Run - perform scheduling.
504 ///
505 MachineBasicBlock *ScheduleDAG::Run() {
506   TII = TM.getInstrInfo();
507   MRI = TM.getRegisterInfo();
508   RegMap = BB->getParent()->getSSARegMap();
509   ConstPool = BB->getParent()->getConstantPool();
510
511   // Number the nodes
512   NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
513
514   Schedule();
515   return BB;
516 }
517
518
519 /// CountInternalUses - Returns the number of edges between the two nodes.
520 ///
521 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
522   unsigned N = 0;
523   for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
524     SDOperand Op = U->Node->getOperand(M);
525     if (Op.Val == D->Node) N++;
526   }
527
528   return N;
529 }
530
531 //===----------------------------------------------------------------------===//
532 /// Add - Adds a definer and user pair to a node group.
533 ///
534 void ScheduleDAG::AddToGroup(NodeInfo *D, NodeInfo *U) {
535   // Get current groups
536   NodeGroup *DGroup = D->Group;
537   NodeGroup *UGroup = U->Group;
538   // If both are members of groups
539   if (DGroup && UGroup) {
540     // There may have been another edge connecting 
541     if (DGroup == UGroup) return;
542     // Add the pending users count
543     DGroup->addPending(UGroup->getPending());
544     // For each member of the users group
545     NodeGroupIterator UNGI(U);
546     while (NodeInfo *UNI = UNGI.next() ) {
547       // Change the group
548       UNI->Group = DGroup;
549       // For each member of the definers group
550       NodeGroupIterator DNGI(D);
551       while (NodeInfo *DNI = DNGI.next() ) {
552         // Remove internal edges
553         DGroup->addPending(-CountInternalUses(DNI, UNI));
554       }
555     }
556     // Merge the two lists
557     DGroup->group_insert(DGroup->group_end(),
558                          UGroup->group_begin(), UGroup->group_end());
559   } else if (DGroup) {
560     // Make user member of definers group
561     U->Group = DGroup;
562     // Add users uses to definers group pending
563     DGroup->addPending(U->Node->use_size());
564     // For each member of the definers group
565     NodeGroupIterator DNGI(D);
566     while (NodeInfo *DNI = DNGI.next() ) {
567       // Remove internal edges
568       DGroup->addPending(-CountInternalUses(DNI, U));
569     }
570     DGroup->group_push_back(U);
571   } else if (UGroup) {
572     // Make definer member of users group
573     D->Group = UGroup;
574     // Add definers uses to users group pending
575     UGroup->addPending(D->Node->use_size());
576     // For each member of the users group
577     NodeGroupIterator UNGI(U);
578     while (NodeInfo *UNI = UNGI.next() ) {
579       // Remove internal edges
580       UGroup->addPending(-CountInternalUses(D, UNI));
581     }
582     UGroup->group_insert(UGroup->group_begin(), D);
583   } else {
584     D->Group = U->Group = DGroup = new NodeGroup();
585     DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
586                        CountInternalUses(D, U));
587     DGroup->group_push_back(D);
588     DGroup->group_push_back(U);
589
590     if (HeadNG == NULL)
591       HeadNG = DGroup;
592     if (TailNG != NULL)
593       TailNG->Next = DGroup;
594     TailNG = DGroup;
595   }
596 }