Temporarily revert r244012 while we see if it's really necessary.
[oota-llvm.git] / tools / llvm-stress / llvm-stress.cpp
index e24e76679acbc420694a04b97c193ccda97af9c3..6a1a248a05725f59bc0cc94393da9d50c986412d 100644 (file)
@@ -1,4 +1,4 @@
-//===-- llvm-stress.cpp - Print the size of each object section ------------===//
+//===-- llvm-stress.cpp - Generate random LL files to stress-test LLVM ----===//
 //
 //                     The LLVM Compiler Infrastructure
 //
 // different components in LLVM.
 //
 //===----------------------------------------------------------------------===//
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-#include "llvm/PassManager.h"
-#include "llvm/Constants.h"
-#include "llvm/Instruction.h"
-#include "llvm/CallGraphSCCPass.h"
-#include "llvm/Assembly/PrintModulePass.h"
-#include "llvm/Analysis/Verifier.h"
-#include "llvm/Support/PassNameParser.h"
+
+#include "llvm/Analysis/CallGraphSCCPass.h"
+#include "llvm/IR/Constants.h"
+#include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IR/Instruction.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/LegacyPassNameParser.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Verifier.h"
+#include "llvm/IR/LegacyPassManager.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/PluginLoader.h"
 #include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/ToolOutputFile.h"
-#include <memory>
-#include <sstream>
+#include <algorithm>
 #include <set>
+#include <sstream>
 #include <vector>
-#include <algorithm>
-using namespace llvm;
+
+namespace llvm {
 
 static cl::opt<unsigned> SeedCL("seed",
   cl::desc("Seed used for randomness"), cl::init(0));
@@ -41,6 +43,41 @@ static cl::opt<std::string>
 OutputFilename("o", cl::desc("Override output filename"),
                cl::value_desc("filename"));
 
+namespace cl {
+template <> class parser<Type*> final : public basic_parser<Type*> {
+public:
+  parser(Option &O) : basic_parser(O) {}
+
+  // Parse options as IR types. Return true on error.
+  bool parse(Option &O, StringRef, StringRef Arg, Type *&Value) {
+    auto &Context = getGlobalContext();
+    if      (Arg == "half")      Value = Type::getHalfTy(Context);
+    else if (Arg == "fp128")     Value = Type::getFP128Ty(Context);
+    else if (Arg == "x86_fp80")  Value = Type::getX86_FP80Ty(Context);
+    else if (Arg == "ppc_fp128") Value = Type::getPPC_FP128Ty(Context);
+    else if (Arg == "x86_mmx")   Value = Type::getX86_MMXTy(Context);
+    else if (Arg.startswith("i")) {
+      unsigned N = 0;
+      Arg.drop_front().getAsInteger(10, N);
+      if (N > 0)
+        Value = Type::getIntNTy(Context, N);
+    }
+
+    if (!Value)
+      return O.error("Invalid IR scalar type: '" + Arg + "'!");
+    return false;
+  }
+
+  const char *getValueName() const override { return "IR scalar type"; }
+};
+}
+
+
+static cl::list<Type*> AdditionalScalarTypes("types", cl::CommaSeparated,
+  cl::desc("Additional IR scalar types "
+           "(always includes i1, i8, i16, i32, i64, float and double)"));
+
+namespace {
 /// A utility class to provide a pseudo-random number generator which is
 /// the same across all platforms. This is somewhat close to the libc
 /// implementation. Note: This is not a cryptographically secure pseudorandom
@@ -49,38 +86,55 @@ class Random {
 public:
   /// C'tor
   Random(unsigned _seed):Seed(_seed) {}
-  /// Return the next random value.
-  unsigned Rand() {
-    unsigned Val = Seed + 0x000b07a1;
+
+  /// Return a random integer, up to a
+  /// maximum of 2**19 - 1.
+  uint32_t Rand() {
+    uint32_t Val = Seed + 0x000b07a1;
     Seed = (Val * 0x3c7c0ac1);
     // Only lowest 19 bits are random-ish.
     return Seed & 0x7ffff;
   }
 
+  /// Return a random 32 bit integer.
+  uint32_t Rand32() {
+    uint32_t Val = Rand();
+    Val &= 0xffff;
+    return Val | (Rand() << 16);
+  }
+
+  /// Return a random 64 bit integer.
+  uint64_t Rand64() {
+    uint64_t Val = Rand32();
+    return Val | (uint64_t(Rand32()) << 32);
+  }
+
+  /// Rand operator for STL algorithms.
+  ptrdiff_t operator()(ptrdiff_t y) {
+    return  Rand64() % y;
+  }
+
 private:
   unsigned Seed;
 };
 
 /// Generate an empty function with a default argument list.
 Function *GenEmptyFunction(Module *M) {
-  // Type Definitions
-  std::vector<Type*> ArgsTy;
   // Define a few arguments
   LLVMContext &Context = M->getContext();
-  ArgsTy.push_back(PointerType::get(IntegerType::getInt8Ty(Context), 0));
-  ArgsTy.push_back(PointerType::get(IntegerType::getInt32Ty(Context), 0));
-  ArgsTy.push_back(PointerType::get(IntegerType::getInt64Ty(Context), 0));
-  ArgsTy.push_back(IntegerType::getInt32Ty(Context));
-  ArgsTy.push_back(IntegerType::getInt64Ty(Context));
-  ArgsTy.push_back(IntegerType::getInt8Ty(Context));
-
-  FunctionType *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, 0);
+  Type* ArgsTy[] = {
+    Type::getInt8PtrTy(Context),
+    Type::getInt32PtrTy(Context),
+    Type::getInt64PtrTy(Context),
+    Type::getInt32Ty(Context),
+    Type::getInt64Ty(Context),
+    Type::getInt8Ty(Context)
+  };
+
+  auto *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, false);
   // Pick a unique name to describe the input parameters
-  std::stringstream ss;
-  ss<<"autogen_SD"<<SeedCL;
-  Function *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
-                                    ss.str(), M);
-
+  Twine Name = "autogen_SD" + Twine{SeedCL};
+  auto *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage, Name, M);
   Func->setCallingConv(CallingConv::C);
   return Func;
 }
@@ -93,8 +147,12 @@ struct Modifier {
 
 public:
   /// C'tor
-  Modifier(BasicBlock *_BB, PieceTable *PT, Random *R):
-    BB(_BB),PT(PT),Ran(R),Context(BB->getContext()) {};
+  Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
+    BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {}
+
+  /// virtual D'tor to silence warnings.
+  virtual ~Modifier() {}
+
   /// Add a new instruction.
   virtual void Act() = 0;
   /// Add N new instructions,
@@ -110,6 +168,19 @@ protected:
     return PT->at(Ran->Rand() % PT->size());
   }
 
+  Constant *getRandomConstant(Type *Tp) {
+    if (Tp->isIntegerTy()) {
+      if (Ran->Rand() & 1)
+        return ConstantInt::getAllOnesValue(Tp);
+      return ConstantInt::getNullValue(Tp);
+    } else if (Tp->isFloatingPointTy()) {
+      if (Ran->Rand() & 1)
+        return ConstantFP::getAllOnesValue(Tp);
+      return ConstantFP::getNullValue(Tp);
+    }
+    return UndefValue::get(Tp);
+  }
+
   /// Return a random value with a known type.
   Value *getRandomValue(Type *Tp) {
     unsigned index = Ran->Rand();
@@ -128,9 +199,18 @@ protected:
       if (Ran->Rand() & 1)
         return ConstantFP::getAllOnesValue(Tp);
       return ConstantFP::getNullValue(Tp);
+    } else if (Tp->isVectorTy()) {
+      VectorType *VTp = cast<VectorType>(Tp);
+
+      std::vector<Constant*> TempValues;
+      TempValues.reserve(VTp->getNumElements());
+      for (unsigned i = 0; i < VTp->getNumElements(); ++i)
+        TempValues.push_back(getRandomConstant(VTp->getScalarType()));
+
+      ArrayRef<Constant*> VectorValue(TempValues);
+      return ConstantVector::get(VectorValue);
     }
 
-    // TODO: return values for vector types.
     return UndefValue::get(Tp);
   }
 
@@ -169,11 +249,17 @@ protected:
 
   /// Pick a random vector type.
   Type *pickVectorType(unsigned len = (unsigned)-1) {
-    Type *Ty = pickScalarType();
     // Pick a random vector width in the range 2**0 to 2**4.
     // by adding two randoms we are generating a normal-like distribution
     // around 2**3.
     unsigned width = 1<<((Ran->Rand() % 3) + (Ran->Rand() % 3));
+    Type *Ty;
+
+    // Vectors of x86mmx are illegal; keep trying till we get something else.
+    do {
+      Ty = pickScalarType();
+    } while (Ty->isX86_MMXTy());
+
     if (len != (unsigned)-1)
       width = len;
     return VectorType::get(Ty, width);
@@ -181,20 +267,22 @@ protected:
 
   /// Pick a random scalar type.
   Type *pickScalarType() {
-    switch (Ran->Rand() % 15) {
-    case 0: return Type::getInt1Ty(Context);
-    case 1: return Type::getInt8Ty(Context);
-    case 2: return Type::getInt16Ty(Context);
-    case 3: case 4:
-    case 5: return Type::getFloatTy(Context);
-    case 6: case 7:
-    case 8: return Type::getDoubleTy(Context);
-    case 9: case 10:
-    case 11: return Type::getInt32Ty(Context);
-    case 12: case 13:
-    case 14: return Type::getInt64Ty(Context);
+    static std::vector<Type*> ScalarTypes;
+    if (ScalarTypes.empty()) {
+      ScalarTypes.assign({
+        Type::getInt1Ty(Context),
+        Type::getInt8Ty(Context),
+        Type::getInt16Ty(Context),
+        Type::getInt32Ty(Context),
+        Type::getInt64Ty(Context),
+        Type::getFloatTy(Context),
+        Type::getDoubleTy(Context)
+      });
+      ScalarTypes.insert(ScalarTypes.end(),
+        AdditionalScalarTypes.begin(), AdditionalScalarTypes.end());
     }
-    llvm_unreachable("Invalid scalar value");
+
+    return ScalarTypes[Ran->Rand() % ScalarTypes.size()];
   }
 
   /// Basic block to populate
@@ -208,9 +296,9 @@ protected:
 };
 
 struct LoadModifier: public Modifier {
-  LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {};
-  virtual void Act() {
-    // Try to use predefined pointers. If non exist, use undef pointer value;
+  LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
+  void Act() override {
+    // Try to use predefined pointers. If non-exist, use undef pointer value;
     Value *Ptr = getRandomPointerValue();
     Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
     PT->push_back(V);
@@ -219,15 +307,16 @@ struct LoadModifier: public Modifier {
 
 struct StoreModifier: public Modifier {
   StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
-  virtual void Act() {
-    // Try to use predefined pointers. If non exist, use undef pointer value;
+  void Act() override {
+    // Try to use predefined pointers. If non-exist, use undef pointer value;
     Value *Ptr = getRandomPointerValue();
     Type  *Tp = Ptr->getType();
     Value *Val = getRandomValue(Tp->getContainedType(0));
+    Type  *ValTy = Val->getType();
 
     // Do not store vectors of i1s because they are unsupported
-    //by the codegen.
-    if (Tp->isVectorTy() && Tp->getScalarSizeInBits() == 1)
+    // by the codegen.
+    if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
       return;
 
     new StoreInst(Val, Ptr, BB->getTerminator());
@@ -237,7 +326,7 @@ struct StoreModifier: public Modifier {
 struct BinModifier: public Modifier {
   BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
 
-  virtual void Act() {
+  void Act() override {
     Value *Val0 = getRandomVal();
     Value *Val1 = getRandomValue(Val0->getType());
 
@@ -280,7 +369,7 @@ struct BinModifier: public Modifier {
 /// Generate constant values.
 struct ConstModifier: public Modifier {
   ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
-  virtual void Act() {
+  void Act() override {
     Type *Ty = pickType();
 
     if (Ty->isVectorTy()) {
@@ -293,10 +382,18 @@ struct ConstModifier: public Modifier {
     }
 
     if (Ty->isFloatingPointTy()) {
+      // Generate 128 random bits, the size of the (currently)
+      // largest floating-point types.
+      uint64_t RandomBits[2];
+      for (unsigned i = 0; i < 2; ++i)
+        RandomBits[i] = Ran->Rand64();
+
+      APInt RandomInt(Ty->getPrimitiveSizeInBits(), makeArrayRef(RandomBits));
+      APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
+
       if (Ran->Rand() & 1)
         return PT->push_back(ConstantFP::getNullValue(Ty));
-      return PT->push_back(ConstantFP::get(Ty,
-                                           static_cast<double>(1)/Ran->Rand()));
+      return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
     }
 
     if (Ty->isIntegerTy()) {
@@ -319,7 +416,7 @@ struct ConstModifier: public Modifier {
 struct AllocaModifier: public Modifier {
   AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
 
-  virtual void Act() {
+  void Act() override {
     Type *Tp = pickType();
     PT->push_back(new AllocaInst(Tp, "A", BB->getFirstNonPHI()));
   }
@@ -329,11 +426,11 @@ struct ExtractElementModifier: public Modifier {
   ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
     Modifier(BB, PT, R) {}
 
-  virtual void Act() {
+  void Act() override {
     Value *Val0 = getRandomVectorValue();
     Value *V = ExtractElementInst::Create(Val0,
              ConstantInt::get(Type::getInt32Ty(BB->getContext()),
-             Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()), 
+             Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
              "E", BB->getTerminator());
     return PT->push_back(V);
   }
@@ -341,7 +438,7 @@ struct ExtractElementModifier: public Modifier {
 
 struct ShuffModifier: public Modifier {
   ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
-  virtual void Act() {
+  void Act() override {
 
     Value *Val0 = getRandomVectorValue();
     Value *Val1 = getRandomValue(Val0->getType());
@@ -370,7 +467,7 @@ struct InsertElementModifier: public Modifier {
   InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
     Modifier(BB, PT, R) {}
 
-  virtual void Act() {
+  void Act() override {
     Value *Val0 = getRandomVectorValue();
     Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
 
@@ -385,7 +482,7 @@ struct InsertElementModifier: public Modifier {
 
 struct CastModifier: public Modifier {
   CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
-  virtual void Act() {
+  void Act() override {
 
     Value *V = getRandomVal();
     Type *VTy = V->getType();
@@ -397,7 +494,7 @@ struct CastModifier: public Modifier {
       DestTy = pickVectorType(VecTy->getNumElements());
     }
 
-    // no need to casr.
+    // no need to cast.
     if (VTy == DestTy) return;
 
     // Pointers:
@@ -408,9 +505,11 @@ struct CastModifier: public Modifier {
         new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
     }
 
+    unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
+    unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
+
     // Generate lots of bitcasts.
-    if ((Ran->Rand() & 1) &&
-        VTy->getPrimitiveSizeInBits() == DestTy->getPrimitiveSizeInBits()) {
+    if ((Ran->Rand() & 1) && VSize == DestSize) {
       return PT->push_back(
         new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
     }
@@ -418,11 +517,11 @@ struct CastModifier: public Modifier {
     // Both types are integers:
     if (VTy->getScalarType()->isIntegerTy() &&
         DestTy->getScalarType()->isIntegerTy()) {
-      if (VTy->getScalarType()->getPrimitiveSizeInBits() >
-          DestTy->getScalarType()->getPrimitiveSizeInBits()) {
+      if (VSize > DestSize) {
         return PT->push_back(
           new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
       } else {
+        assert(VSize < DestSize && "Different int types with the same size?");
         if (Ran->Rand() & 1)
           return PT->push_back(
             new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
@@ -452,14 +551,15 @@ struct CastModifier: public Modifier {
     // Both floats.
     if (VTy->getScalarType()->isFloatingPointTy() &&
         DestTy->getScalarType()->isFloatingPointTy()) {
-      if (VTy->getScalarType()->getPrimitiveSizeInBits() >
-          DestTy->getScalarType()->getPrimitiveSizeInBits()) {
+      if (VSize > DestSize) {
         return PT->push_back(
           new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
-      } else {
+      } else if (VSize < DestSize) {
         return PT->push_back(
           new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
       }
+      // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
+      // for which there is no defined conversion. So do nothing.
     }
   }
 
@@ -469,7 +569,7 @@ struct SelectModifier: public Modifier {
   SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
     Modifier(BB, PT, R) {}
 
-  virtual void Act() {
+  void Act() override {
     // Try a bunch of different select configuration until a valid one is found.
       Value *Val0 = getRandomVal();
       Value *Val1 = getRandomValue(Val0->getType());
@@ -492,7 +592,7 @@ struct SelectModifier: public Modifier {
 
 struct CmpModifier: public Modifier {
   CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
-  virtual void Act() {
+  void Act() override {
 
     Value *Val0 = getRandomVal();
     Value *Val1 = getRandomValue(Val0->getType());
@@ -517,68 +617,56 @@ struct CmpModifier: public Modifier {
   }
 };
 
-void FillFunction(Function *F) {
+} // end anonymous namespace
+
+static void FillFunction(Function *F, Random &R) {
   // Create a legal entry block.
   BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
   ReturnInst::Create(F->getContext(), BB);
 
   // Create the value table.
   Modifier::PieceTable PT;
-  // Pick an initial seed value
-  Random R(SeedCL);
 
   // Consider arguments as legal values.
-  for (Function::arg_iterator it = F->arg_begin(), e = F->arg_end();
-       it != e; ++it)
-    PT.push_back(it);
+  for (auto &arg : F->args())
+    PT.push_back(&arg);
 
   // List of modifiers which add new random instructions.
-  std::vector<Modifier*> Modifiers;
-  std::auto_ptr<Modifier> LM(new LoadModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> SM(new StoreModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> EE(new ExtractElementModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> SHM(new ShuffModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> IE(new InsertElementModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> BM(new BinModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> CM(new CastModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> SLM(new SelectModifier(BB, &PT, &R));
-  std::auto_ptr<Modifier> PM(new CmpModifier(BB, &PT, &R));
-  Modifiers.push_back(LM.get());
-  Modifiers.push_back(SM.get());
-  Modifiers.push_back(EE.get());
-  Modifiers.push_back(SHM.get());
-  Modifiers.push_back(IE.get());
-  Modifiers.push_back(BM.get());
-  Modifiers.push_back(CM.get());
-  Modifiers.push_back(SLM.get());
-  Modifiers.push_back(PM.get());
+  std::vector<std::unique_ptr<Modifier>> Modifiers;
+  Modifiers.emplace_back(new LoadModifier(BB, &PT, &R));
+  Modifiers.emplace_back(new StoreModifier(BB, &PT, &R));
+  auto SM = Modifiers.back().get();
+  Modifiers.emplace_back(new ExtractElementModifier(BB, &PT, &R));
+  Modifiers.emplace_back(new ShuffModifier(BB, &PT, &R));
+  Modifiers.emplace_back(new InsertElementModifier(BB, &PT, &R));
+  Modifiers.emplace_back(new BinModifier(BB, &PT, &R));
+  Modifiers.emplace_back(new CastModifier(BB, &PT, &R));
+  Modifiers.emplace_back(new SelectModifier(BB, &PT, &R));
+  Modifiers.emplace_back(new CmpModifier(BB, &PT, &R));
 
   // Generate the random instructions
-  AllocaModifier AM(BB, &PT, &R); AM.ActN(5); // Throw in a few allocas
-  ConstModifier COM(BB, &PT, &R);  COM.ActN(40); // Throw in a few constants
+  AllocaModifier{BB, &PT, &R}.ActN(5); // Throw in a few allocas
+  ConstModifier{BB, &PT, &R}.ActN(40); // Throw in a few constants
 
-  for (unsigned i=0; i< SizeCL / Modifiers.size(); ++i)
-    for (std::vector<Modifier*>::iterator it = Modifiers.begin(),
-         e = Modifiers.end(); it != e; ++it) {
-      (*it)->Act();
-    }
+  for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
+    for (auto &Mod : Modifiers)
+      Mod->Act();
 
   SM->ActN(5); // Throw in a few stores.
 }
 
-void IntroduceControlFlow(Function *F) {
-  std::set<Instruction*> BoolInst;
-  for (BasicBlock::iterator it = F->begin()->begin(),
-       e = F->begin()->end(); it != e; ++it) {
-    if (it->getType() == IntegerType::getInt1Ty(F->getContext()))
-      BoolInst.insert(it);
+static void IntroduceControlFlow(Function *F, Random &R) {
+  std::vector<Instruction*> BoolInst;
+  for (auto &Instr : F->front()) {
+    if (Instr.getType() == IntegerType::getInt1Ty(F->getContext()))
+      BoolInst.push_back(&Instr);
   }
 
-  for (std::set<Instruction*>::iterator it = BoolInst.begin(),
-       e = BoolInst.end(); it != e; ++it) {
-    Instruction *Instr = *it;
+  std::random_shuffle(BoolInst.begin(), BoolInst.end(), R);
+
+  for (auto *Instr : BoolInst) {
     BasicBlock *Curr = Instr->getParent();
-    BasicBlock::iterator Loc= Instr;
+    BasicBlock::iterator Loc = Instr;
     BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
     Instr->moveBefore(Curr->getTerminator());
     if (Curr != &F->getEntryBlock()) {
@@ -588,34 +676,42 @@ void IntroduceControlFlow(Function *F) {
   }
 }
 
+}
+
 int main(int argc, char **argv) {
+  using namespace llvm;
+
   // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
-  llvm::PrettyStackTraceProgram X(argc, argv);
+  PrettyStackTraceProgram X(argc, argv);
   cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
   llvm_shutdown_obj Y;
 
-  std::auto_ptr<Module> M(new Module("/tmp/autogen.bc", getGlobalContext()));
+  auto M = make_unique<Module>("/tmp/autogen.bc", getGlobalContext());
   Function *F = GenEmptyFunction(M.get());
-  FillFunction(F);
-  IntroduceControlFlow(F);
+
+  // Pick an initial seed value
+  Random R(SeedCL);
+  // Generate lots of random instructions inside a single basic block.
+  FillFunction(F, R);
+  // Break the basic block into many loops.
+  IntroduceControlFlow(F, R);
 
   // Figure out what stream we are supposed to write to...
-  OwningPtr<tool_output_file> Out;
+  std::unique_ptr<tool_output_file> Out;
   // Default to standard output.
   if (OutputFilename.empty())
     OutputFilename = "-";
 
-  std::string ErrorInfo;
-  Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
-                                 raw_fd_ostream::F_Binary));
-  if (!ErrorInfo.empty()) {
-    errs() << ErrorInfo << '\n';
+  std::error_code EC;
+  Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
+  if (EC) {
+    errs() << EC.message() << '\n';
     return 1;
   }
 
-  PassManager Passes;
+  legacy::PassManager Passes;
   Passes.add(createVerifierPass());
-  Passes.add(createPrintModulePass(&Out->os()));
+  Passes.add(createPrintModulePass(Out->os()));
   Passes.run(*M.get());
   Out->keep();