1 //===-- llvm-stress.cpp - Generate random LL files to stress-test LLVM ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program is a utility that generates random .ll files to stress-test
11 // different components in LLVM.
13 //===----------------------------------------------------------------------===//
14 #include "llvm/LLVMContext.h"
15 #include "llvm/Module.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instruction.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Support/PassNameParser.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/PluginLoader.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/ToolOutputFile.h"
35 static cl::opt<unsigned> SeedCL("seed",
36 cl::desc("Seed used for randomness"), cl::init(0));
37 static cl::opt<unsigned> SizeCL("size",
38 cl::desc("The estimated size of the generated function (# of instrs)"),
40 static cl::opt<std::string>
41 OutputFilename("o", cl::desc("Override output filename"),
42 cl::value_desc("filename"));
44 static cl::opt<bool> GenHalfFloat("generate-half-float",
45 cl::desc("Generate half-length floating-point values"), cl::init(false));
46 static cl::opt<bool> GenX86FP80("generate-x86-fp80",
47 cl::desc("Generate 80-bit X86 floating-point values"), cl::init(false));
48 static cl::opt<bool> GenFP128("generate-fp128",
49 cl::desc("Generate 128-bit floating-point values"), cl::init(false));
50 static cl::opt<bool> GenPPCFP128("generate-ppc-fp128",
51 cl::desc("Generate 128-bit PPC floating-point values"), cl::init(false));
52 static cl::opt<bool> GenX86MMX("generate-x86-mmx",
53 cl::desc("Generate X86 MMX floating-point values"), cl::init(false));
55 /// A utility class to provide a pseudo-random number generator which is
56 /// the same across all platforms. This is somewhat close to the libc
57 /// implementation. Note: This is not a cryptographically secure pseudorandom
62 Random(unsigned _seed):Seed(_seed) {}
63 /// Return the next random value.
65 unsigned Val = Seed + 0x000b07a1;
66 Seed = (Val * 0x3c7c0ac1);
67 // Only lowest 19 bits are random-ish.
68 return Seed & 0x7ffff;
75 /// Generate an empty function with a default argument list.
76 Function *GenEmptyFunction(Module *M) {
78 std::vector<Type*> ArgsTy;
79 // Define a few arguments
80 LLVMContext &Context = M->getContext();
81 ArgsTy.push_back(PointerType::get(IntegerType::getInt8Ty(Context), 0));
82 ArgsTy.push_back(PointerType::get(IntegerType::getInt32Ty(Context), 0));
83 ArgsTy.push_back(PointerType::get(IntegerType::getInt64Ty(Context), 0));
84 ArgsTy.push_back(IntegerType::getInt32Ty(Context));
85 ArgsTy.push_back(IntegerType::getInt64Ty(Context));
86 ArgsTy.push_back(IntegerType::getInt8Ty(Context));
88 FunctionType *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, 0);
89 // Pick a unique name to describe the input parameters
91 ss<<"autogen_SD"<<SeedCL;
92 Function *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
95 Func->setCallingConv(CallingConv::C);
99 /// A base class, implementing utilities needed for
100 /// modifying and adding new random instructions.
102 /// Used to store the randomly generated values.
103 typedef std::vector<Value*> PieceTable;
107 Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
108 BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {}
109 /// Add a new instruction.
110 virtual void Act() = 0;
111 /// Add N new instructions,
112 virtual void ActN(unsigned n) {
113 for (unsigned i=0; i<n; ++i)
118 /// Return a random value from the list of known values.
119 Value *getRandomVal() {
121 return PT->at(Ran->Rand() % PT->size());
124 Constant *getRandomConstant(Type *Tp) {
125 if (Tp->isIntegerTy()) {
127 return ConstantInt::getAllOnesValue(Tp);
128 return ConstantInt::getNullValue(Tp);
129 } else if (Tp->isFloatingPointTy()) {
131 return ConstantFP::getAllOnesValue(Tp);
132 return ConstantFP::getNullValue(Tp);
134 return UndefValue::get(Tp);
137 /// Return a random value with a known type.
138 Value *getRandomValue(Type *Tp) {
139 unsigned index = Ran->Rand();
140 for (unsigned i=0; i<PT->size(); ++i) {
141 Value *V = PT->at((index + i) % PT->size());
142 if (V->getType() == Tp)
146 // If the requested type was not found, generate a constant value.
147 if (Tp->isIntegerTy()) {
149 return ConstantInt::getAllOnesValue(Tp);
150 return ConstantInt::getNullValue(Tp);
151 } else if (Tp->isFloatingPointTy()) {
153 return ConstantFP::getAllOnesValue(Tp);
154 return ConstantFP::getNullValue(Tp);
155 } else if (Tp->isVectorTy()) {
156 VectorType *VTp = cast<VectorType>(Tp);
158 std::vector<Constant*> TempValues;
159 TempValues.reserve(VTp->getNumElements());
160 for (unsigned i = 0; i < VTp->getNumElements(); ++i)
161 TempValues.push_back(getRandomConstant(VTp->getScalarType()));
163 ArrayRef<Constant*> VectorValue(TempValues);
164 return ConstantVector::get(VectorValue);
167 return UndefValue::get(Tp);
170 /// Return a random value of any pointer type.
171 Value *getRandomPointerValue() {
172 unsigned index = Ran->Rand();
173 for (unsigned i=0; i<PT->size(); ++i) {
174 Value *V = PT->at((index + i) % PT->size());
175 if (V->getType()->isPointerTy())
178 return UndefValue::get(pickPointerType());
181 /// Return a random value of any vector type.
182 Value *getRandomVectorValue() {
183 unsigned index = Ran->Rand();
184 for (unsigned i=0; i<PT->size(); ++i) {
185 Value *V = PT->at((index + i) % PT->size());
186 if (V->getType()->isVectorTy())
189 return UndefValue::get(pickVectorType());
192 /// Pick a random type.
194 return (Ran->Rand() & 1 ? pickVectorType() : pickScalarType());
197 /// Pick a random pointer type.
198 Type *pickPointerType() {
199 Type *Ty = pickType();
200 return PointerType::get(Ty, 0);
203 /// Pick a random vector type.
204 Type *pickVectorType(unsigned len = (unsigned)-1) {
205 // Pick a random vector width in the range 2**0 to 2**4.
206 // by adding two randoms we are generating a normal-like distribution
208 unsigned width = 1<<((Ran->Rand() % 3) + (Ran->Rand() % 3));
211 // Vectors of x86mmx are illegal; keep trying till we get something else.
213 Ty = pickScalarType();
214 } while (Ty->isX86_MMXTy());
216 if (len != (unsigned)-1)
218 return VectorType::get(Ty, width);
221 /// Pick a random scalar type.
222 Type *pickScalarType() {
225 switch (Ran->Rand() % 30) {
226 case 0: t = Type::getInt1Ty(Context); break;
227 case 1: t = Type::getInt8Ty(Context); break;
228 case 2: t = Type::getInt16Ty(Context); break;
230 case 5: t = Type::getFloatTy(Context); break;
232 case 8: t = Type::getDoubleTy(Context); break;
234 case 11: t = Type::getInt32Ty(Context); break;
236 case 14: t = Type::getInt64Ty(Context); break;
238 case 17: if (GenHalfFloat) t = Type::getHalfTy(Context); break;
240 case 20: if (GenX86FP80) t = Type::getX86_FP80Ty(Context); break;
242 case 23: if (GenFP128) t = Type::getFP128Ty(Context); break;
244 case 26: if (GenPPCFP128) t = Type::getPPC_FP128Ty(Context); break;
246 case 29: if (GenX86MMX) t = Type::getX86_MMXTy(Context); break;
247 default: llvm_unreachable("Invalid scalar value");
254 /// Basic block to populate
258 /// Random number generator
261 LLVMContext &Context;
264 struct LoadModifier: public Modifier {
265 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
267 // Try to use predefined pointers. If non exist, use undef pointer value;
268 Value *Ptr = getRandomPointerValue();
269 Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
274 struct StoreModifier: public Modifier {
275 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
277 // Try to use predefined pointers. If non exist, use undef pointer value;
278 Value *Ptr = getRandomPointerValue();
279 Type *Tp = Ptr->getType();
280 Value *Val = getRandomValue(Tp->getContainedType(0));
281 Type *ValTy = Val->getType();
283 // Do not store vectors of i1s because they are unsupported
285 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
288 new StoreInst(Val, Ptr, BB->getTerminator());
292 struct BinModifier: public Modifier {
293 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
296 Value *Val0 = getRandomVal();
297 Value *Val1 = getRandomValue(Val0->getType());
299 // Don't handle pointer types.
300 if (Val0->getType()->isPointerTy() ||
301 Val1->getType()->isPointerTy())
304 // Don't handle i1 types.
305 if (Val0->getType()->getScalarSizeInBits() == 1)
309 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
310 Instruction* Term = BB->getTerminator();
311 unsigned R = Ran->Rand() % (isFloat ? 7 : 13);
312 Instruction::BinaryOps Op;
315 default: llvm_unreachable("Invalid BinOp");
316 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
317 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
318 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
319 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
320 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
321 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
322 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
323 case 7: {Op = Instruction::Shl; break; }
324 case 8: {Op = Instruction::LShr; break; }
325 case 9: {Op = Instruction::AShr; break; }
326 case 10:{Op = Instruction::And; break; }
327 case 11:{Op = Instruction::Or; break; }
328 case 12:{Op = Instruction::Xor; break; }
331 PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
335 /// Generate constant values.
336 struct ConstModifier: public Modifier {
337 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
339 Type *Ty = pickType();
341 if (Ty->isVectorTy()) {
342 switch (Ran->Rand() % 2) {
343 case 0: if (Ty->getScalarType()->isIntegerTy())
344 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
345 case 1: if (Ty->getScalarType()->isIntegerTy())
346 return PT->push_back(ConstantVector::getNullValue(Ty));
350 if (Ty->isFloatingPointTy()) {
352 return PT->push_back(ConstantFP::getNullValue(Ty));
353 return PT->push_back(ConstantFP::get(Ty,
354 static_cast<double>(1)/Ran->Rand()));
357 if (Ty->isIntegerTy()) {
358 switch (Ran->Rand() % 7) {
359 case 0: if (Ty->isIntegerTy())
360 return PT->push_back(ConstantInt::get(Ty,
361 APInt::getAllOnesValue(Ty->getPrimitiveSizeInBits())));
362 case 1: if (Ty->isIntegerTy())
363 return PT->push_back(ConstantInt::get(Ty,
364 APInt::getNullValue(Ty->getPrimitiveSizeInBits())));
365 case 2: case 3: case 4: case 5:
366 case 6: if (Ty->isIntegerTy())
367 PT->push_back(ConstantInt::get(Ty, Ran->Rand()));
374 struct AllocaModifier: public Modifier {
375 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
378 Type *Tp = pickType();
379 PT->push_back(new AllocaInst(Tp, "A", BB->getFirstNonPHI()));
383 struct ExtractElementModifier: public Modifier {
384 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
385 Modifier(BB, PT, R) {}
388 Value *Val0 = getRandomVectorValue();
389 Value *V = ExtractElementInst::Create(Val0,
390 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
391 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
392 "E", BB->getTerminator());
393 return PT->push_back(V);
397 struct ShuffModifier: public Modifier {
398 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
401 Value *Val0 = getRandomVectorValue();
402 Value *Val1 = getRandomValue(Val0->getType());
404 unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
405 std::vector<Constant*> Idxs;
407 Type *I32 = Type::getInt32Ty(BB->getContext());
408 for (unsigned i=0; i<Width; ++i) {
409 Constant *CI = ConstantInt::get(I32, Ran->Rand() % (Width*2));
410 // Pick some undef values.
411 if (!(Ran->Rand() % 5))
412 CI = UndefValue::get(I32);
416 Constant *Mask = ConstantVector::get(Idxs);
418 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
419 BB->getTerminator());
424 struct InsertElementModifier: public Modifier {
425 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
426 Modifier(BB, PT, R) {}
429 Value *Val0 = getRandomVectorValue();
430 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
432 Value *V = InsertElementInst::Create(Val0, Val1,
433 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
434 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
435 "I", BB->getTerminator());
436 return PT->push_back(V);
441 struct CastModifier: public Modifier {
442 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
445 Value *V = getRandomVal();
446 Type *VTy = V->getType();
447 Type *DestTy = pickScalarType();
449 // Handle vector casts vectors.
450 if (VTy->isVectorTy()) {
451 VectorType *VecTy = cast<VectorType>(VTy);
452 DestTy = pickVectorType(VecTy->getNumElements());
456 if (VTy == DestTy) return;
459 if (VTy->isPointerTy()) {
460 if (!DestTy->isPointerTy())
461 DestTy = PointerType::get(DestTy, 0);
462 return PT->push_back(
463 new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
466 // Generate lots of bitcasts.
467 if ((Ran->Rand() & 1) &&
468 VTy->getPrimitiveSizeInBits() == DestTy->getPrimitiveSizeInBits()) {
469 return PT->push_back(
470 new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
473 // Both types are integers:
474 if (VTy->getScalarType()->isIntegerTy() &&
475 DestTy->getScalarType()->isIntegerTy()) {
476 if (VTy->getScalarType()->getPrimitiveSizeInBits() >
477 DestTy->getScalarType()->getPrimitiveSizeInBits()) {
478 return PT->push_back(
479 new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
482 return PT->push_back(
483 new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
484 return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
489 if (VTy->getScalarType()->isFloatingPointTy() &&
490 DestTy->getScalarType()->isIntegerTy()) {
492 return PT->push_back(
493 new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
494 return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
498 if (VTy->getScalarType()->isIntegerTy() &&
499 DestTy->getScalarType()->isFloatingPointTy()) {
501 return PT->push_back(
502 new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
503 return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
508 if (VTy->getScalarType()->isFloatingPointTy() &&
509 DestTy->getScalarType()->isFloatingPointTy()) {
510 if (VTy->getScalarType()->getPrimitiveSizeInBits() >
511 DestTy->getScalarType()->getPrimitiveSizeInBits()) {
512 return PT->push_back(
513 new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
515 return PT->push_back(
516 new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
523 struct SelectModifier: public Modifier {
524 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
525 Modifier(BB, PT, R) {}
528 // Try a bunch of different select configuration until a valid one is found.
529 Value *Val0 = getRandomVal();
530 Value *Val1 = getRandomValue(Val0->getType());
532 Type *CondTy = Type::getInt1Ty(Context);
534 // If the value type is a vector, and we allow vector select, then in 50%
535 // of the cases generate a vector select.
536 if (Val0->getType()->isVectorTy() && (Ran->Rand() % 1)) {
537 unsigned NumElem = cast<VectorType>(Val0->getType())->getNumElements();
538 CondTy = VectorType::get(CondTy, NumElem);
541 Value *Cond = getRandomValue(CondTy);
542 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
543 return PT->push_back(V);
548 struct CmpModifier: public Modifier {
549 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
552 Value *Val0 = getRandomVal();
553 Value *Val1 = getRandomValue(Val0->getType());
555 if (Val0->getType()->isPointerTy()) return;
556 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
561 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
562 CmpInst::FIRST_FCMP_PREDICATE;
565 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
566 CmpInst::FIRST_ICMP_PREDICATE;
569 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
570 op, Val0, Val1, "Cmp", BB->getTerminator());
571 return PT->push_back(V);
575 void FillFunction(Function *F) {
576 // Create a legal entry block.
577 BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
578 ReturnInst::Create(F->getContext(), BB);
580 // Create the value table.
581 Modifier::PieceTable PT;
582 // Pick an initial seed value
585 // Consider arguments as legal values.
586 for (Function::arg_iterator it = F->arg_begin(), e = F->arg_end();
590 // List of modifiers which add new random instructions.
591 std::vector<Modifier*> Modifiers;
592 std::auto_ptr<Modifier> LM(new LoadModifier(BB, &PT, &R));
593 std::auto_ptr<Modifier> SM(new StoreModifier(BB, &PT, &R));
594 std::auto_ptr<Modifier> EE(new ExtractElementModifier(BB, &PT, &R));
595 std::auto_ptr<Modifier> SHM(new ShuffModifier(BB, &PT, &R));
596 std::auto_ptr<Modifier> IE(new InsertElementModifier(BB, &PT, &R));
597 std::auto_ptr<Modifier> BM(new BinModifier(BB, &PT, &R));
598 std::auto_ptr<Modifier> CM(new CastModifier(BB, &PT, &R));
599 std::auto_ptr<Modifier> SLM(new SelectModifier(BB, &PT, &R));
600 std::auto_ptr<Modifier> PM(new CmpModifier(BB, &PT, &R));
601 Modifiers.push_back(LM.get());
602 Modifiers.push_back(SM.get());
603 Modifiers.push_back(EE.get());
604 Modifiers.push_back(SHM.get());
605 Modifiers.push_back(IE.get());
606 Modifiers.push_back(BM.get());
607 Modifiers.push_back(CM.get());
608 Modifiers.push_back(SLM.get());
609 Modifiers.push_back(PM.get());
611 // Generate the random instructions
612 AllocaModifier AM(BB, &PT, &R); AM.ActN(5); // Throw in a few allocas
613 ConstModifier COM(BB, &PT, &R); COM.ActN(40); // Throw in a few constants
615 for (unsigned i=0; i< SizeCL / Modifiers.size(); ++i)
616 for (std::vector<Modifier*>::iterator it = Modifiers.begin(),
617 e = Modifiers.end(); it != e; ++it) {
621 SM->ActN(5); // Throw in a few stores.
624 void IntroduceControlFlow(Function *F) {
625 std::set<Instruction*> BoolInst;
626 for (BasicBlock::iterator it = F->begin()->begin(),
627 e = F->begin()->end(); it != e; ++it) {
628 if (it->getType() == IntegerType::getInt1Ty(F->getContext()))
632 for (std::set<Instruction*>::iterator it = BoolInst.begin(),
633 e = BoolInst.end(); it != e; ++it) {
634 Instruction *Instr = *it;
635 BasicBlock *Curr = Instr->getParent();
636 BasicBlock::iterator Loc= Instr;
637 BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
638 Instr->moveBefore(Curr->getTerminator());
639 if (Curr != &F->getEntryBlock()) {
640 BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
641 Curr->getTerminator()->eraseFromParent();
646 int main(int argc, char **argv) {
647 // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
648 llvm::PrettyStackTraceProgram X(argc, argv);
649 cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
652 std::auto_ptr<Module> M(new Module("/tmp/autogen.bc", getGlobalContext()));
653 Function *F = GenEmptyFunction(M.get());
655 IntroduceControlFlow(F);
657 // Figure out what stream we are supposed to write to...
658 OwningPtr<tool_output_file> Out;
659 // Default to standard output.
660 if (OutputFilename.empty())
661 OutputFilename = "-";
663 std::string ErrorInfo;
664 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
665 raw_fd_ostream::F_Binary));
666 if (!ErrorInfo.empty()) {
667 errs() << ErrorInfo << '\n';
672 Passes.add(createVerifierPass());
673 Passes.add(createPrintModulePass(&Out->os()));
674 Passes.run(*M.get());