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 /// A utility class to provide a pseudo-random number generator which is
45 /// the same across all platforms. This is somewhat close to the libc
46 /// implementation. Note: This is not a cryptographically secure pseudorandom
51 Random(unsigned _seed):Seed(_seed) {}
52 /// Return the next random value.
54 unsigned Val = Seed + 0x000b07a1;
55 Seed = (Val * 0x3c7c0ac1);
56 // Only lowest 19 bits are random-ish.
57 return Seed & 0x7ffff;
64 /// Generate an empty function with a default argument list.
65 Function *GenEmptyFunction(Module *M) {
67 std::vector<Type*> ArgsTy;
68 // Define a few arguments
69 LLVMContext &Context = M->getContext();
70 ArgsTy.push_back(PointerType::get(IntegerType::getInt8Ty(Context), 0));
71 ArgsTy.push_back(PointerType::get(IntegerType::getInt32Ty(Context), 0));
72 ArgsTy.push_back(PointerType::get(IntegerType::getInt64Ty(Context), 0));
73 ArgsTy.push_back(IntegerType::getInt32Ty(Context));
74 ArgsTy.push_back(IntegerType::getInt64Ty(Context));
75 ArgsTy.push_back(IntegerType::getInt8Ty(Context));
77 FunctionType *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, 0);
78 // Pick a unique name to describe the input parameters
80 ss<<"autogen_SD"<<SeedCL;
81 Function *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
84 Func->setCallingConv(CallingConv::C);
88 /// A base class, implementing utilities needed for
89 /// modifying and adding new random instructions.
91 /// Used to store the randomly generated values.
92 typedef std::vector<Value*> PieceTable;
96 Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
97 BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {};
98 /// Add a new instruction.
99 virtual void Act() = 0;
100 /// Add N new instructions,
101 virtual void ActN(unsigned n) {
102 for (unsigned i=0; i<n; ++i)
107 /// Return a random value from the list of known values.
108 Value *getRandomVal() {
110 return PT->at(Ran->Rand() % PT->size());
113 /// Return a random value with a known type.
114 Value *getRandomValue(Type *Tp) {
115 unsigned index = Ran->Rand();
116 for (unsigned i=0; i<PT->size(); ++i) {
117 Value *V = PT->at((index + i) % PT->size());
118 if (V->getType() == Tp)
122 // If the requested type was not found, generate a constant value.
123 if (Tp->isIntegerTy()) {
125 return ConstantInt::getAllOnesValue(Tp);
126 return ConstantInt::getNullValue(Tp);
127 } else if (Tp->isFloatingPointTy()) {
129 return ConstantFP::getAllOnesValue(Tp);
130 return ConstantFP::getNullValue(Tp);
133 // TODO: return values for vector types.
134 return UndefValue::get(Tp);
137 /// Return a random value of any pointer type.
138 Value *getRandomPointerValue() {
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()->isPointerTy())
145 return UndefValue::get(pickPointerType());
148 /// Return a random value of any vector type.
149 Value *getRandomVectorValue() {
150 unsigned index = Ran->Rand();
151 for (unsigned i=0; i<PT->size(); ++i) {
152 Value *V = PT->at((index + i) % PT->size());
153 if (V->getType()->isVectorTy())
156 return UndefValue::get(pickVectorType());
159 /// Pick a random type.
161 return (Ran->Rand() & 1 ? pickVectorType() : pickScalarType());
164 /// Pick a random pointer type.
165 Type *pickPointerType() {
166 Type *Ty = pickType();
167 return PointerType::get(Ty, 0);
170 /// Pick a random vector type.
171 Type *pickVectorType(unsigned len = (unsigned)-1) {
172 Type *Ty = pickScalarType();
173 // Pick a random vector width in the range 2**0 to 2**4.
174 // by adding two randoms we are generating a normal-like distribution
176 unsigned width = 1<<((Ran->Rand() % 3) + (Ran->Rand() % 3));
177 if (len != (unsigned)-1)
179 return VectorType::get(Ty, width);
182 /// Pick a random scalar type.
183 Type *pickScalarType() {
184 switch (Ran->Rand() % 15) {
185 case 0: return Type::getInt1Ty(Context);
186 case 1: return Type::getInt8Ty(Context);
187 case 2: return Type::getInt16Ty(Context);
189 case 5: return Type::getFloatTy(Context);
191 case 8: return Type::getDoubleTy(Context);
193 case 11: return Type::getInt32Ty(Context);
195 case 14: return Type::getInt64Ty(Context);
197 llvm_unreachable("Invalid scalar value");
200 /// Basic block to populate
204 /// Random number generator
207 LLVMContext &Context;
210 struct LoadModifier: public Modifier {
211 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {};
213 // Try to use predefined pointers. If non exist, use undef pointer value;
214 Value *Ptr = getRandomPointerValue();
215 Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
220 struct StoreModifier: public Modifier {
221 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
223 // Try to use predefined pointers. If non exist, use undef pointer value;
224 Value *Ptr = getRandomPointerValue();
225 Type *Tp = Ptr->getType();
226 Value *Val = getRandomValue(Tp->getContainedType(0));
227 Type *ValTy = Val->getType();
229 // Do not store vectors of i1s because they are unsupported
231 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
234 new StoreInst(Val, Ptr, BB->getTerminator());
238 struct BinModifier: public Modifier {
239 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
242 Value *Val0 = getRandomVal();
243 Value *Val1 = getRandomValue(Val0->getType());
245 // Don't handle pointer types.
246 if (Val0->getType()->isPointerTy() ||
247 Val1->getType()->isPointerTy())
250 // Don't handle i1 types.
251 if (Val0->getType()->getScalarSizeInBits() == 1)
255 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
256 Instruction* Term = BB->getTerminator();
257 unsigned R = Ran->Rand() % (isFloat ? 7 : 13);
258 Instruction::BinaryOps Op;
261 default: llvm_unreachable("Invalid BinOp");
262 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
263 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
264 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
265 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
266 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
267 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
268 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
269 case 7: {Op = Instruction::Shl; break; }
270 case 8: {Op = Instruction::LShr; break; }
271 case 9: {Op = Instruction::AShr; break; }
272 case 10:{Op = Instruction::And; break; }
273 case 11:{Op = Instruction::Or; break; }
274 case 12:{Op = Instruction::Xor; break; }
277 PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
281 /// Generate constant values.
282 struct ConstModifier: public Modifier {
283 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
285 Type *Ty = pickType();
287 if (Ty->isVectorTy()) {
288 switch (Ran->Rand() % 2) {
289 case 0: if (Ty->getScalarType()->isIntegerTy())
290 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
291 case 1: if (Ty->getScalarType()->isIntegerTy())
292 return PT->push_back(ConstantVector::getNullValue(Ty));
296 if (Ty->isFloatingPointTy()) {
298 return PT->push_back(ConstantFP::getNullValue(Ty));
299 return PT->push_back(ConstantFP::get(Ty,
300 static_cast<double>(1)/Ran->Rand()));
303 if (Ty->isIntegerTy()) {
304 switch (Ran->Rand() % 7) {
305 case 0: if (Ty->isIntegerTy())
306 return PT->push_back(ConstantInt::get(Ty,
307 APInt::getAllOnesValue(Ty->getPrimitiveSizeInBits())));
308 case 1: if (Ty->isIntegerTy())
309 return PT->push_back(ConstantInt::get(Ty,
310 APInt::getNullValue(Ty->getPrimitiveSizeInBits())));
311 case 2: case 3: case 4: case 5:
312 case 6: if (Ty->isIntegerTy())
313 PT->push_back(ConstantInt::get(Ty, Ran->Rand()));
320 struct AllocaModifier: public Modifier {
321 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
324 Type *Tp = pickType();
325 PT->push_back(new AllocaInst(Tp, "A", BB->getFirstNonPHI()));
329 struct ExtractElementModifier: public Modifier {
330 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
331 Modifier(BB, PT, R) {}
334 Value *Val0 = getRandomVectorValue();
335 Value *V = ExtractElementInst::Create(Val0,
336 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
337 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
338 "E", BB->getTerminator());
339 return PT->push_back(V);
343 struct ShuffModifier: public Modifier {
344 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
347 Value *Val0 = getRandomVectorValue();
348 Value *Val1 = getRandomValue(Val0->getType());
350 unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
351 std::vector<Constant*> Idxs;
353 Type *I32 = Type::getInt32Ty(BB->getContext());
354 for (unsigned i=0; i<Width; ++i) {
355 Constant *CI = ConstantInt::get(I32, Ran->Rand() % (Width*2));
356 // Pick some undef values.
357 if (!(Ran->Rand() % 5))
358 CI = UndefValue::get(I32);
362 Constant *Mask = ConstantVector::get(Idxs);
364 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
365 BB->getTerminator());
370 struct InsertElementModifier: public Modifier {
371 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
372 Modifier(BB, PT, R) {}
375 Value *Val0 = getRandomVectorValue();
376 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
378 Value *V = InsertElementInst::Create(Val0, Val1,
379 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
380 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
381 "I", BB->getTerminator());
382 return PT->push_back(V);
387 struct CastModifier: public Modifier {
388 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
391 Value *V = getRandomVal();
392 Type *VTy = V->getType();
393 Type *DestTy = pickScalarType();
395 // Handle vector casts vectors.
396 if (VTy->isVectorTy()) {
397 VectorType *VecTy = cast<VectorType>(VTy);
398 DestTy = pickVectorType(VecTy->getNumElements());
402 if (VTy == DestTy) return;
405 if (VTy->isPointerTy()) {
406 if (!DestTy->isPointerTy())
407 DestTy = PointerType::get(DestTy, 0);
408 return PT->push_back(
409 new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
412 // Generate lots of bitcasts.
413 if ((Ran->Rand() & 1) &&
414 VTy->getPrimitiveSizeInBits() == DestTy->getPrimitiveSizeInBits()) {
415 return PT->push_back(
416 new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
419 // Both types are integers:
420 if (VTy->getScalarType()->isIntegerTy() &&
421 DestTy->getScalarType()->isIntegerTy()) {
422 if (VTy->getScalarType()->getPrimitiveSizeInBits() >
423 DestTy->getScalarType()->getPrimitiveSizeInBits()) {
424 return PT->push_back(
425 new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
428 return PT->push_back(
429 new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
430 return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
435 if (VTy->getScalarType()->isFloatingPointTy() &&
436 DestTy->getScalarType()->isIntegerTy()) {
438 return PT->push_back(
439 new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
440 return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
444 if (VTy->getScalarType()->isIntegerTy() &&
445 DestTy->getScalarType()->isFloatingPointTy()) {
447 return PT->push_back(
448 new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
449 return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
454 if (VTy->getScalarType()->isFloatingPointTy() &&
455 DestTy->getScalarType()->isFloatingPointTy()) {
456 if (VTy->getScalarType()->getPrimitiveSizeInBits() >
457 DestTy->getScalarType()->getPrimitiveSizeInBits()) {
458 return PT->push_back(
459 new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
461 return PT->push_back(
462 new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
469 struct SelectModifier: public Modifier {
470 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
471 Modifier(BB, PT, R) {}
474 // Try a bunch of different select configuration until a valid one is found.
475 Value *Val0 = getRandomVal();
476 Value *Val1 = getRandomValue(Val0->getType());
478 Type *CondTy = Type::getInt1Ty(Context);
480 // If the value type is a vector, and we allow vector select, then in 50%
481 // of the cases generate a vector select.
482 if (Val0->getType()->isVectorTy() && (Ran->Rand() % 1)) {
483 unsigned NumElem = cast<VectorType>(Val0->getType())->getNumElements();
484 CondTy = VectorType::get(CondTy, NumElem);
487 Value *Cond = getRandomValue(CondTy);
488 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
489 return PT->push_back(V);
494 struct CmpModifier: public Modifier {
495 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
498 Value *Val0 = getRandomVal();
499 Value *Val1 = getRandomValue(Val0->getType());
501 if (Val0->getType()->isPointerTy()) return;
502 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
507 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
508 CmpInst::FIRST_FCMP_PREDICATE;
511 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
512 CmpInst::FIRST_ICMP_PREDICATE;
515 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
516 op, Val0, Val1, "Cmp", BB->getTerminator());
517 return PT->push_back(V);
521 void FillFunction(Function *F) {
522 // Create a legal entry block.
523 BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
524 ReturnInst::Create(F->getContext(), BB);
526 // Create the value table.
527 Modifier::PieceTable PT;
528 // Pick an initial seed value
531 // Consider arguments as legal values.
532 for (Function::arg_iterator it = F->arg_begin(), e = F->arg_end();
536 // List of modifiers which add new random instructions.
537 std::vector<Modifier*> Modifiers;
538 std::auto_ptr<Modifier> LM(new LoadModifier(BB, &PT, &R));
539 std::auto_ptr<Modifier> SM(new StoreModifier(BB, &PT, &R));
540 std::auto_ptr<Modifier> EE(new ExtractElementModifier(BB, &PT, &R));
541 std::auto_ptr<Modifier> SHM(new ShuffModifier(BB, &PT, &R));
542 std::auto_ptr<Modifier> IE(new InsertElementModifier(BB, &PT, &R));
543 std::auto_ptr<Modifier> BM(new BinModifier(BB, &PT, &R));
544 std::auto_ptr<Modifier> CM(new CastModifier(BB, &PT, &R));
545 std::auto_ptr<Modifier> SLM(new SelectModifier(BB, &PT, &R));
546 std::auto_ptr<Modifier> PM(new CmpModifier(BB, &PT, &R));
547 Modifiers.push_back(LM.get());
548 Modifiers.push_back(SM.get());
549 Modifiers.push_back(EE.get());
550 Modifiers.push_back(SHM.get());
551 Modifiers.push_back(IE.get());
552 Modifiers.push_back(BM.get());
553 Modifiers.push_back(CM.get());
554 Modifiers.push_back(SLM.get());
555 Modifiers.push_back(PM.get());
557 // Generate the random instructions
558 AllocaModifier AM(BB, &PT, &R); AM.ActN(5); // Throw in a few allocas
559 ConstModifier COM(BB, &PT, &R); COM.ActN(40); // Throw in a few constants
561 for (unsigned i=0; i< SizeCL / Modifiers.size(); ++i)
562 for (std::vector<Modifier*>::iterator it = Modifiers.begin(),
563 e = Modifiers.end(); it != e; ++it) {
567 SM->ActN(5); // Throw in a few stores.
570 void IntroduceControlFlow(Function *F) {
571 std::set<Instruction*> BoolInst;
572 for (BasicBlock::iterator it = F->begin()->begin(),
573 e = F->begin()->end(); it != e; ++it) {
574 if (it->getType() == IntegerType::getInt1Ty(F->getContext()))
578 for (std::set<Instruction*>::iterator it = BoolInst.begin(),
579 e = BoolInst.end(); it != e; ++it) {
580 Instruction *Instr = *it;
581 BasicBlock *Curr = Instr->getParent();
582 BasicBlock::iterator Loc= Instr;
583 BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
584 Instr->moveBefore(Curr->getTerminator());
585 if (Curr != &F->getEntryBlock()) {
586 BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
587 Curr->getTerminator()->eraseFromParent();
592 int main(int argc, char **argv) {
593 // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
594 llvm::PrettyStackTraceProgram X(argc, argv);
595 cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
598 std::auto_ptr<Module> M(new Module("/tmp/autogen.bc", getGlobalContext()));
599 Function *F = GenEmptyFunction(M.get());
601 IntroduceControlFlow(F);
603 // Figure out what stream we are supposed to write to...
604 OwningPtr<tool_output_file> Out;
605 // Default to standard output.
606 if (OutputFilename.empty())
607 OutputFilename = "-";
609 std::string ErrorInfo;
610 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
611 raw_fd_ostream::F_Binary));
612 if (!ErrorInfo.empty()) {
613 errs() << ErrorInfo << '\n';
618 Passes.add(createVerifierPass());
619 Passes.add(createPrintModulePass(&Out->os()));
620 Passes.run(*M.get());