IA64 compat
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrSelection.cpp
index 760976509c156f325e3ab58d40181ab11042f827..0c12fe42271ed26c2140468f247a0b25e783424f 100644 (file)
 //     
 //===----------------------------------------------------------------------===//
 
+#include "llvm/CodeGen/InstrSelection.h"
 #include "llvm/Function.h"
 #include "llvm/iPHINode.h"
+#include "llvm/iOther.h"
 #include "llvm/Pass.h"
 #include "llvm/CodeGen/InstrForest.h"
-#include "llvm/CodeGen/InstrSelection.h"
-#include "llvm/CodeGen/InstrSelectionSupport.h"
+#include "llvm/CodeGen/IntrinsicLowering.h"
 #include "llvm/CodeGen/MachineCodeForInstruction.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/Target/TargetMachine.h"
-#include "llvm/Target/TargetRegInfo.h"
+#include "llvm/Support/CFG.h"
+#include "../SparcV9RegInfo.h"
 #include "Support/CommandLine.h"
 #include "Support/LeakDetector.h"
-#include <vector>
+#include <iostream>
 
 namespace llvm {
-
-std::vector<MachineInstr*>
-FixConstantOperandsForInstr(Instruction* vmInstr, MachineInstr* minstr,
-                            TargetMachine& target);
+  std::vector<MachineInstr*>
+  FixConstantOperandsForInstr(Instruction *I, MachineInstr *MI,
+                              TargetMachine &TM);
+}
 
 namespace {
   //===--------------------------------------------------------------------===//
@@ -55,7 +57,7 @@ namespace {
      clEnumValN(Select_DebugInstTrees,   "i",
                 "print debugging info for instruction selection"),
      clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"),
-                              0));
+                              clEnumValEnd));
 
 
   //===--------------------------------------------------------------------===//
@@ -73,7 +75,7 @@ namespace {
     void PostprocessMachineCodeForTree(InstructionNode* instrNode,
                                        int ruleForNode, short* nts);
   public:
-    InstructionSelection(TargetMachine &T) : Target(T) {}
+    InstructionSelection(TargetMachine &TM) : Target(TM) {}
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
@@ -84,7 +86,16 @@ namespace {
   };
 }
 
-namespace llvm {
+TmpInstruction::TmpInstruction(Value *s1, Value *s2, const std::string &name)
+  : Instruction(s1->getType(), Instruction::UserOp1, name)
+{
+  Operands.push_back(Use(s1, this));  // s1 must be non-null
+  if (s2)
+    Operands.push_back(Use(s2, this));
+
+  // TmpInstructions should not be garbage checked.
+  LeakDetector::removeGarbageObject(this);
+}
 
 TmpInstruction::TmpInstruction(MachineCodeForInstruction& mcfi,
                                Value *s1, Value *s2, const std::string &name)
@@ -99,9 +110,9 @@ TmpInstruction::TmpInstruction(MachineCodeForInstruction& mcfi,
   // TmpInstructions should not be garbage checked.
   LeakDetector::removeGarbageObject(this);
 }
-  
+
 // Constructor that requires the type of the temporary to be specified.
-// Both S1 and S2 may be NULL.(
+// Both S1 and S2 may be NULL.
 TmpInstruction::TmpInstruction(MachineCodeForInstruction& mcfi,
                                const Type *Ty, Value *s1, Value* s2,
                                const std::string &name)
@@ -118,15 +129,37 @@ TmpInstruction::TmpInstruction(MachineCodeForInstruction& mcfi,
   LeakDetector::removeGarbageObject(this);
 }
 
-} // End llvm namespace
+bool InstructionSelection::runOnFunction(Function &F) {
+  // First pass - Walk the function, lowering any calls to intrinsic functions
+  // which the instruction selector cannot handle.
+  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
+    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
+      if (CallInst *CI = dyn_cast<CallInst>(I++))
+        if (Function *F = CI->getCalledFunction())
+          switch (F->getIntrinsicID()) {
+          case Intrinsic::not_intrinsic:
+          case Intrinsic::vastart:
+          case Intrinsic::vacopy:
+          case Intrinsic::vaend:
+            // We directly implement these intrinsics.  Note that this knowledge
+            // is incestuously entangled with the code in
+            // SparcInstrSelection.cpp and must be updated when it is updated.
+            // Since ALL of the code in this library is incestuously intertwined
+            // with it already and sparc specific, we will live with this.
+            break;
+          default:
+            // All other intrinsic calls we must lower.
+            Instruction *Before = CI->getPrev();
+            Target.getIntrinsicLowering().LowerIntrinsicCall(CI);
+            if (Before) {        // Move iterator to instruction after call
+              I = Before;  ++I;
+            } else {
+              I = BB->begin();
+            }
+          }
 
-bool InstructionSelection::runOnFunction(Function &F)
-{
-  //
   // Build the instruction trees to be given as inputs to BURG.
-  // 
   InstrForest instrForest(&F);
-  
   if (SelectDebugLevel >= Select_DebugInstTrees) {
     std::cerr << "\n\n*** Input to instruction selection for function "
               << F.getName() << "\n\n" << F
@@ -135,9 +168,7 @@ bool InstructionSelection::runOnFunction(Function &F)
     instrForest.dump();
   }
   
-  //
   // Invoke BURG instruction selection for each tree
-  // 
   for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
        RI != instrForest.roots_end(); ++RI) {
     InstructionNode* basicNode = *RI;
@@ -145,7 +176,6 @@ bool InstructionSelection::runOnFunction(Function &F)
       
     // Invoke BURM to label each tree node with a state
     burm_label(basicNode);
-      
     if (SelectDebugLevel >= Select_DebugBurgTrees) {
       printcover(basicNode, 1, 0);
       std::cerr << "\nCover cost == " << treecost(basicNode, 1, 0) <<"\n\n";
@@ -156,19 +186,30 @@ bool InstructionSelection::runOnFunction(Function &F)
     SelectInstructionsForTree(basicNode, /*goalnt*/1);
   }
   
-  //
-  // Create the MachineBasicBlock records and add all of the MachineInstrs
-  // defined in the MachineCodeForInstruction objects to also live in the
-  // MachineBasicBlock objects.
-  // 
+  // Create the MachineBasicBlocks and add all of the MachineInstrs
+  // defined in the MachineCodeForInstruction objects to the MachineBasicBlocks.
   MachineFunction &MF = MachineFunction::get(&F);
+  std::map<const BasicBlock *, MachineBasicBlock *> MBBMap;
   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
-    MachineBasicBlock *MCBB = new MachineBasicBlock(BI);
-    MF.getBasicBlockList().push_back(MCBB);
+    MachineBasicBlock *MBB = new MachineBasicBlock(BI);
+    MF.getBasicBlockList().push_back(MBB);
+    MBBMap[BI] = MBB;
 
     for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
       MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
-      MCBB->insert(MCBB->end(), mvec.begin(), mvec.end());
+      MBB->insert(MBB->end(), mvec.begin(), mvec.end());
+    }
+  }
+
+  // Initialize Machine-CFG for the function.
+  for (MachineFunction::iterator i = MF.begin (), e = MF.end (); i != e; ++i) {
+    MachineBasicBlock &MBB = *i;
+    const BasicBlock *BB = MBB.getBasicBlock ();
+    // for each successor S of BB, add MBBMap[S] as a successor of MBB.
+    for (succ_const_iterator si = succ_begin(BB), se = succ_end(BB); si != se; ++si) {
+      MachineBasicBlock *succMBB = MBBMap[*si];
+      assert (succMBB && "Can't find MachineBasicBlock for this successor");
+      MBB.addSuccessor (succMBB);
     }
   }
 
@@ -183,34 +224,30 @@ bool InstructionSelection::runOnFunction(Function &F)
   return true;
 }
 
-
-//-------------------------------------------------------------------------
-// This method inserts phi elimination code for all BBs in a method
-//-------------------------------------------------------------------------
-
-void
-InstructionSelection::InsertCodeForPhis(Function &F) {
-  // for all basic blocks in function
-  //
+/// InsertCodeForPhis - This method inserts Phi elimination code for
+/// all Phi nodes in the given function.  After this method is called,
+/// the Phi nodes still exist in the LLVM code, but copies are added to the
+/// machine code.
+///
+void InstructionSelection::InsertCodeForPhis(Function &F) {
+  // Iterate over every Phi node PN in F:
   MachineFunction &MF = MachineFunction::get(&F);
   for (MachineFunction::iterator BB = MF.begin(); BB != MF.end(); ++BB) {
     for (BasicBlock::const_iterator IIt = BB->getBasicBlock()->begin();
          const PHINode *PN = dyn_cast<PHINode>(IIt); ++IIt) {
-      // FIXME: This is probably wrong...
-      Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
-
+      // Create a new temporary register to hold the result of the Phi copy.
       // The leak detector shouldn't track these nodes.  They are not garbage,
       // even though their parent field is never filled in.
-      //
+      Value *PhiCpRes = new PHINode(PN->getType(), PN->getName() + ":PhiCp");
       LeakDetector::removeGarbageObject(PhiCpRes);
 
-      // for each incoming value of the phi, insert phi elimination
-      //
+      // For each of PN's incoming values, insert a copy in the corresponding
+      // predecessor block.
+      MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get (PN);
       for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
-        // insert the copy instruction to the predecessor BB
         std::vector<MachineInstr*> mvec, CpVec;
-        Target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
-                                          mvec);
+        Target.getRegInfo()->cpValue2Value(PN->getIncomingValue(i), 
+                                           PhiCpRes, mvec);
         for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
              MI != mvec.end(); ++MI) {
           std::vector<MachineInstr*> CpVec2 =
@@ -218,23 +255,24 @@ InstructionSelection::InsertCodeForPhis(Function &F) {
           CpVec2.push_back(*MI);
           CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
         }
-        
+        // Insert the copy instructions into the predecessor BB.        
         InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
+        MCforPN.insert (MCforPN.end (), CpVec.begin (), CpVec.end ());
       }
-      
+      // Insert a copy instruction from PhiCpRes to PN.
       std::vector<MachineInstr*> mvec;
-      Target.getRegInfo().cpValue2Value(PhiCpRes, const_cast<PHINode*>(PN),
+      Target.getRegInfo()->cpValue2Value(PhiCpRes, const_cast<PHINode*>(PN),
                                         mvec);
       BB->insert(BB->begin(), mvec.begin(), mvec.end());
+      MCforPN.insert (MCforPN.end (), mvec.begin (), mvec.end ());
     }  // for each Phi Instr in BB
   } // for all BBs in function
 }
 
-//-------------------------------------------------------------------------
-// Thid method inserts a copy instruction to a predecessor BB as a result
-// of phi elimination.
-//-------------------------------------------------------------------------
-
+/// InsertPhiElimInstructions - Inserts the instructions in CpVec into the
+/// MachineBasicBlock corresponding to BB, just before its terminator
+/// instruction. This is used by InsertCodeForPhis() to insert copies, above.
+///
 void
 InstructionSelection::InsertPhiElimInstructions(BasicBlock *BB,
                                         const std::vector<MachineInstr*>& CpVec)
@@ -244,22 +282,9 @@ InstructionSelection::InsertPhiElimInstructions(BasicBlock *BB,
   MachineInstr *FirstMIOfTerm = MC4Term.front();
   assert (FirstMIOfTerm && "No Machine Instrs for terminator");
 
-  MachineFunction &MF = MachineFunction::get(BB->getParent());
-
-  // FIXME: if PHI instructions existed in the machine code, this would be
-  // unnecessary.
-  MachineBasicBlock *MBB = 0;
-  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
-    if (I->getBasicBlock() == BB) {
-      MBB = I;
-      break;
-    }
-
-  // find the position of first machine instruction generated by the
-  // terminator of this BB
-  MachineBasicBlock::iterator MCIt =
-    std::find(MBB->begin(), MBB->end(), FirstMIOfTerm);
-
+  MachineBasicBlock *MBB = FirstMIOfTerm->getParent();
+  assert(MBB && "Machine BB for predecessor's terminator not found");
+  MachineBasicBlock::iterator MCIt = FirstMIOfTerm;
   assert(MCIt != MBB->end() && "Start inst of terminator not found");
   
   // insert the copy instructions just before the first machine instruction
@@ -384,8 +409,6 @@ InstructionSelection::PostprocessMachineCodeForTree(InstructionNode* instrNode,
 // createInstructionSelectionPass - Public entrypoint for instruction selection
 // and this file as a whole...
 //
-FunctionPass *createInstructionSelectionPass(TargetMachine &T) {
-  return new InstructionSelection(T);
+FunctionPass *llvm::createInstructionSelectionPass(TargetMachine &TM) {
+  return new InstructionSelection(TM);
 }
-
-} // End llvm namespace