Remove a useless statement.
[oota-llvm.git] / lib / VMCore / Verifier.cpp
index 9f4a6c894d922a0d83498dd44489530f94c42ee3..5983204aa0550a077e34cf66e04c024c06669e4d 100644 (file)
@@ -47,6 +47,7 @@
 #include "llvm/Module.h"
 #include "llvm/ModuleProvider.h"
 #include "llvm/DerivedTypes.h"
+#include "llvm/InlineAsm.h"
 #include "llvm/Instructions.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/PassManager.h"
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/InstVisitor.h"
+#include "llvm/Support/Streams.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Compiler.h"
 #include <algorithm>
-#include <iostream>
 #include <sstream>
+#include <cstdarg>
 using namespace llvm;
 
 namespace {  // Anonymous namespace for class
 
-  struct Verifier : public FunctionPass, InstVisitor<Verifier> {
+  struct VISIBILITY_HIDDEN
+     Verifier : public FunctionPass, InstVisitor<Verifier> {
     bool Broken;          // Is this module found to be broken?
     bool RealPass;        // Are we not being run by a PassManager?
     VerifierFailureAction action;
@@ -100,13 +105,14 @@ namespace {  // Anonymous namespace for class
       // returning back to the pass manager, or else the pass manager may try to
       // run other passes on the broken module.
       if (RealPass)
-        abortIfBroken();
+        return abortIfBroken();
       return false;
     }
 
     bool runOnFunction(Function &F) {
       // Get dominator information if we are being run by PassManager
       if (RealPass) EF = &getAnalysis<ETForest>();
+      
       visit(F);
       InstsInThisBlock.clear();
 
@@ -114,7 +120,7 @@ namespace {  // Anonymous namespace for class
       // returning back to the pass manager, or else the pass manager may try to
       // run other passes on the broken module.
       if (RealPass)
-        abortIfBroken();
+        return abortIfBroken();
 
       return false;
     }
@@ -133,8 +139,7 @@ namespace {  // Anonymous namespace for class
         visitGlobalVariable(*I);
 
       // If the module is broken, abort at this time.
-      abortIfBroken();
-      return false;
+      return abortIfBroken();
     }
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
@@ -146,27 +151,24 @@ namespace {  // Anonymous namespace for class
     /// abortIfBroken - If the module is broken and we are supposed to abort on
     /// this condition, do so.
     ///
-    void abortIfBroken() {
-      if (Broken)
-      {
+    bool abortIfBroken() {
+      if (Broken) {
         msgs << "Broken module found, ";
-        switch (action)
-        {
+        switch (action) {
           case AbortProcessAction:
             msgs << "compilation aborted!\n";
-            std::cerr << msgs.str();
+            cerr << msgs.str();
             abort();
-          case ThrowExceptionAction:
-            msgs << "verification terminated.\n";
-            throw msgs.str();
           case PrintMessageAction:
             msgs << "verification continues.\n";
-            std::cerr << msgs.str();
-            break;
+            cerr << msgs.str();
+            return false;
           case ReturnStatusAction:
-            break;
+            msgs << "compilation terminated.\n";
+            return Broken;
         }
       }
+      return false;
     }
 
 
@@ -176,11 +178,26 @@ namespace {  // Anonymous namespace for class
     void visitGlobalVariable(GlobalVariable &GV);
     void visitFunction(Function &F);
     void visitBasicBlock(BasicBlock &BB);
+    void visitTruncInst(TruncInst &I);
+    void visitZExtInst(ZExtInst &I);
+    void visitSExtInst(SExtInst &I);
+    void visitFPTruncInst(FPTruncInst &I);
+    void visitFPExtInst(FPExtInst &I);
+    void visitFPToUIInst(FPToUIInst &I);
+    void visitFPToSIInst(FPToSIInst &I);
+    void visitUIToFPInst(UIToFPInst &I);
+    void visitSIToFPInst(SIToFPInst &I);
+    void visitIntToPtrInst(IntToPtrInst &I);
+    void visitPtrToIntInst(PtrToIntInst &I);
+    void visitBitCastInst(BitCastInst &I);
     void visitPHINode(PHINode &PN);
     void visitBinaryOperator(BinaryOperator &B);
+    void visitICmpInst(ICmpInst &IC);
+    void visitFCmpInst(FCmpInst &FC);
     void visitShiftInst(ShiftInst &SI);
     void visitExtractElementInst(ExtractElementInst &EI);
     void visitInsertElementInst(InsertElementInst &EI);
+    void visitShuffleVectorInst(ShuffleVectorInst &EI);
     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
     void visitCallInst(CallInst &CI);
     void visitGetElementPtrInst(GetElementPtrInst &GEP);
@@ -195,13 +212,14 @@ namespace {  // Anonymous namespace for class
     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
 
+    void VerifyIntrinsicPrototype(Function *F, ...);
 
     void WriteValue(const Value *V) {
       if (!V) return;
       if (isa<Instruction>(V)) {
         msgs << *V;
       } else {
-        WriteAsOperand (msgs, V, true, true, Mod);
+        WriteAsOperand(msgs, V, true, Mod);
         msgs << "\n";
       }
     }
@@ -236,7 +254,7 @@ namespace {  // Anonymous namespace for class
     }
   };
 
-  RegisterOpt<Verifier> X("verify", "Module Verifier");
+  RegisterPass<Verifier> X("verify", "Module Verifier");
 } // End anonymous namespace
 
 
@@ -254,8 +272,16 @@ namespace {  // Anonymous namespace for class
 
 
 void Verifier::visitGlobalValue(GlobalValue &GV) {
-  Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
-          "Global is external, but doesn't have external linkage!", &GV);
+  Assert1(!GV.isExternal() ||
+          GV.hasExternalLinkage() ||
+          GV.hasDLLImportLinkage() ||
+          GV.hasExternalWeakLinkage(),
+  "Global is external, but doesn't have external or dllimport or weak linkage!",
+          &GV);
+
+  Assert1(!GV.hasDLLImportLinkage() || GV.isExternal(),
+          "Global is marked as dllimport, but not external", &GV);
+  
   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
           "Only global variables can have appending linkage!", &GV);
 
@@ -297,9 +323,6 @@ void Verifier::verifySymbolTable(SymbolTable &ST) {
 // visitFunction - Verify that a function is ok.
 //
 void Verifier::visitFunction(Function &F) {
-  Assert1(!F.isVarArg() || F.getCallingConv() == CallingConv::C,
-          "Varargs functions must have C calling conventions!", &F);
-
   // Check function arguments.
   const FunctionType *FT = F.getFunctionType();
   unsigned NumArgs = F.getArgumentList().size();
@@ -311,9 +334,29 @@ void Verifier::visitFunction(Function &F) {
           F.getReturnType() == Type::VoidTy,
           "Functions cannot return aggregate values!", &F);
 
+  // Check that this function meets the restrictions on this calling convention.
+  switch (F.getCallingConv()) {
+  default:
+    break;
+  case CallingConv::C:
+    break;
+  case CallingConv::CSRet:
+    Assert1(FT->getReturnType() == Type::VoidTy && 
+            FT->getNumParams() > 0 && isa<PointerType>(FT->getParamType(0)),
+            "Invalid struct-return function!", &F);
+    break;
+  case CallingConv::Fast:
+  case CallingConv::Cold:
+  case CallingConv::X86_FastCall:
+    Assert1(!F.isVarArg(),
+            "Varargs functions must have C calling conventions!", &F);
+    break;
+  }
+  
   // Check that the argument values match the function type for this function...
   unsigned i = 0;
-  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
+  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
+       I != E; ++I, ++i) {
     Assert2(I->getType() == FT->getParamType(i),
             "Argument value does not match function argument type!",
             I, FT->getParamType(i));
@@ -323,6 +366,12 @@ void Verifier::visitFunction(Function &F) {
    }
 
   if (!F.isExternal()) {
+    // Verify that this function (which has a body) is not named "llvm.*".  It
+    // is not legal to define intrinsics.
+    if (F.getName().size() >= 5)
+      Assert1(F.getName().substr(0, 5) != "llvm.",
+              "llvm intrinsics cannot be defined!", &F);
+    
     verifySymbolTable(F.getSymbolTable());
 
     // Check the entry node
@@ -435,8 +484,170 @@ void Verifier::visitSelectInst(SelectInst &SI) {
 /// a pass, if any exist, it's an error.
 ///
 void Verifier::visitUserOp1(Instruction &I) {
-  Assert1(0, "User-defined operators should not live outside of a pass!",
-          &I);
+  Assert1(0, "User-defined operators should not live outside of a pass!", &I);
+}
+
+void Verifier::visitTruncInst(TruncInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  // Get the size of the types in bits, we'll need this later
+  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
+  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
+
+  Assert1(SrcTy->isIntegral(), "Trunc only operates on integer", &I);
+  Assert1(DestTy->isIntegral(),"Trunc only produces integral", &I);
+  Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitZExtInst(ZExtInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  // Get the size of the types in bits, we'll need this later
+  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
+  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
+
+  Assert1(SrcTy->isIntegral(),"ZExt only operates on integral", &I);
+  Assert1(DestTy->isInteger(),"ZExt only produces an integer", &I);
+  Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitSExtInst(SExtInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  // Get the size of the types in bits, we'll need this later
+  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
+  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
+
+  Assert1(SrcTy->isIntegral(),"SExt only operates on integral", &I);
+  Assert1(DestTy->isInteger(),"SExt only produces an integer", &I);
+  Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitFPTruncInst(FPTruncInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+  // Get the size of the types in bits, we'll need this later
+  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
+  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
+
+  Assert1(SrcTy->isFloatingPoint(),"FPTrunc only operates on FP", &I);
+  Assert1(DestTy->isFloatingPoint(),"FPTrunc only produces an FP", &I);
+  Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitFPExtInst(FPExtInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  // Get the size of the types in bits, we'll need this later
+  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
+  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
+
+  Assert1(SrcTy->isFloatingPoint(),"FPExt only operates on FP", &I);
+  Assert1(DestTy->isFloatingPoint(),"FPExt only produces an FP", &I);
+  Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitUIToFPInst(UIToFPInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  Assert1(SrcTy->isIntegral(),"UInt2FP source must be integral", &I);
+  Assert1(DestTy->isFloatingPoint(),"UInt2FP result must be FP", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitSIToFPInst(SIToFPInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  Assert1(SrcTy->isIntegral(),"SInt2FP source must be integral", &I);
+  Assert1(DestTy->isFloatingPoint(),"SInt2FP result must be FP", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitFPToUIInst(FPToUIInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  Assert1(SrcTy->isFloatingPoint(),"FP2UInt source must be FP", &I);
+  Assert1(DestTy->isIntegral(),"FP2UInt result must be integral", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitFPToSIInst(FPToSIInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  Assert1(SrcTy->isFloatingPoint(),"FPToSI source must be FP", &I);
+  Assert1(DestTy->isIntegral(),"FP2ToI result must be integral", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
+  Assert1(DestTy->isIntegral(), "PtrToInt result must be integral", &I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  Assert1(SrcTy->isIntegral(), "IntToPtr source must be an integral", &I);
+  Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
+
+  visitInstruction(I);
+}
+
+void Verifier::visitBitCastInst(BitCastInst &I) {
+  // Get the source and destination types
+  const Type *SrcTy = I.getOperand(0)->getType();
+  const Type *DestTy = I.getType();
+
+  // Get the size of the types in bits, we'll need this later
+  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
+  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
+
+  // BitCast implies a no-op cast of type only. No bits change.
+  // However, you can't cast pointers to anything but pointers.
+  Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
+          "Bitcast requires both operands to be pointer or neither", &I);
+  Assert1(SrcBitSize == DestBitSize, "Bitcast requies types of same width", &I);
+
+  visitInstruction(I);
 }
 
 /// visitPHINode - Ensure that a PHI node is well formed.
@@ -525,6 +736,33 @@ void Verifier::visitBinaryOperator(BinaryOperator &B) {
   visitInstruction(B);
 }
 
+void Verifier::visitICmpInst(ICmpInst& IC) {
+  // Check that the operands are the same type
+  const Type* Op0Ty = IC.getOperand(0)->getType();
+  const Type* Op1Ty = IC.getOperand(1)->getType();
+  Assert1(Op0Ty == Op1Ty,
+          "Both operands to ICmp instruction are not of the same type!", &IC);
+  // Check that the operands are the right type
+  Assert1(Op0Ty->isIntegral() || Op0Ty->getTypeID() == Type::PointerTyID ||
+          (isa<PackedType>(Op0Ty) && 
+           cast<PackedType>(Op0Ty)->getElementType()->isIntegral()),
+          "Invalid operand types for ICmp instruction", &IC);
+  visitInstruction(IC);
+}
+
+void Verifier::visitFCmpInst(FCmpInst& FC) {
+  // Check that the operands are the same type
+  const Type* Op0Ty = FC.getOperand(0)->getType();
+  const Type* Op1Ty = FC.getOperand(1)->getType();
+  Assert1(Op0Ty == Op1Ty,
+          "Both operands to FCmp instruction are not of the same type!", &FC);
+  // Check that the operands are the right type
+  Assert1(Op0Ty->isFloatingPoint() || (isa<PackedType>(Op0Ty) &&
+           cast<PackedType>(Op0Ty)->getElementType()->isFloatingPoint()),
+          "Invalid operand types for FCmp instruction", &FC);
+  visitInstruction(FC);
+}
+
 void Verifier::visitShiftInst(ShiftInst &SI) {
   Assert1(SI.getType()->isInteger(),
           "Shift must return an integer result!", &SI);
@@ -536,29 +774,43 @@ void Verifier::visitShiftInst(ShiftInst &SI) {
 }
 
 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
-  Assert1(isa<PackedType>(EI.getOperand(0)->getType()),
-          "First operand to extractelement must be packed type!", &EI);
-  Assert1(EI.getOperand(1)->getType() == Type::UIntTy,
-          "Second operand to extractelement must be uint type!", &EI);
-  Assert1(EI.getType() == 
-          cast<PackedType>(EI.getOperand(0)->getType())->getElementType(),
-          "Extractelement return type must match "
-          "first operand element type!", &EI);
+  Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
+                                              EI.getOperand(1)),
+          "Invalid extractelement operands!", &EI);
   visitInstruction(EI);
 }
 
 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
-  Assert1(isa<PackedType>(IE.getOperand(0)->getType()),
-          "First operand to insertelement must be packed type!", &IE);
-  Assert1(IE.getOperand(1)->getType() == 
-          cast<PackedType>(IE.getOperand(0)->getType())->getElementType(),
-          "Second operand to insertelement must match "
-          "first operand element type!", &IE);
-  Assert1(IE.getOperand(2)->getType() == Type::UIntTy,
-          "Third operand to insertelement must be uint type!", &IE);
+  Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
+                                             IE.getOperand(1),
+                                             IE.getOperand(2)),
+          "Invalid insertelement operands!", &IE);
   visitInstruction(IE);
 }
 
+void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
+  Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
+                                             SV.getOperand(2)),
+          "Invalid shufflevector operands!", &SV);
+  Assert1(SV.getType() == SV.getOperand(0)->getType(),
+          "Result of shufflevector must match first operand type!", &SV);
+  
+  // Check to see if Mask is valid.
+  if (const ConstantPacked *MV = dyn_cast<ConstantPacked>(SV.getOperand(2))) {
+    for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
+      Assert1(isa<ConstantInt>(MV->getOperand(i)) ||
+              isa<UndefValue>(MV->getOperand(i)),
+              "Invalid shufflevector shuffle mask!", &SV);
+    }
+  } else {
+    Assert1(isa<UndefValue>(SV.getOperand(2)) || 
+            isa<ConstantAggregateZero>(SV.getOperand(2)),
+            "Invalid shufflevector shuffle mask!", &SV);
+  }
+  
+  visitInstruction(SV);
+}
+
 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
   const Type *ElTy =
     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
@@ -622,10 +874,16 @@ void Verifier::visitInstruction(Instruction &I) {
   }
 
   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
-    // Check to make sure that the "address of" an intrinsic function is never
-    // taken.
     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
+
+    // Check to make sure that only first-class-values are operands to
+    // instructions.
+    Assert1(I.getOperand(i)->getType()->isFirstClassType(),
+            "Instruction operands must be first-class values!", &I);
+  
     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
+      // Check to make sure that the "address of" an intrinsic function is never
+      // taken.
       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
               "Cannot take the address of an intrinsic!", &I);
     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
@@ -641,9 +899,41 @@ void Verifier::visitInstruction(Instruction &I) {
       if (!isa<PHINode>(I)) {
         // Invoke results are only usable in the normal destination, not in the
         // exceptional destination.
-        if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
+        if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
           OpBlock = II->getNormalDest();
-        else if (OpBlock == BB) {
+          
+          // If the normal successor of an invoke instruction has multiple
+          // predecessors, then the normal edge from the invoke is critical, so
+          // the invoke value can only be live if the destination block
+          // dominates all of it's predecessors (other than the invoke) or if
+          // the invoke value is only used by a phi in the successor.
+          if (!OpBlock->getSinglePredecessor() &&
+              EF->dominates(&BB->getParent()->getEntryBlock(), BB)) {
+            // The first case we allow is if the use is a PHI operand in the
+            // normal block, and if that PHI operand corresponds to the invoke's
+            // block.
+            bool Bad = true;
+            if (PHINode *PN = dyn_cast<PHINode>(&I))
+              if (PN->getParent() == OpBlock &&
+                  PN->getIncomingBlock(i/2) == Op->getParent())
+                Bad = false;
+            
+            // If it is used by something non-phi, then the other case is that
+            // 'OpBlock' dominates all of its predecessors other than the
+            // invoke.  In this case, the invoke value can still be used.
+            if (!Bad) {
+              for (pred_iterator PI = pred_begin(OpBlock),
+                   E = pred_end(OpBlock); PI != E; ++PI) {
+                if (*PI != II->getParent() && !EF->dominates(OpBlock, *PI)) {
+                  Bad = true;
+                  break;
+                }
+              }
+            }
+            Assert1(!Bad,
+                    "Invoke value defined on critical edge but not dead!", &I);
+          }
+        } else if (OpBlock == BB) {
           // If they are in the same basic block, make sure that the definition
           // comes before the use.
           Assert2(InstsInThisBlock.count(Op) ||
@@ -663,6 +953,9 @@ void Verifier::visitInstruction(Instruction &I) {
                 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
                 "Instruction does not dominate all uses!", Op, &I);
       }
+    } else if (isa<InlineAsm>(I.getOperand(i))) {
+      Assert1(i == 0 && isa<CallInst>(I),
+              "Cannot take the address of an inline asm!", &I);
     }
   }
   InstsInThisBlock.insert(&I);
@@ -672,336 +965,68 @@ void Verifier::visitInstruction(Instruction &I) {
 ///
 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
   Function *IF = CI.getCalledFunction();
-  const FunctionType *FT = IF->getFunctionType();
   Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
-  unsigned NumArgs = 0;
-
-  // FIXME: this should check the return type of each intrinsic as well, also
-  // arguments!
-  switch (ID) {
-  case Intrinsic::vastart:
-    Assert1(CI.getParent()->getParent()->getFunctionType()->isVarArg(),
-            "llvm.va_start intrinsic may only occur in function with variable"
-            " args!", &CI);
-    NumArgs = 1;
-    break;
-  case Intrinsic::vaend:          NumArgs = 1; break;
-  case Intrinsic::vacopy:         NumArgs = 2; break;
-
-  case Intrinsic::returnaddress:
-  case Intrinsic::frameaddress:
-    Assert1(isa<PointerType>(FT->getReturnType()),
-            "llvm.(frame|return)address must return pointers", IF);
-    Assert1(FT->getNumParams() == 1 && isa<ConstantInt>(CI.getOperand(1)),
-       "llvm.(frame|return)address require a single constant integer argument",
-            &CI);
-    NumArgs = 1;
-    break;
-
-  // Verify that read and write port have integral parameters of the correct
-  // signed-ness.
-  case Intrinsic::writeport:
-    Assert1(FT->getNumParams() == 2,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getParamType(0)->isIntegral(),
-            "First argument not unsigned int!", IF);
-    Assert1(FT->getParamType(1)->isUnsigned(),
-            "First argument not unsigned int!", IF);
-    NumArgs = 2;
-    break;
-
-  case Intrinsic::writeio:
-    Assert1(FT->getNumParams() == 2,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getParamType(0)->isFirstClassType(),
-            "First argument not a first class type!", IF);
-    Assert1(isa<PointerType>(FT->getParamType(1)),
-            "Second argument not a pointer!", IF);
-    NumArgs = 2;
-    break;
-
-  case Intrinsic::readport:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType()->isFirstClassType(),
-            "Return type is not a first class type!", IF);
-    Assert1(FT->getParamType(0)->isUnsigned(),
-            "First argument not unsigned int!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::readio: {
-    const PointerType *ParamType = dyn_cast<PointerType>(FT->getParamType(0));
-    const Type *ReturnType = FT->getReturnType();
-
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(ParamType, "First argument not a pointer!", IF);
-    Assert1(ParamType->getElementType() == ReturnType,
-            "Pointer type doesn't match return type!", IF);
-    NumArgs = 1;
-    break;
-  }
-
-  case Intrinsic::isunordered_f32:
-    Assert1(FT->getNumParams() == 2,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == Type::BoolTy,
-            "Return type is not bool!", IF);
-    Assert1(FT->getParamType(0) == FT->getParamType(1),
-            "Arguments must be of the same type!", IF);
-    Assert1(FT->getParamType(0) == Type::FloatTy,
-            "Arguments must be a 32-bit floating point type!", IF);
-    NumArgs = 2;
-    break;
-
-  case Intrinsic::isunordered_f64:
-    Assert1(FT->getNumParams() == 2,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == Type::BoolTy,
-            "Return type is not bool!", IF);
-    Assert1(FT->getParamType(0) == FT->getParamType(1),
-            "Arguments must be of the same type!", IF);
-    Assert1(FT->getParamType(0) == Type::DoubleTy,
-            "Argument is not a 64-bit floating point type!", IF);
-    NumArgs = 2;
-    break;
+  
+#define GET_INTRINSIC_VERIFIER
+#include "llvm/Intrinsics.gen"
+#undef GET_INTRINSIC_VERIFIER
+}
 
-  case Intrinsic::readcyclecounter:
-    Assert1(FT->getNumParams() == 0,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == Type::ULongTy,
-            "Return type is not ulong!", IF);
-    NumArgs = 0;
-    break;
+/// VerifyIntrinsicPrototype - TableGen emits calls to this function into
+/// Intrinsics.gen.  This implements a little state machine that verifies the
+/// prototype of intrinsics.
+void Verifier::VerifyIntrinsicPrototype(Function *F, ...) {
+  va_list VA;
+  va_start(VA, F);
+  
+  const FunctionType *FTy = F->getFunctionType();
+  
+  // Note that "arg#0" is the return type.
+  for (unsigned ArgNo = 0; 1; ++ArgNo) {
+    int TypeID = va_arg(VA, int);
+
+    if (TypeID == -1) {
+      if (ArgNo != FTy->getNumParams()+1)
+        CheckFailed("Intrinsic prototype has too many arguments!", F);
+      break;
+    }
 
-  case Intrinsic::bswap_i16:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getReturnType() == Type::UShortTy,
-            "Return type is not ushort!", IF);
-    NumArgs = 1;
-    break;    
-
-  case Intrinsic::bswap_i32:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getReturnType() == Type::UIntTy,
-            "Return type is not uint!", IF);
-    NumArgs = 1;
-    break;    
-
-  case Intrinsic::bswap_i64:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getReturnType() == Type::ULongTy,
-            "Return type is not ulong!", IF);
-    NumArgs = 1;
-    break;    
+    if (ArgNo == FTy->getNumParams()+1) {
+      CheckFailed("Intrinsic prototype has too few arguments!", F);
+      break;
+    }
     
-  case Intrinsic::ctpop_i8:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UByteTy 
-            || FT->getParamType(0) == Type::SByteTy,
-            "Argument must be a byte type!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::ctpop_i16:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UShortTy 
-            || FT->getParamType(0) == Type::ShortTy,
-            "Argument must be a short type!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::ctpop_i32:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UIntTy 
-            || FT->getParamType(0) == Type::IntTy,
-            "Argument must be an int type!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::ctpop_i64:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::ULongTy 
-            || FT->getParamType(0) == Type::LongTy,
-            "Argument must be a long type!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::ctlz_i8:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UByteTy 
-            || FT->getParamType(0) == Type::SByteTy,
-            "Argument must be a byte type!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::ctlz_i16:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UShortTy 
-            || FT->getParamType(0) == Type::ShortTy,
-            "Argument must be a short type!", IF);
-    NumArgs = 1;
-    break;
-  case Intrinsic::ctlz_i32:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UIntTy 
-            || FT->getParamType(0) == Type::IntTy,
-            "Argument must be an int type!", IF);
-    NumArgs = 1;
-    break;
-  case Intrinsic::ctlz_i64:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::ULongTy 
-            || FT->getParamType(0) == Type::LongTy,
-            "Argument must be a long type!", IF);
-    NumArgs = 1;
-    break;
-  case Intrinsic::cttz_i8:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UByteTy 
-            || FT->getParamType(0) == Type::SByteTy,
-            "Argument must be a byte type!", IF);
-    NumArgs = 1;
-    break;
-  case Intrinsic::cttz_i16:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UShortTy 
-            || FT->getParamType(0) == Type::ShortTy,
-            "Argument must be a short type!", IF);
-    NumArgs = 1;
-    break;
-  case Intrinsic::cttz_i32:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::UIntTy 
-            || FT->getParamType(0) == Type::IntTy,
-            "Argument must be an int type!", IF);
-    NumArgs = 1;
-    break;
-  case Intrinsic::cttz_i64:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type does not match source type", IF);
-    Assert1(FT->getParamType(0) == Type::ULongTy 
-            || FT->getParamType(0) == Type::LongTy,
-            "Argument must be a long type!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::sqrt_f32:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getParamType(0) == Type::FloatTy,
-            "Argument is not a 32-bit floating point type!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type is not the same as argument type!", IF);
-    NumArgs = 1;
-    break;
-
-  case Intrinsic::sqrt_f64:
-    Assert1(FT->getNumParams() == 1,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(FT->getParamType(0) == Type::DoubleTy,
-            "Argument is not a 64-bit floating point type!", IF);
-    Assert1(FT->getReturnType() == FT->getParamType(0),
-            "Return type is not the same as argument type!", IF);
-    NumArgs = 1;
-    break;
+    const Type *Ty;
+    if (ArgNo == 0) 
+      Ty = FTy->getReturnType();
+    else
+      Ty = FTy->getParamType(ArgNo-1);
+    
+    if (Ty->getTypeID() != TypeID) {
+      if (ArgNo == 0)
+        CheckFailed("Intrinsic prototype has incorrect result type!", F);
+      else
+        CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is wrong!",F);
+      break;
+    }
 
-  case Intrinsic::setjmp:          NumArgs = 1; break;
-  case Intrinsic::longjmp:         NumArgs = 2; break;
-  case Intrinsic::sigsetjmp:       NumArgs = 2; break;
-  case Intrinsic::siglongjmp:      NumArgs = 2; break;
-
-  case Intrinsic::gcroot:
-    Assert1(FT->getNumParams() == 2,
-            "Illegal # arguments for intrinsic function!", IF);
-    Assert1(isa<Constant>(CI.getOperand(2)),
-            "Second argument to llvm.gcroot must be a constant!", &CI);
-    NumArgs = 2;
-    break;
-  case Intrinsic::gcread:          NumArgs = 2; break;
-  case Intrinsic::gcwrite:         NumArgs = 3; break;
-
-  case Intrinsic::dbg_stoppoint:   NumArgs = 4; break;
-  case Intrinsic::dbg_region_start:NumArgs = 1; break;
-  case Intrinsic::dbg_region_end:  NumArgs = 1; break;
-  case Intrinsic::dbg_func_start:  NumArgs = 1; break;
-  case Intrinsic::dbg_declare:     NumArgs = 1; break;
-
-  case Intrinsic::memcpy:          NumArgs = 4; break;
-  case Intrinsic::memmove:         NumArgs = 4; break;
-  case Intrinsic::memset:          NumArgs = 4; break;
-
-  case Intrinsic::stacksave:
-    NumArgs = 0;
-    Assert1(CI.getType() == PointerType::get(Type::SByteTy),
-            "llvm.stacksave must return an sbyte*", &CI);
-    break;
-  case Intrinsic::stackrestore:
-    NumArgs = 1;
-    Assert1(CI.getOperand(1)->getType() == PointerType::get(Type::SByteTy),
-            "llvm.stackrestore must take an sbyte*", &CI);
-    Assert1(CI.getType() == Type::VoidTy,
-            "llvm.stackrestore return void", &CI);
-    break;
-  case Intrinsic::prefetch:        NumArgs = 3; break;
-  case Intrinsic::pcmarker:
-    NumArgs = 1;
-    Assert1(isa<Constant>(CI.getOperand(1)),
-            "First argument to llvm.pcmarker must be a constant!", &CI);
-    break;
+    // If this is a packed argument, verify the number and type of elements.
+    if (TypeID == Type::PackedTyID) {
+      const PackedType *PTy = cast<PackedType>(Ty);
+      if (va_arg(VA, int) != PTy->getElementType()->getTypeID()) {
+        CheckFailed("Intrinsic prototype has incorrect vector element type!",F);
+        break;
+      }
 
-  case Intrinsic::not_intrinsic:
-    assert(0 && "Invalid intrinsic!"); NumArgs = 0; break;
+      if ((unsigned)va_arg(VA, int) != PTy->getNumElements()) {
+        CheckFailed("Intrinsic prototype has incorrect number of "
+                    "vector elements!",F);
+        break;
+      }
+    }
   }
 
-  Assert1(FT->getNumParams() == NumArgs || (FT->getNumParams() < NumArgs &&
-                                             FT->isVarArg()),
-          "Illegal # arguments for intrinsic function!", IF);
+  va_end(VA);
 }
 
 
@@ -1029,11 +1054,15 @@ bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
 /// verifyModule - Check a module for errors, printing messages on stderr.
 /// Return true if the module is corrupt.
 ///
-bool llvm::verifyModule(const Module &M, VerifierFailureAction action) {
+bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
+                        std::string *ErrorInfo) {
   PassManager PM;
   Verifier *V = new Verifier(action);
   PM.add(V);
   PM.run((Module&)M);
+  
+  if (ErrorInfo && V->Broken)
+    *ErrorInfo = V->msgs.str();
   return V->Broken;
 }