- Add a "getOrInsertGlobal" method to the Module class. This acts similarly to
[oota-llvm.git] / lib / VMCore / Verifier.cpp
index fc458c8f2f9a238b4cf62734d9a448ede7cc7b83..f8dd24c3af62f0f7eea74b92fc96742eff954ed5 100644 (file)
@@ -70,7 +70,7 @@ namespace {  // Anonymous namespace for class
   struct VISIBILITY_HIDDEN PreVerifier : public FunctionPass {
     static char ID; // Pass ID, replacement for typeid
 
-    PreVerifier() : FunctionPass((intptr_t)&ID) { }
+    PreVerifier() : FunctionPass(&ID) { }
 
     // Check that the prerequisites for successful DominatorTree construction
     // are satisfied.
@@ -118,20 +118,20 @@ namespace {
     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
 
     Verifier()
-      : FunctionPass((intptr_t)&ID), 
+      : FunctionPass(&ID), 
       Broken(false), RealPass(true), action(AbortProcessAction),
       DT(0), msgs( std::ios::app | std::ios::out ) {}
     explicit Verifier(VerifierFailureAction ctn)
-      : FunctionPass((intptr_t)&ID), 
+      : FunctionPass(&ID), 
       Broken(false), RealPass(true), action(ctn), DT(0),
       msgs( std::ios::app | std::ios::out ) {}
     explicit Verifier(bool AB)
-      : FunctionPass((intptr_t)&ID), 
+      : FunctionPass(&ID), 
       Broken(false), RealPass(true),
       action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
       msgs( std::ios::app | std::ios::out ) {}
     explicit Verifier(DominatorTree &dt)
-      : FunctionPass((intptr_t)&ID), 
+      : FunctionPass(&ID), 
       Broken(false), RealPass(false), action(PrintMessageAction),
       DT(&dt), msgs( std::ios::app | std::ios::out ) {}
 
@@ -198,23 +198,22 @@ namespace {
     /// this condition, do so.
     ///
     bool abortIfBroken() {
-      if (Broken) {
-        msgs << "Broken module found, ";
-        switch (action) {
-          case AbortProcessAction:
-            msgs << "compilation aborted!\n";
-            cerr << msgs.str();
-            abort();
-          case PrintMessageAction:
-            msgs << "verification continues.\n";
-            cerr << msgs.str();
-            return false;
-          case ReturnStatusAction:
-            msgs << "compilation terminated.\n";
-            return Broken;
-        }
+      if (!Broken) return false;
+      msgs << "Broken module found, ";
+      switch (action) {
+      default: assert(0 && "Unknown action");
+      case AbortProcessAction:
+        msgs << "compilation aborted!\n";
+        cerr << msgs.str();
+        abort();
+      case PrintMessageAction:
+        msgs << "verification continues.\n";
+        cerr << msgs.str();
+        return false;
+      case ReturnStatusAction:
+        msgs << "compilation terminated.\n";
+        return Broken;
       }
-      return false;
     }
 
 
@@ -225,6 +224,10 @@ namespace {
     void visitGlobalAlias(GlobalAlias &GA);
     void visitFunction(Function &F);
     void visitBasicBlock(BasicBlock &BB);
+    using InstVisitor<Verifier>::visit;
+       
+    void visit(Instruction &I);
+       
     void visitTruncInst(TruncInst &I);
     void visitZExtInst(ZExtInst &I);
     void visitSExtInst(SExtInst &I);
@@ -265,9 +268,9 @@ namespace {
     void VerifyCallSite(CallSite CS);
     void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
                                   unsigned Count, ...);
-    void VerifyAttrs(ParameterAttributes Attrs, const Type *Ty,
+    void VerifyAttrs(Attributes Attrs, const Type *Ty,
                      bool isReturnValue, const Value *V);
-    void VerifyFunctionAttrs(const FunctionType *FT, const PAListPtr &Attrs,
+    void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
                              const Value *V);
 
     void WriteValue(const Value *V) {
@@ -327,6 +330,13 @@ static RegisterPass<Verifier> X("verify", "Module Verifier");
   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
 
 
+void Verifier::visit(Instruction &I) {
+  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
+    Assert1(I.getOperand(i) != 0, "Operand is null", &I);
+  InstVisitor<Verifier>::visit(I);
+}
+
+
 void Verifier::visitGlobalValue(GlobalValue &GV) {
   Assert1(!GV.isDeclaration() ||
           GV.hasExternalLinkage() ||
@@ -384,7 +394,7 @@ void Verifier::visitGlobalAlias(GlobalAlias &GA) {
             &GA);
   }
 
-  const GlobalValue* Aliasee = GA.resolveAliasedGlobal();
+  const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
   Assert1(Aliasee,
           "Aliasing chain should end with function or global variable", &GA);
 
@@ -396,37 +406,47 @@ void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
 
 // VerifyAttrs - Check the given parameter attributes for an argument or return
 // value of the specified type.  The value V is printed in error messages.
-void Verifier::VerifyAttrs(ParameterAttributes Attrs, const Type *Ty, 
+void Verifier::VerifyAttrs(Attributes Attrs, const Type *Ty, 
                            bool isReturnValue, const Value *V) {
-  if (Attrs == ParamAttr::None)
+  if (Attrs == Attribute::None)
     return;
 
   if (isReturnValue) {
-    ParameterAttributes RetI = Attrs & ParamAttr::ParameterOnly;
-    Assert1(!RetI, "Attribute " + ParamAttr::getAsString(RetI) +
+    Attributes RetI = Attrs & Attribute::ParameterOnly;
+    Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
             " does not apply to return values!", V);
-  } else {
-    ParameterAttributes ParmI = Attrs & ParamAttr::ReturnOnly;
-    Assert1(!ParmI, "Attribute " + ParamAttr::getAsString(ParmI) +
-            " only applies to return values!", V);
   }
-
+  Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
+  Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
+          " only applies to functions!", V);
+  
   for (unsigned i = 0;
-       i < array_lengthof(ParamAttr::MutuallyIncompatible); ++i) {
-    ParameterAttributes MutI = Attrs & ParamAttr::MutuallyIncompatible[i];
+       i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
+    Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
     Assert1(!(MutI & (MutI - 1)), "Attributes " +
-            ParamAttr::getAsString(MutI) + " are incompatible!", V);
+            Attribute::getAsString(MutI) + " are incompatible!", V);
   }
 
-  ParameterAttributes TypeI = Attrs & ParamAttr::typeIncompatible(Ty);
+  Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
   Assert1(!TypeI, "Wrong type for attribute " +
-          ParamAttr::getAsString(TypeI), V);
+          Attribute::getAsString(TypeI), V);
+
+  Attributes ByValI = Attrs & Attribute::ByVal;
+  if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
+    Assert1(!ByValI || PTy->getElementType()->isSized(),
+            "Attribute " + Attribute::getAsString(ByValI) +
+            " does not support unsized types!", V);
+  } else {
+    Assert1(!ByValI,
+            "Attribute " + Attribute::getAsString(ByValI) +
+            " only applies to parameters with pointer type!", V);
+  }
 }
 
 // VerifyFunctionAttrs - Check parameter attributes against a function type.
 // The value V is printed in error messages.
 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
-                                   const PAListPtr &Attrs,
+                                   const AttrListPtr &Attrs,
                                    const Value *V) {
   if (Attrs.isEmpty())
     return;
@@ -434,7 +454,7 @@ void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
   bool SawNest = false;
 
   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
-    const ParamAttrsWithIndex &Attr = Attrs.getSlot(i);
+    const AttributeWithIndex &Attr = Attrs.getSlot(i);
 
     const Type *Ty;
     if (Attr.Index == 0)
@@ -446,16 +466,41 @@ void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
     
     VerifyAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
 
-    if (Attr.Attrs & ParamAttr::Nest) {
+    if (Attr.Attrs & Attribute::Nest) {
       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
       SawNest = true;
     }
 
-    if (Attr.Attrs & ParamAttr::StructRet)
+    if (Attr.Attrs & Attribute::StructRet)
       Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
   }
+
+  Attributes FAttrs = Attrs.getFnAttributes();
+  Assert1(!(FAttrs & (~Attribute::FunctionOnly)),
+          "Attribute " + Attribute::getAsString(FAttrs) +
+          " does not apply to function!", V);
+      
+  for (unsigned i = 0;
+       i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
+    Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
+    Assert1(!(MutI & (MutI - 1)), "Attributes " +
+            Attribute::getAsString(MutI) + " are incompatible!", V);
+  }
 }
 
+static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
+  if (Attrs.isEmpty())
+    return true;
+    
+  unsigned LastSlot = Attrs.getNumSlots() - 1;
+  unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
+  if (LastIndex <= Params
+      || (LastIndex == (unsigned)~0
+          && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))  
+    return true;
+    
+  return false;
+}
 // visitFunction - Verify that a function is ok.
 //
 void Verifier::visitFunction(Function &F) {
@@ -474,10 +519,9 @@ void Verifier::visitFunction(Function &F) {
   Assert1(!F.hasStructRetAttr() || F.getReturnType() == Type::VoidTy,
           "Invalid struct return type!", &F);
 
-  const PAListPtr &Attrs = F.getParamAttrs();
+  const AttrListPtr &Attrs = F.getAttributes();
 
-  Assert1(Attrs.isEmpty() ||
-          Attrs.getSlot(Attrs.getNumSlots()-1).Index <= FT->getNumParams(),
+  Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
           "Attributes after last parameter!", &F);
 
   // Check function attributes.
@@ -488,7 +532,6 @@ void Verifier::visitFunction(Function &F) {
   default:
     break;
   case CallingConv::C:
-  case CallingConv::X86_SSECall:
     break;
   case CallingConv::Fast:
   case CallingConv::Cold:
@@ -505,10 +548,9 @@ void Verifier::visitFunction(Function &F) {
     Assert2(I->getType() == FT->getParamType(i),
             "Argument value does not match function argument type!",
             I, FT->getParamType(i));
-    // Make sure no aggregates are passed by value.
     Assert1(I->getType()->isFirstClassType(),
-            "Functions cannot take aggregates as arguments by value!", I);
-   }
+            "Function arguments must have first-class types!", I);
+  }
 
   if (F.isDeclaration()) {
     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
@@ -639,8 +681,21 @@ void Verifier::visitSwitchInst(SwitchInst &SI) {
 }
 
 void Verifier::visitSelectInst(SelectInst &SI) {
-  Assert1(SI.getCondition()->getType() == Type::Int1Ty,
-          "Select condition type must be bool!", &SI);
+  if (const VectorType* vt
+             = dyn_cast<VectorType>(SI.getCondition()->getType())) {
+    Assert1( vt->getElementType() == Type::Int1Ty,
+            "Select condition type must be vector of bool!", &SI);
+    if (const VectorType* val_vt
+             = dyn_cast<VectorType>(SI.getTrueValue()->getType())) {
+      Assert1( vt->getNumElements() == val_vt->getNumElements(),
+               "Select vector size != value vector size", &SI);
+    } else {
+      Assert1(0, "Vector select values must have vector types", &SI);
+    }
+  } else {
+    Assert1(SI.getCondition()->getType() == Type::Int1Ty,
+            "Select condition type must be bool!", &SI);
+  }
   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
           "Select values must have identical types!", &SI);
   Assert1(SI.getTrueValue()->getType() == SI.getType(),
@@ -863,6 +918,12 @@ void Verifier::visitBitCastInst(BitCastInst &I) {
           "Bitcast requires both operands to be pointer or neither", &I);
   Assert1(SrcBitSize == DestBitSize, "Bitcast requies types of same width", &I);
 
+  // Disallow aggregates.
+  Assert1(!SrcTy->isAggregateType(),
+          "Bitcast operand must not be aggregate", &I);
+  Assert1(!DestTy->isAggregateType(),
+          "Bitcast type must not be aggregate", &I);
+
   visitInstruction(I);
 }
 
@@ -914,10 +975,9 @@ void Verifier::VerifyCallSite(CallSite CS) {
             "Call parameter type does not match function signature!",
             CS.getArgument(i), FTy->getParamType(i), I);
 
-  const PAListPtr &Attrs = CS.getParamAttrs();
+  const AttrListPtr &Attrs = CS.getAttributes();
 
-  Assert1(Attrs.isEmpty() ||
-          Attrs.getSlot(Attrs.getNumSlots()-1).Index <= CS.arg_size(),
+  Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
           "Attributes after last parameter!", I);
 
   // Verify call attributes.
@@ -926,12 +986,12 @@ void Verifier::VerifyCallSite(CallSite CS) {
   if (FTy->isVarArg())
     // Check attributes on the varargs part.
     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
-      ParameterAttributes Attr = Attrs.getParamAttrs(Idx);
+      Attributes Attr = Attrs.getParamAttributes(Idx);
 
       VerifyAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
 
-      ParameterAttributes VArgI = Attr & ParamAttr::VarArgsIncompatible;
-      Assert1(!VArgI, "Attribute " + ParamAttr::getAsString(VArgI) +
+      Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
+      Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
               " cannot be used for vararg call arguments!", I);
     }
 
@@ -1002,7 +1062,7 @@ void Verifier::visitICmpInst(ICmpInst& IC) {
   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->isInteger() || isa<PointerType>(Op0Ty),
+  Assert1(Op0Ty->isIntOrIntVector() || isa<PointerType>(Op0Ty),
           "Invalid operand types for ICmp instruction", &IC);
   visitInstruction(IC);
 }
@@ -1014,7 +1074,7 @@ void Verifier::visitFCmpInst(FCmpInst& FC) {
   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(),
+  Assert1(Op0Ty->isFPOrFPVector(),
           "Invalid operand types for FCmp instruction", &FC);
   visitInstruction(FC);
 }
@@ -1285,48 +1345,32 @@ void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
     break;
   case Intrinsic::gcroot:
   case Intrinsic::gcwrite:
-  case Intrinsic::gcread: {
-      Type *PtrTy    = PointerType::getUnqual(Type::Int8Ty),
-           *PtrPtrTy = PointerType::getUnqual(PtrTy);
-      
-      switch (ID) {
-      default:
-        break;
-      case Intrinsic::gcroot:
-        Assert1(CI.getOperand(1)->getType() == PtrPtrTy,
-                "Intrinsic parameter #1 is not i8**.", &CI);
-        Assert1(CI.getOperand(2)->getType() == PtrTy,
-                "Intrinsic parameter #2 is not i8*.", &CI);
-        Assert1(isa<AllocaInst>(CI.getOperand(1)->stripPointerCasts()),
-                "llvm.gcroot parameter #1 must be an alloca.", &CI);
-        Assert1(isa<Constant>(CI.getOperand(2)),
-                "llvm.gcroot parameter #2 must be a constant.", &CI);
-        break;
-      case Intrinsic::gcwrite:
-        Assert1(CI.getOperand(1)->getType() == PtrTy,
-                "Intrinsic parameter #1 is not a i8*.", &CI);
-        Assert1(CI.getOperand(2)->getType() == PtrTy,
-                "Intrinsic parameter #2 is not a i8*.", &CI);
-        Assert1(CI.getOperand(3)->getType() == PtrPtrTy,
-                "Intrinsic parameter #3 is not a i8**.", &CI);
-        break;
-      case Intrinsic::gcread:
-        Assert1(CI.getOperand(1)->getType() == PtrTy,
-                "Intrinsic parameter #1 is not a i8*.", &CI);
-        Assert1(CI.getOperand(2)->getType() == PtrPtrTy,
-                "Intrinsic parameter #2 is not a i8**.", &CI);
-        break;
-      }
+  case Intrinsic::gcread:
+    if (ID == Intrinsic::gcroot) {
+      AllocaInst *AI =
+        dyn_cast<AllocaInst>(CI.getOperand(1)->stripPointerCasts());
+      Assert1(AI && isa<PointerType>(AI->getType()->getElementType()),
+              "llvm.gcroot parameter #1 must be a pointer alloca.", &CI);
+      Assert1(isa<Constant>(CI.getOperand(2)),
+              "llvm.gcroot parameter #2 must be a constant.", &CI);
+    }
       
-      Assert1(CI.getParent()->getParent()->hasGC(),
-              "Enclosing function does not use GC.",
-              &CI);
-    } break;
+    Assert1(CI.getParent()->getParent()->hasGC(),
+            "Enclosing function does not use GC.", &CI);
+    break;
   case Intrinsic::init_trampoline:
     Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
             "llvm.init_trampoline parameter #2 must resolve to a function.",
             &CI);
     break;
+  case Intrinsic::prefetch:
+    Assert1(isa<ConstantInt>(CI.getOperand(2)) &&
+            isa<ConstantInt>(CI.getOperand(3)) &&
+            cast<ConstantInt>(CI.getOperand(2))->getZExtValue() < 2 &&
+            cast<ConstantInt>(CI.getOperand(3))->getZExtValue() < 4,
+            "invalid arguments to llvm.prefetch",
+            &CI);
+    break;
   }
 }
 
@@ -1499,7 +1543,7 @@ void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID,
   }
 
   // Check parameter attributes.
-  Assert1(F->getParamAttrs() == Intrinsic::getParamAttrs(ID),
+  Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
           "Intrinsic has wrong parameter attributes!", F);
 }
 
@@ -1518,10 +1562,12 @@ bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
   Function &F = const_cast<Function&>(f);
   assert(!F.isDeclaration() && "Cannot verify external functions");
 
-  FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
+  ExistingModuleProvider MP(F.getParent());
+  FunctionPassManager FPM(&MP);
   Verifier *V = new Verifier(action);
   FPM.add(V);
   FPM.run(F);
+  MP.releaseModule();
   return V->Broken;
 }