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 //===----------------------------------------------------------------------===//
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"
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)"),
41 static cl::opt<std::string>
42 OutputFilename("o", cl::desc("Override output filename"),
43 cl::value_desc("filename"));
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));
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
64 Random(unsigned _seed):Seed(_seed) {}
66 /// Return a random integer, up to a
67 /// maximum of 2**19 - 1.
69 uint32_t Val = Seed + 0x000b07a1;
70 Seed = (Val * 0x3c7c0ac1);
71 // Only lowest 19 bits are random-ish.
72 return Seed & 0x7ffff;
75 /// Return a random 32 bit integer.
77 uint32_t Val = Rand();
79 return Val | (Rand() << 16);
82 /// Return a random 64 bit integer.
84 uint64_t Val = Rand32();
85 return Val | (uint64_t(Rand32()) << 32);
88 /// Rand operator for STL algorithms.
89 ptrdiff_t operator()(ptrdiff_t y) {
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();
102 Type::getInt8PtrTy(Context),
103 Type::getInt32PtrTy(Context),
104 Type::getInt64PtrTy(Context),
105 Type::getInt32Ty(Context),
106 Type::getInt64Ty(Context),
107 Type::getInt8Ty(Context)
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);
118 /// A base class, implementing utilities needed for
119 /// modifying and adding new random instructions.
121 /// Used to store the randomly generated values.
122 typedef std::vector<Value*> PieceTable;
126 Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
127 BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {}
129 /// virtual D'tor to silence warnings.
130 virtual ~Modifier() {}
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)
141 /// Return a random value from the list of known values.
142 Value *getRandomVal() {
144 return PT->at(Ran->Rand() % PT->size());
147 Constant *getRandomConstant(Type *Tp) {
148 if (Tp->isIntegerTy()) {
150 return ConstantInt::getAllOnesValue(Tp);
151 return ConstantInt::getNullValue(Tp);
152 } else if (Tp->isFloatingPointTy()) {
154 return ConstantFP::getAllOnesValue(Tp);
155 return ConstantFP::getNullValue(Tp);
157 return UndefValue::get(Tp);
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)
169 // If the requested type was not found, generate a constant value.
170 if (Tp->isIntegerTy()) {
172 return ConstantInt::getAllOnesValue(Tp);
173 return ConstantInt::getNullValue(Tp);
174 } else if (Tp->isFloatingPointTy()) {
176 return ConstantFP::getAllOnesValue(Tp);
177 return ConstantFP::getNullValue(Tp);
178 } else if (Tp->isVectorTy()) {
179 VectorType *VTp = cast<VectorType>(Tp);
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()));
186 ArrayRef<Constant*> VectorValue(TempValues);
187 return ConstantVector::get(VectorValue);
190 return UndefValue::get(Tp);
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())
201 return UndefValue::get(pickPointerType());
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())
212 return UndefValue::get(pickVectorType());
215 /// Pick a random type.
217 return (Ran->Rand() & 1 ? pickVectorType() : pickScalarType());
220 /// Pick a random pointer type.
221 Type *pickPointerType() {
222 Type *Ty = pickType();
223 return PointerType::get(Ty, 0);
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
231 unsigned width = 1<<((Ran->Rand() % 3) + (Ran->Rand() % 3));
234 // Vectors of x86mmx are illegal; keep trying till we get something else.
236 Ty = pickScalarType();
237 } while (Ty->isX86_MMXTy());
239 if (len != (unsigned)-1)
241 return VectorType::get(Ty, width);
244 /// Pick a random scalar type.
245 Type *pickScalarType() {
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;
253 case 5: t = Type::getFloatTy(Context); break;
255 case 8: t = Type::getDoubleTy(Context); break;
257 case 11: t = Type::getInt32Ty(Context); break;
259 case 14: t = Type::getInt64Ty(Context); break;
261 case 17: if (GenHalfFloat) t = Type::getHalfTy(Context); break;
263 case 20: if (GenX86FP80) t = Type::getX86_FP80Ty(Context); break;
265 case 23: if (GenFP128) t = Type::getFP128Ty(Context); break;
267 case 26: if (GenPPCFP128) t = Type::getPPC_FP128Ty(Context); break;
269 case 29: if (GenX86MMX) t = Type::getX86_MMXTy(Context); break;
270 default: llvm_unreachable("Invalid scalar value");
272 } while (t == nullptr);
277 /// Basic block to populate
281 /// Random number generator
284 LLVMContext &Context;
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());
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();
306 // Do not store vectors of i1s because they are unsupported
308 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
311 new StoreInst(Val, Ptr, BB->getTerminator());
315 struct BinModifier: public Modifier {
316 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
318 void Act() override {
319 Value *Val0 = getRandomVal();
320 Value *Val1 = getRandomValue(Val0->getType());
322 // Don't handle pointer types.
323 if (Val0->getType()->isPointerTy() ||
324 Val1->getType()->isPointerTy())
327 // Don't handle i1 types.
328 if (Val0->getType()->getScalarSizeInBits() == 1)
332 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
333 Instruction* Term = BB->getTerminator();
334 unsigned R = Ran->Rand() % (isFloat ? 7 : 13);
335 Instruction::BinaryOps Op;
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; }
354 PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
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();
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));
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();
380 APInt RandomInt(Ty->getPrimitiveSizeInBits(), makeArrayRef(RandomBits));
381 APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
384 return PT->push_back(ConstantFP::getNullValue(Ty));
385 return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
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()));
405 struct AllocaModifier: public Modifier {
406 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
408 void Act() override {
409 Type *Tp = pickType();
410 PT->push_back(new AllocaInst(Tp, "A", BB->getFirstNonPHI()));
414 struct ExtractElementModifier: public Modifier {
415 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
416 Modifier(BB, PT, R) {}
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);
428 struct ShuffModifier: public Modifier {
429 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
430 void Act() override {
432 Value *Val0 = getRandomVectorValue();
433 Value *Val1 = getRandomValue(Val0->getType());
435 unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
436 std::vector<Constant*> Idxs;
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);
447 Constant *Mask = ConstantVector::get(Idxs);
449 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
450 BB->getTerminator());
455 struct InsertElementModifier: public Modifier {
456 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
457 Modifier(BB, PT, R) {}
459 void Act() override {
460 Value *Val0 = getRandomVectorValue();
461 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
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);
472 struct CastModifier: public Modifier {
473 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
474 void Act() override {
476 Value *V = getRandomVal();
477 Type *VTy = V->getType();
478 Type *DestTy = pickScalarType();
480 // Handle vector casts vectors.
481 if (VTy->isVectorTy()) {
482 VectorType *VecTy = cast<VectorType>(VTy);
483 DestTy = pickVectorType(VecTy->getNumElements());
487 if (VTy == DestTy) return;
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()));
497 unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
498 unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
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()));
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()));
513 assert(VSize < DestSize && "Different int types with the same size?");
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()));
522 if (VTy->getScalarType()->isFloatingPointTy() &&
523 DestTy->getScalarType()->isIntegerTy()) {
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()));
531 if (VTy->getScalarType()->isIntegerTy() &&
532 DestTy->getScalarType()->isFloatingPointTy()) {
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()));
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()));
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.
557 struct SelectModifier: public Modifier {
558 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
559 Modifier(BB, PT, R) {}
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());
566 Type *CondTy = Type::getInt1Ty(Context);
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);
575 Value *Cond = getRandomValue(CondTy);
576 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
577 return PT->push_back(V);
582 struct CmpModifier: public Modifier {
583 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
584 void Act() override {
586 Value *Val0 = getRandomVal();
587 Value *Val1 = getRandomValue(Val0->getType());
589 if (Val0->getType()->isPointerTy()) return;
590 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
595 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
596 CmpInst::FIRST_FCMP_PREDICATE;
599 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
600 CmpInst::FIRST_ICMP_PREDICATE;
603 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
604 op, Val0, Val1, "Cmp", BB->getTerminator());
605 return PT->push_back(V);
609 } // end anonymous namespace
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);
616 // Create the value table.
617 Modifier::PieceTable PT;
619 // Consider arguments as legal values.
620 for (auto &arg : F->args())
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));
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
640 for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
641 for (auto &Mod : Modifiers)
644 SM->ActN(5); // Throw in a few stores.
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);
654 std::random_shuffle(BoolInst.begin(), BoolInst.end(), R);
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();
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");
674 auto M = make_unique<Module>("/tmp/autogen.bc", getGlobalContext());
675 Function *F = GenEmptyFunction(M.get());
677 // Pick an initial seed value
679 // Generate lots of random instructions inside a single basic block.
681 // Break the basic block into many loops.
682 IntroduceControlFlow(F, R);
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 = "-";
691 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
693 errs() << EC.message() << '\n';
697 legacy::PassManager Passes;
698 Passes.add(createVerifierPass());
699 Passes.add(createPrintModulePass(Out->os()));
700 Passes.run(*M.get());