[llvm-stress] Simple refactoring and better style. NFC.
[oota-llvm.git] / tools / llvm-stress / llvm-stress.cpp
1 //===-- llvm-stress.cpp - Generate random LL files to stress-test LLVM ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This program is a utility that generates random .ll files to stress-test
11 // different components in LLVM.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/CallGraphSCCPass.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/IRPrintingPasses.h"
18 #include "llvm/IR/Instruction.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/LegacyPassNameParser.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/PluginLoader.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/ToolOutputFile.h"
30 #include <algorithm>
31 #include <set>
32 #include <sstream>
33 #include <vector>
34 using namespace llvm;
35
36 static cl::opt<unsigned> SeedCL("seed",
37   cl::desc("Seed used for randomness"), cl::init(0));
38 static cl::opt<unsigned> SizeCL("size",
39   cl::desc("The estimated size of the generated function (# of instrs)"),
40   cl::init(100));
41 static cl::opt<std::string>
42 OutputFilename("o", cl::desc("Override output filename"),
43                cl::value_desc("filename"));
44
45 static cl::opt<bool> GenHalfFloat("generate-half-float",
46   cl::desc("Generate half-length floating-point values"), cl::init(false));
47 static cl::opt<bool> GenX86FP80("generate-x86-fp80",
48   cl::desc("Generate 80-bit X86 floating-point values"), cl::init(false));
49 static cl::opt<bool> GenFP128("generate-fp128",
50   cl::desc("Generate 128-bit floating-point values"), cl::init(false));
51 static cl::opt<bool> GenPPCFP128("generate-ppc-fp128",
52   cl::desc("Generate 128-bit PPC floating-point values"), cl::init(false));
53 static cl::opt<bool> GenX86MMX("generate-x86-mmx",
54   cl::desc("Generate X86 MMX floating-point values"), cl::init(false));
55
56 namespace {
57 /// A utility class to provide a pseudo-random number generator which is
58 /// the same across all platforms. This is somewhat close to the libc
59 /// implementation. Note: This is not a cryptographically secure pseudorandom
60 /// number generator.
61 class Random {
62 public:
63   /// C'tor
64   Random(unsigned _seed):Seed(_seed) {}
65
66   /// Return a random integer, up to a
67   /// maximum of 2**19 - 1.
68   uint32_t Rand() {
69     uint32_t Val = Seed + 0x000b07a1;
70     Seed = (Val * 0x3c7c0ac1);
71     // Only lowest 19 bits are random-ish.
72     return Seed & 0x7ffff;
73   }
74
75   /// Return a random 32 bit integer.
76   uint32_t Rand32() {
77     uint32_t Val = Rand();
78     Val &= 0xffff;
79     return Val | (Rand() << 16);
80   }
81
82   /// Return a random 64 bit integer.
83   uint64_t Rand64() {
84     uint64_t Val = Rand32();
85     return Val | (uint64_t(Rand32()) << 32);
86   }
87
88   /// Rand operator for STL algorithms.
89   ptrdiff_t operator()(ptrdiff_t y) {
90     return  Rand64() % y;
91   }
92
93 private:
94   unsigned Seed;
95 };
96
97 /// Generate an empty function with a default argument list.
98 Function *GenEmptyFunction(Module *M) {
99   // Define a few arguments
100   LLVMContext &Context = M->getContext();
101   Type* ArgsTy[] = {
102     Type::getInt8PtrTy(Context),
103     Type::getInt32PtrTy(Context),
104     Type::getInt64PtrTy(Context),
105     Type::getInt32Ty(Context),
106     Type::getInt64Ty(Context),
107     Type::getInt8Ty(Context)
108   };
109
110   auto *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, false);
111   // Pick a unique name to describe the input parameters
112   Twine Name = "autogen_SD" + Twine{SeedCL};
113   auto *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage, Name, M);
114   Func->setCallingConv(CallingConv::C);
115   return Func;
116 }
117
118 /// A base class, implementing utilities needed for
119 /// modifying and adding new random instructions.
120 struct Modifier {
121   /// Used to store the randomly generated values.
122   typedef std::vector<Value*> PieceTable;
123
124 public:
125   /// C'tor
126   Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
127     BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {}
128
129   /// virtual D'tor to silence warnings.
130   virtual ~Modifier() {}
131
132   /// Add a new instruction.
133   virtual void Act() = 0;
134   /// Add N new instructions,
135   virtual void ActN(unsigned n) {
136     for (unsigned i=0; i<n; ++i)
137       Act();
138   }
139
140 protected:
141   /// Return a random value from the list of known values.
142   Value *getRandomVal() {
143     assert(PT->size());
144     return PT->at(Ran->Rand() % PT->size());
145   }
146
147   Constant *getRandomConstant(Type *Tp) {
148     if (Tp->isIntegerTy()) {
149       if (Ran->Rand() & 1)
150         return ConstantInt::getAllOnesValue(Tp);
151       return ConstantInt::getNullValue(Tp);
152     } else if (Tp->isFloatingPointTy()) {
153       if (Ran->Rand() & 1)
154         return ConstantFP::getAllOnesValue(Tp);
155       return ConstantFP::getNullValue(Tp);
156     }
157     return UndefValue::get(Tp);
158   }
159
160   /// Return a random value with a known type.
161   Value *getRandomValue(Type *Tp) {
162     unsigned index = Ran->Rand();
163     for (unsigned i=0; i<PT->size(); ++i) {
164       Value *V = PT->at((index + i) % PT->size());
165       if (V->getType() == Tp)
166         return V;
167     }
168
169     // If the requested type was not found, generate a constant value.
170     if (Tp->isIntegerTy()) {
171       if (Ran->Rand() & 1)
172         return ConstantInt::getAllOnesValue(Tp);
173       return ConstantInt::getNullValue(Tp);
174     } else if (Tp->isFloatingPointTy()) {
175       if (Ran->Rand() & 1)
176         return ConstantFP::getAllOnesValue(Tp);
177       return ConstantFP::getNullValue(Tp);
178     } else if (Tp->isVectorTy()) {
179       VectorType *VTp = cast<VectorType>(Tp);
180
181       std::vector<Constant*> TempValues;
182       TempValues.reserve(VTp->getNumElements());
183       for (unsigned i = 0; i < VTp->getNumElements(); ++i)
184         TempValues.push_back(getRandomConstant(VTp->getScalarType()));
185
186       ArrayRef<Constant*> VectorValue(TempValues);
187       return ConstantVector::get(VectorValue);
188     }
189
190     return UndefValue::get(Tp);
191   }
192
193   /// Return a random value of any pointer type.
194   Value *getRandomPointerValue() {
195     unsigned index = Ran->Rand();
196     for (unsigned i=0; i<PT->size(); ++i) {
197       Value *V = PT->at((index + i) % PT->size());
198       if (V->getType()->isPointerTy())
199         return V;
200     }
201     return UndefValue::get(pickPointerType());
202   }
203
204   /// Return a random value of any vector type.
205   Value *getRandomVectorValue() {
206     unsigned index = Ran->Rand();
207     for (unsigned i=0; i<PT->size(); ++i) {
208       Value *V = PT->at((index + i) % PT->size());
209       if (V->getType()->isVectorTy())
210         return V;
211     }
212     return UndefValue::get(pickVectorType());
213   }
214
215   /// Pick a random type.
216   Type *pickType() {
217     return (Ran->Rand() & 1 ? pickVectorType() : pickScalarType());
218   }
219
220   /// Pick a random pointer type.
221   Type *pickPointerType() {
222     Type *Ty = pickType();
223     return PointerType::get(Ty, 0);
224   }
225
226   /// Pick a random vector type.
227   Type *pickVectorType(unsigned len = (unsigned)-1) {
228     // Pick a random vector width in the range 2**0 to 2**4.
229     // by adding two randoms we are generating a normal-like distribution
230     // around 2**3.
231     unsigned width = 1<<((Ran->Rand() % 3) + (Ran->Rand() % 3));
232     Type *Ty;
233
234     // Vectors of x86mmx are illegal; keep trying till we get something else.
235     do {
236       Ty = pickScalarType();
237     } while (Ty->isX86_MMXTy());
238
239     if (len != (unsigned)-1)
240       width = len;
241     return VectorType::get(Ty, width);
242   }
243
244   /// Pick a random scalar type.
245   Type *pickScalarType() {
246     Type *t = nullptr;
247     do {
248       switch (Ran->Rand() % 30) {
249       case 0: t = Type::getInt1Ty(Context); break;
250       case 1: t = Type::getInt8Ty(Context); break;
251       case 2: t = Type::getInt16Ty(Context); break;
252       case 3: case 4:
253       case 5: t = Type::getFloatTy(Context); break;
254       case 6: case 7:
255       case 8: t = Type::getDoubleTy(Context); break;
256       case 9: case 10:
257       case 11: t = Type::getInt32Ty(Context); break;
258       case 12: case 13:
259       case 14: t = Type::getInt64Ty(Context); break;
260       case 15: case 16:
261       case 17: if (GenHalfFloat) t = Type::getHalfTy(Context); break;
262       case 18: case 19:
263       case 20: if (GenX86FP80) t = Type::getX86_FP80Ty(Context); break;
264       case 21: case 22:
265       case 23: if (GenFP128) t = Type::getFP128Ty(Context); break;
266       case 24: case 25:
267       case 26: if (GenPPCFP128) t = Type::getPPC_FP128Ty(Context); break;
268       case 27: case 28:
269       case 29: if (GenX86MMX) t = Type::getX86_MMXTy(Context); break;
270       default: llvm_unreachable("Invalid scalar value");
271       }
272     } while (t == nullptr);
273
274     return t;
275   }
276
277   /// Basic block to populate
278   BasicBlock *BB;
279   /// Value table
280   PieceTable *PT;
281   /// Random number generator
282   Random *Ran;
283   /// Context
284   LLVMContext &Context;
285 };
286
287 struct LoadModifier: public Modifier {
288   LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
289   void Act() override {
290     // Try to use predefined pointers. If non-exist, use undef pointer value;
291     Value *Ptr = getRandomPointerValue();
292     Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
293     PT->push_back(V);
294   }
295 };
296
297 struct StoreModifier: public Modifier {
298   StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
299   void Act() override {
300     // Try to use predefined pointers. If non-exist, use undef pointer value;
301     Value *Ptr = getRandomPointerValue();
302     Type  *Tp = Ptr->getType();
303     Value *Val = getRandomValue(Tp->getContainedType(0));
304     Type  *ValTy = Val->getType();
305
306     // Do not store vectors of i1s because they are unsupported
307     // by the codegen.
308     if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
309       return;
310
311     new StoreInst(Val, Ptr, BB->getTerminator());
312   }
313 };
314
315 struct BinModifier: public Modifier {
316   BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
317
318   void Act() override {
319     Value *Val0 = getRandomVal();
320     Value *Val1 = getRandomValue(Val0->getType());
321
322     // Don't handle pointer types.
323     if (Val0->getType()->isPointerTy() ||
324         Val1->getType()->isPointerTy())
325       return;
326
327     // Don't handle i1 types.
328     if (Val0->getType()->getScalarSizeInBits() == 1)
329       return;
330
331
332     bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
333     Instruction* Term = BB->getTerminator();
334     unsigned R = Ran->Rand() % (isFloat ? 7 : 13);
335     Instruction::BinaryOps Op;
336
337     switch (R) {
338     default: llvm_unreachable("Invalid BinOp");
339     case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
340     case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
341     case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
342     case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
343     case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
344     case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
345     case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
346     case 7: {Op = Instruction::Shl;  break; }
347     case 8: {Op = Instruction::LShr; break; }
348     case 9: {Op = Instruction::AShr; break; }
349     case 10:{Op = Instruction::And;  break; }
350     case 11:{Op = Instruction::Or;   break; }
351     case 12:{Op = Instruction::Xor;  break; }
352     }
353
354     PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
355   }
356 };
357
358 /// Generate constant values.
359 struct ConstModifier: public Modifier {
360   ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
361   void Act() override {
362     Type *Ty = pickType();
363
364     if (Ty->isVectorTy()) {
365       switch (Ran->Rand() % 2) {
366       case 0: if (Ty->getScalarType()->isIntegerTy())
367                 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
368       case 1: if (Ty->getScalarType()->isIntegerTy())
369                 return PT->push_back(ConstantVector::getNullValue(Ty));
370       }
371     }
372
373     if (Ty->isFloatingPointTy()) {
374       // Generate 128 random bits, the size of the (currently)
375       // largest floating-point types.
376       uint64_t RandomBits[2];
377       for (unsigned i = 0; i < 2; ++i)
378         RandomBits[i] = Ran->Rand64();
379
380       APInt RandomInt(Ty->getPrimitiveSizeInBits(), makeArrayRef(RandomBits));
381       APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
382
383       if (Ran->Rand() & 1)
384         return PT->push_back(ConstantFP::getNullValue(Ty));
385       return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
386     }
387
388     if (Ty->isIntegerTy()) {
389       switch (Ran->Rand() % 7) {
390       case 0: if (Ty->isIntegerTy())
391                 return PT->push_back(ConstantInt::get(Ty,
392                   APInt::getAllOnesValue(Ty->getPrimitiveSizeInBits())));
393       case 1: if (Ty->isIntegerTy())
394                 return PT->push_back(ConstantInt::get(Ty,
395                   APInt::getNullValue(Ty->getPrimitiveSizeInBits())));
396       case 2: case 3: case 4: case 5:
397       case 6: if (Ty->isIntegerTy())
398                 PT->push_back(ConstantInt::get(Ty, Ran->Rand()));
399       }
400     }
401
402   }
403 };
404
405 struct AllocaModifier: public Modifier {
406   AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
407
408   void Act() override {
409     Type *Tp = pickType();
410     PT->push_back(new AllocaInst(Tp, "A", BB->getFirstNonPHI()));
411   }
412 };
413
414 struct ExtractElementModifier: public Modifier {
415   ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
416     Modifier(BB, PT, R) {}
417
418   void Act() override {
419     Value *Val0 = getRandomVectorValue();
420     Value *V = ExtractElementInst::Create(Val0,
421              ConstantInt::get(Type::getInt32Ty(BB->getContext()),
422              Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
423              "E", BB->getTerminator());
424     return PT->push_back(V);
425   }
426 };
427
428 struct ShuffModifier: public Modifier {
429   ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
430   void Act() override {
431
432     Value *Val0 = getRandomVectorValue();
433     Value *Val1 = getRandomValue(Val0->getType());
434
435     unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
436     std::vector<Constant*> Idxs;
437
438     Type *I32 = Type::getInt32Ty(BB->getContext());
439     for (unsigned i=0; i<Width; ++i) {
440       Constant *CI = ConstantInt::get(I32, Ran->Rand() % (Width*2));
441       // Pick some undef values.
442       if (!(Ran->Rand() % 5))
443         CI = UndefValue::get(I32);
444       Idxs.push_back(CI);
445     }
446
447     Constant *Mask = ConstantVector::get(Idxs);
448
449     Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
450                                      BB->getTerminator());
451     PT->push_back(V);
452   }
453 };
454
455 struct InsertElementModifier: public Modifier {
456   InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
457     Modifier(BB, PT, R) {}
458
459   void Act() override {
460     Value *Val0 = getRandomVectorValue();
461     Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
462
463     Value *V = InsertElementInst::Create(Val0, Val1,
464               ConstantInt::get(Type::getInt32Ty(BB->getContext()),
465               Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
466               "I",  BB->getTerminator());
467     return PT->push_back(V);
468   }
469
470 };
471
472 struct CastModifier: public Modifier {
473   CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
474   void Act() override {
475
476     Value *V = getRandomVal();
477     Type *VTy = V->getType();
478     Type *DestTy = pickScalarType();
479
480     // Handle vector casts vectors.
481     if (VTy->isVectorTy()) {
482       VectorType *VecTy = cast<VectorType>(VTy);
483       DestTy = pickVectorType(VecTy->getNumElements());
484     }
485
486     // no need to cast.
487     if (VTy == DestTy) return;
488
489     // Pointers:
490     if (VTy->isPointerTy()) {
491       if (!DestTy->isPointerTy())
492         DestTy = PointerType::get(DestTy, 0);
493       return PT->push_back(
494         new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
495     }
496
497     unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
498     unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
499
500     // Generate lots of bitcasts.
501     if ((Ran->Rand() & 1) && VSize == DestSize) {
502       return PT->push_back(
503         new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
504     }
505
506     // Both types are integers:
507     if (VTy->getScalarType()->isIntegerTy() &&
508         DestTy->getScalarType()->isIntegerTy()) {
509       if (VSize > DestSize) {
510         return PT->push_back(
511           new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
512       } else {
513         assert(VSize < DestSize && "Different int types with the same size?");
514         if (Ran->Rand() & 1)
515           return PT->push_back(
516             new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
517         return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
518       }
519     }
520
521     // Fp to int.
522     if (VTy->getScalarType()->isFloatingPointTy() &&
523         DestTy->getScalarType()->isIntegerTy()) {
524       if (Ran->Rand() & 1)
525         return PT->push_back(
526           new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
527       return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
528     }
529
530     // Int to fp.
531     if (VTy->getScalarType()->isIntegerTy() &&
532         DestTy->getScalarType()->isFloatingPointTy()) {
533       if (Ran->Rand() & 1)
534         return PT->push_back(
535           new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
536       return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
537
538     }
539
540     // Both floats.
541     if (VTy->getScalarType()->isFloatingPointTy() &&
542         DestTy->getScalarType()->isFloatingPointTy()) {
543       if (VSize > DestSize) {
544         return PT->push_back(
545           new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
546       } else if (VSize < DestSize) {
547         return PT->push_back(
548           new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
549       }
550       // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
551       // for which there is no defined conversion. So do nothing.
552     }
553   }
554
555 };
556
557 struct SelectModifier: public Modifier {
558   SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
559     Modifier(BB, PT, R) {}
560
561   void Act() override {
562     // Try a bunch of different select configuration until a valid one is found.
563       Value *Val0 = getRandomVal();
564       Value *Val1 = getRandomValue(Val0->getType());
565
566       Type *CondTy = Type::getInt1Ty(Context);
567
568       // If the value type is a vector, and we allow vector select, then in 50%
569       // of the cases generate a vector select.
570       if (Val0->getType()->isVectorTy() && (Ran->Rand() % 1)) {
571         unsigned NumElem = cast<VectorType>(Val0->getType())->getNumElements();
572         CondTy = VectorType::get(CondTy, NumElem);
573       }
574
575       Value *Cond = getRandomValue(CondTy);
576       Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
577       return PT->push_back(V);
578   }
579 };
580
581
582 struct CmpModifier: public Modifier {
583   CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
584   void Act() override {
585
586     Value *Val0 = getRandomVal();
587     Value *Val1 = getRandomValue(Val0->getType());
588
589     if (Val0->getType()->isPointerTy()) return;
590     bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
591
592     int op;
593     if (fp) {
594       op = Ran->Rand() %
595       (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
596        CmpInst::FIRST_FCMP_PREDICATE;
597     } else {
598       op = Ran->Rand() %
599       (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
600        CmpInst::FIRST_ICMP_PREDICATE;
601     }
602
603     Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
604                                op, Val0, Val1, "Cmp", BB->getTerminator());
605     return PT->push_back(V);
606   }
607 };
608
609 } // end anonymous namespace
610
611 static void FillFunction(Function *F, Random &R) {
612   // Create a legal entry block.
613   BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
614   ReturnInst::Create(F->getContext(), BB);
615
616   // Create the value table.
617   Modifier::PieceTable PT;
618
619   // Consider arguments as legal values.
620   for (auto &arg : F->args())
621     PT.push_back(&arg);
622
623   // List of modifiers which add new random instructions.
624   std::vector<std::unique_ptr<Modifier>> Modifiers;
625   Modifiers.emplace_back(new LoadModifier(BB, &PT, &R));
626   Modifiers.emplace_back(new StoreModifier(BB, &PT, &R));
627   auto SM = Modifiers.back().get();
628   Modifiers.emplace_back(new ExtractElementModifier(BB, &PT, &R));
629   Modifiers.emplace_back(new ShuffModifier(BB, &PT, &R));
630   Modifiers.emplace_back(new InsertElementModifier(BB, &PT, &R));
631   Modifiers.emplace_back(new BinModifier(BB, &PT, &R));
632   Modifiers.emplace_back(new CastModifier(BB, &PT, &R));
633   Modifiers.emplace_back(new SelectModifier(BB, &PT, &R));
634   Modifiers.emplace_back(new CmpModifier(BB, &PT, &R));
635
636   // Generate the random instructions
637   AllocaModifier{BB, &PT, &R}.ActN(5); // Throw in a few allocas
638   ConstModifier{BB, &PT, &R}.ActN(40); // Throw in a few constants
639
640   for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
641     for (auto &Mod : Modifiers)
642       Mod->Act();
643
644   SM->ActN(5); // Throw in a few stores.
645 }
646
647 static void IntroduceControlFlow(Function *F, Random &R) {
648   std::vector<Instruction*> BoolInst;
649   for (auto &Instr : F->front()) {
650     if (Instr.getType() == IntegerType::getInt1Ty(F->getContext()))
651       BoolInst.push_back(&Instr);
652   }
653
654   std::random_shuffle(BoolInst.begin(), BoolInst.end(), R);
655
656   for (auto *Instr : BoolInst) {
657     BasicBlock *Curr = Instr->getParent();
658     BasicBlock::iterator Loc = Instr;
659     BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
660     Instr->moveBefore(Curr->getTerminator());
661     if (Curr != &F->getEntryBlock()) {
662       BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
663       Curr->getTerminator()->eraseFromParent();
664     }
665   }
666 }
667
668 int main(int argc, char **argv) {
669   // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
670   llvm::PrettyStackTraceProgram X(argc, argv);
671   cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
672   llvm_shutdown_obj Y;
673
674   auto M = make_unique<Module>("/tmp/autogen.bc", getGlobalContext());
675   Function *F = GenEmptyFunction(M.get());
676
677   // Pick an initial seed value
678   Random R(SeedCL);
679   // Generate lots of random instructions inside a single basic block.
680   FillFunction(F, R);
681   // Break the basic block into many loops.
682   IntroduceControlFlow(F, R);
683
684   // Figure out what stream we are supposed to write to...
685   std::unique_ptr<tool_output_file> Out;
686   // Default to standard output.
687   if (OutputFilename.empty())
688     OutputFilename = "-";
689
690   std::error_code EC;
691   Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
692   if (EC) {
693     errs() << EC.message() << '\n';
694     return 1;
695   }
696
697   legacy::PassManager Passes;
698   Passes.add(createVerifierPass());
699   Passes.add(createPrintModulePass(Out->os()));
700   Passes.run(*M.get());
701   Out->keep();
702
703   return 0;
704 }