blob: 3cf8b37bc2e29ed98da3cdf7e9e589a75bc6794d [file] [log] [blame]
Daniel Dunbarbeb34252012-02-29 00:20:33 +00001//===-- llvm-stress.cpp - Generate random LL files to stress-test LLVM ----===//
Nadav Rotem78bda892012-02-26 08:35:53 +00002//
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//===----------------------------------------------------------------------===//
Ahmed Charles56440fd2014-03-06 05:51:42 +000014
Chandler Carruth839a98e2013-01-07 15:26:48 +000015#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000017#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Instruction.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000019#include "llvm/IR/LLVMContext.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000020#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth1b69ed82014-03-04 12:32:42 +000021#include "llvm/IR/LegacyPassNameParser.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Verifier.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000024#include "llvm/Support/Debug.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000025#include "llvm/Support/FileSystem.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000026#include "llvm/Support/ManagedStatic.h"
27#include "llvm/Support/PluginLoader.h"
28#include "llvm/Support/PrettyStackTrace.h"
29#include "llvm/Support/ToolOutputFile.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000030#include <algorithm>
Marshall Clowe9110d72017-02-16 14:37:03 +000031#include <random>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000032#include <vector>
Pawel Bylicaedb02102015-07-10 10:01:47 +000033
34namespace llvm {
Nadav Rotem78bda892012-02-26 08:35:53 +000035
36static cl::opt<unsigned> SeedCL("seed",
37 cl::desc("Seed used for randomness"), cl::init(0));
38static cl::opt<unsigned> SizeCL("size",
39 cl::desc("The estimated size of the generated function (# of instrs)"),
40 cl::init(100));
41static cl::opt<std::string>
42OutputFilename("o", cl::desc("Override output filename"),
43 cl::value_desc("filename"));
44
Mehdi Amini03b42e42016-04-14 21:59:01 +000045static LLVMContext Context;
46
Pawel Bylicaedb02102015-07-10 10:01:47 +000047namespace cl {
48template <> class parser<Type*> final : public basic_parser<Type*> {
49public:
50 parser(Option &O) : basic_parser(O) {}
51
52 // Parse options as IR types. Return true on error.
53 bool parse(Option &O, StringRef, StringRef Arg, Type *&Value) {
Pawel Bylicaedb02102015-07-10 10:01:47 +000054 if (Arg == "half") Value = Type::getHalfTy(Context);
55 else if (Arg == "fp128") Value = Type::getFP128Ty(Context);
56 else if (Arg == "x86_fp80") Value = Type::getX86_FP80Ty(Context);
57 else if (Arg == "ppc_fp128") Value = Type::getPPC_FP128Ty(Context);
58 else if (Arg == "x86_mmx") Value = Type::getX86_MMXTy(Context);
59 else if (Arg.startswith("i")) {
60 unsigned N = 0;
61 Arg.drop_front().getAsInteger(10, N);
62 if (N > 0)
63 Value = Type::getIntNTy(Context, N);
64 }
65
66 if (!Value)
67 return O.error("Invalid IR scalar type: '" + Arg + "'!");
68 return false;
69 }
70
Mehdi Aminie11b7452016-10-01 03:43:20 +000071 StringRef getValueName() const override { return "IR scalar type"; }
Pawel Bylicaedb02102015-07-10 10:01:47 +000072};
73}
74
75
76static cl::list<Type*> AdditionalScalarTypes("types", cl::CommaSeparated,
77 cl::desc("Additional IR scalar types "
78 "(always includes i1, i8, i16, i32, i64, float and double)"));
Hal Finkelc9474122012-02-27 23:59:33 +000079
Juergen Ributzka05c5a932013-11-19 03:08:35 +000080namespace {
Nadav Rotem78bda892012-02-26 08:35:53 +000081/// A utility class to provide a pseudo-random number generator which is
82/// the same across all platforms. This is somewhat close to the libc
83/// implementation. Note: This is not a cryptographically secure pseudorandom
84/// number generator.
85class Random {
86public:
87 /// C'tor
88 Random(unsigned _seed):Seed(_seed) {}
Dylan Noblesmith68f310d2012-04-10 22:44:51 +000089
90 /// Return a random integer, up to a
91 /// maximum of 2**19 - 1.
92 uint32_t Rand() {
93 uint32_t Val = Seed + 0x000b07a1;
Nadav Rotem78bda892012-02-26 08:35:53 +000094 Seed = (Val * 0x3c7c0ac1);
95 // Only lowest 19 bits are random-ish.
96 return Seed & 0x7ffff;
97 }
98
Dylan Noblesmith68f310d2012-04-10 22:44:51 +000099 /// Return a random 64 bit integer.
100 uint64_t Rand64() {
Simon Pilgrim3d116182017-06-26 13:17:36 +0000101 uint64_t Val = Rand() & 0xffff;
102 Val |= uint64_t(Rand() & 0xffff) << 16;
103 Val |= uint64_t(Rand() & 0xffff) << 32;
104 Val |= uint64_t(Rand() & 0xffff) << 48;
105 return Val;
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000106 }
Nadav Rotem0fb74082012-06-21 08:58:15 +0000107
108 /// Rand operator for STL algorithms.
109 ptrdiff_t operator()(ptrdiff_t y) {
110 return Rand64() % y;
111 }
112
Marshall Clowe9110d72017-02-16 14:37:03 +0000113 /// Make this like a C++11 random device
114 typedef uint32_t result_type;
Marshall Clowe9110d72017-02-16 14:37:03 +0000115 static constexpr result_type min() { return 0; }
116 static constexpr result_type max() { return 0x7ffff; }
Simon Pilgrim1158fe92017-06-26 10:16:34 +0000117 uint32_t operator()() {
118 uint32_t Val = Rand();
119 assert(Val <= max() && "Random value out of range");
120 return Val;
121 }
122
Nadav Rotem78bda892012-02-26 08:35:53 +0000123private:
124 unsigned Seed;
125};
126
127/// Generate an empty function with a default argument list.
128Function *GenEmptyFunction(Module *M) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000129 // Define a few arguments
130 LLVMContext &Context = M->getContext();
Pawel Bylica23663472015-06-24 11:49:44 +0000131 Type* ArgsTy[] = {
132 Type::getInt8PtrTy(Context),
133 Type::getInt32PtrTy(Context),
134 Type::getInt64PtrTy(Context),
135 Type::getInt32Ty(Context),
136 Type::getInt64Ty(Context),
137 Type::getInt8Ty(Context)
138 };
Nadav Rotem78bda892012-02-26 08:35:53 +0000139
Pawel Bylica23663472015-06-24 11:49:44 +0000140 auto *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, false);
Nadav Rotem78bda892012-02-26 08:35:53 +0000141 // Pick a unique name to describe the input parameters
Pawel Bylica23663472015-06-24 11:49:44 +0000142 Twine Name = "autogen_SD" + Twine{SeedCL};
143 auto *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage, Name, M);
Nadav Rotem78bda892012-02-26 08:35:53 +0000144 Func->setCallingConv(CallingConv::C);
145 return Func;
146}
147
148/// A base class, implementing utilities needed for
149/// modifying and adding new random instructions.
150struct Modifier {
151 /// Used to store the randomly generated values.
152 typedef std::vector<Value*> PieceTable;
153
154public:
155 /// C'tor
Nadav Rotemdc497b62012-02-26 08:59:25 +0000156 Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
Daniel Dunbarbeb34252012-02-29 00:20:33 +0000157 BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {}
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000158
159 /// virtual D'tor to silence warnings.
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000160 virtual ~Modifier() {}
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000161
Nadav Rotem78bda892012-02-26 08:35:53 +0000162 /// Add a new instruction.
163 virtual void Act() = 0;
164 /// Add N new instructions,
165 virtual void ActN(unsigned n) {
166 for (unsigned i=0; i<n; ++i)
167 Act();
168 }
169
170protected:
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000171 /// Return a random integer.
172 uint32_t getRandom() {
173 return Ran->Rand();
174 }
175
Nadav Rotem78bda892012-02-26 08:35:53 +0000176 /// Return a random value from the list of known values.
177 Value *getRandomVal() {
178 assert(PT->size());
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000179 return PT->at(getRandom() % PT->size());
Nadav Rotem78bda892012-02-26 08:35:53 +0000180 }
181
Nadav Roteme4972dd2012-02-26 13:56:18 +0000182 Constant *getRandomConstant(Type *Tp) {
183 if (Tp->isIntegerTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000184 if (getRandom() & 1)
Nadav Roteme4972dd2012-02-26 13:56:18 +0000185 return ConstantInt::getAllOnesValue(Tp);
186 return ConstantInt::getNullValue(Tp);
187 } else if (Tp->isFloatingPointTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000188 if (getRandom() & 1)
Nadav Roteme4972dd2012-02-26 13:56:18 +0000189 return ConstantFP::getAllOnesValue(Tp);
190 return ConstantFP::getNullValue(Tp);
191 }
192 return UndefValue::get(Tp);
193 }
194
Nadav Rotem78bda892012-02-26 08:35:53 +0000195 /// Return a random value with a known type.
196 Value *getRandomValue(Type *Tp) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000197 unsigned index = getRandom();
Nadav Rotem78bda892012-02-26 08:35:53 +0000198 for (unsigned i=0; i<PT->size(); ++i) {
199 Value *V = PT->at((index + i) % PT->size());
200 if (V->getType() == Tp)
201 return V;
202 }
203
204 // If the requested type was not found, generate a constant value.
205 if (Tp->isIntegerTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000206 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000207 return ConstantInt::getAllOnesValue(Tp);
208 return ConstantInt::getNullValue(Tp);
209 } else if (Tp->isFloatingPointTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000210 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000211 return ConstantFP::getAllOnesValue(Tp);
212 return ConstantFP::getNullValue(Tp);
Nadav Roteme4972dd2012-02-26 13:56:18 +0000213 } else if (Tp->isVectorTy()) {
214 VectorType *VTp = cast<VectorType>(Tp);
215
216 std::vector<Constant*> TempValues;
217 TempValues.reserve(VTp->getNumElements());
218 for (unsigned i = 0; i < VTp->getNumElements(); ++i)
219 TempValues.push_back(getRandomConstant(VTp->getScalarType()));
220
221 ArrayRef<Constant*> VectorValue(TempValues);
222 return ConstantVector::get(VectorValue);
Nadav Rotem78bda892012-02-26 08:35:53 +0000223 }
224
Nadav Rotem78bda892012-02-26 08:35:53 +0000225 return UndefValue::get(Tp);
226 }
227
228 /// Return a random value of any pointer type.
229 Value *getRandomPointerValue() {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000230 unsigned index = getRandom();
Nadav Rotem78bda892012-02-26 08:35:53 +0000231 for (unsigned i=0; i<PT->size(); ++i) {
232 Value *V = PT->at((index + i) % PT->size());
233 if (V->getType()->isPointerTy())
234 return V;
235 }
236 return UndefValue::get(pickPointerType());
237 }
238
239 /// Return a random value of any vector type.
240 Value *getRandomVectorValue() {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000241 unsigned index = getRandom();
Nadav Rotem78bda892012-02-26 08:35:53 +0000242 for (unsigned i=0; i<PT->size(); ++i) {
243 Value *V = PT->at((index + i) % PT->size());
244 if (V->getType()->isVectorTy())
245 return V;
246 }
247 return UndefValue::get(pickVectorType());
248 }
249
250 /// Pick a random type.
251 Type *pickType() {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000252 return (getRandom() & 1 ? pickVectorType() : pickScalarType());
Nadav Rotem78bda892012-02-26 08:35:53 +0000253 }
254
255 /// Pick a random pointer type.
256 Type *pickPointerType() {
257 Type *Ty = pickType();
258 return PointerType::get(Ty, 0);
259 }
260
261 /// Pick a random vector type.
262 Type *pickVectorType(unsigned len = (unsigned)-1) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000263 // Pick a random vector width in the range 2**0 to 2**4.
264 // by adding two randoms we are generating a normal-like distribution
265 // around 2**3.
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000266 unsigned width = 1<<((getRandom() % 3) + (getRandom() % 3));
Dylan Noblesmith2a592dc2012-04-10 22:44:49 +0000267 Type *Ty;
268
269 // Vectors of x86mmx are illegal; keep trying till we get something else.
270 do {
271 Ty = pickScalarType();
272 } while (Ty->isX86_MMXTy());
273
Nadav Rotem78bda892012-02-26 08:35:53 +0000274 if (len != (unsigned)-1)
275 width = len;
276 return VectorType::get(Ty, width);
277 }
278
279 /// Pick a random scalar type.
280 Type *pickScalarType() {
Pawel Bylicaedb02102015-07-10 10:01:47 +0000281 static std::vector<Type*> ScalarTypes;
282 if (ScalarTypes.empty()) {
283 ScalarTypes.assign({
284 Type::getInt1Ty(Context),
285 Type::getInt8Ty(Context),
286 Type::getInt16Ty(Context),
287 Type::getInt32Ty(Context),
288 Type::getInt64Ty(Context),
289 Type::getFloatTy(Context),
290 Type::getDoubleTy(Context)
291 });
292 ScalarTypes.insert(ScalarTypes.end(),
293 AdditionalScalarTypes.begin(), AdditionalScalarTypes.end());
294 }
Hal Finkelc9474122012-02-27 23:59:33 +0000295
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000296 return ScalarTypes[getRandom() % ScalarTypes.size()];
Nadav Rotem78bda892012-02-26 08:35:53 +0000297 }
298
299 /// Basic block to populate
300 BasicBlock *BB;
301 /// Value table
302 PieceTable *PT;
303 /// Random number generator
304 Random *Ran;
305 /// Context
306 LLVMContext &Context;
307};
308
309struct LoadModifier: public Modifier {
Daniel Dunbarbeb34252012-02-29 00:20:33 +0000310 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000311 void Act() override {
Alp Tokerf907b892013-12-05 05:44:44 +0000312 // Try to use predefined pointers. If non-exist, use undef pointer value;
Nadav Rotem78bda892012-02-26 08:35:53 +0000313 Value *Ptr = getRandomPointerValue();
314 Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
315 PT->push_back(V);
316 }
317};
318
319struct StoreModifier: public Modifier {
320 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000321 void Act() override {
Alp Tokerf907b892013-12-05 05:44:44 +0000322 // Try to use predefined pointers. If non-exist, use undef pointer value;
Nadav Rotem78bda892012-02-26 08:35:53 +0000323 Value *Ptr = getRandomPointerValue();
324 Type *Tp = Ptr->getType();
325 Value *Val = getRandomValue(Tp->getContainedType(0));
Nadav Rotem63ff91d2012-02-26 12:00:22 +0000326 Type *ValTy = Val->getType();
Nadav Rotem78bda892012-02-26 08:35:53 +0000327
328 // Do not store vectors of i1s because they are unsupported
Nadav Rotem115ec822012-02-26 12:34:17 +0000329 // by the codegen.
330 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000331 return;
332
333 new StoreInst(Val, Ptr, BB->getTerminator());
334 }
335};
336
337struct BinModifier: public Modifier {
338 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
339
Craig Toppere56917c2014-03-08 08:27:28 +0000340 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000341 Value *Val0 = getRandomVal();
342 Value *Val1 = getRandomValue(Val0->getType());
343
344 // Don't handle pointer types.
345 if (Val0->getType()->isPointerTy() ||
346 Val1->getType()->isPointerTy())
347 return;
348
349 // Don't handle i1 types.
350 if (Val0->getType()->getScalarSizeInBits() == 1)
351 return;
352
353
354 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
355 Instruction* Term = BB->getTerminator();
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000356 unsigned R = getRandom() % (isFloat ? 7 : 13);
Nadav Rotem78bda892012-02-26 08:35:53 +0000357 Instruction::BinaryOps Op;
358
359 switch (R) {
360 default: llvm_unreachable("Invalid BinOp");
361 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
362 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
363 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
364 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
365 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
366 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
367 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
368 case 7: {Op = Instruction::Shl; break; }
369 case 8: {Op = Instruction::LShr; break; }
370 case 9: {Op = Instruction::AShr; break; }
371 case 10:{Op = Instruction::And; break; }
372 case 11:{Op = Instruction::Or; break; }
373 case 12:{Op = Instruction::Xor; break; }
374 }
375
376 PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
377 }
378};
379
380/// Generate constant values.
381struct ConstModifier: public Modifier {
382 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000383 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000384 Type *Ty = pickType();
385
386 if (Ty->isVectorTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000387 switch (getRandom() % 2) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000388 case 0: if (Ty->getScalarType()->isIntegerTy())
389 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
Galina Kistanovab6448142017-06-10 18:26:19 +0000390 break;
Nadav Rotem78bda892012-02-26 08:35:53 +0000391 case 1: if (Ty->getScalarType()->isIntegerTy())
392 return PT->push_back(ConstantVector::getNullValue(Ty));
393 }
394 }
395
396 if (Ty->isFloatingPointTy()) {
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000397 // Generate 128 random bits, the size of the (currently)
398 // largest floating-point types.
399 uint64_t RandomBits[2];
400 for (unsigned i = 0; i < 2; ++i)
401 RandomBits[i] = Ran->Rand64();
402
403 APInt RandomInt(Ty->getPrimitiveSizeInBits(), makeArrayRef(RandomBits));
Tim Northover98d9b7e2013-01-22 10:18:26 +0000404 APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000405
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000406 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000407 return PT->push_back(ConstantFP::getNullValue(Ty));
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000408 return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
Nadav Rotem78bda892012-02-26 08:35:53 +0000409 }
410
411 if (Ty->isIntegerTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000412 switch (getRandom() % 7) {
David Blaikie30b2c6b2017-06-12 20:09:53 +0000413 case 0:
414 return PT->push_back(ConstantInt::get(
415 Ty, APInt::getAllOnesValue(Ty->getPrimitiveSizeInBits())));
416 case 1:
417 return PT->push_back(ConstantInt::get(
418 Ty, APInt::getNullValue(Ty->getPrimitiveSizeInBits())));
David Blaikie8f9621a2017-06-21 15:20:46 +0000419 case 2:
420 case 3:
421 case 4:
422 case 5:
David Blaikie30b2c6b2017-06-12 20:09:53 +0000423 case 6:
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000424 PT->push_back(ConstantInt::get(Ty, getRandom()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000425 }
426 }
Nadav Rotem78bda892012-02-26 08:35:53 +0000427 }
428};
429
430struct AllocaModifier: public Modifier {
431 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
432
Craig Toppere56917c2014-03-08 08:27:28 +0000433 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000434 Type *Tp = pickType();
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000435 const DataLayout &DL = BB->getModule()->getDataLayout();
436 PT->push_back(new AllocaInst(Tp, DL.getAllocaAddrSpace(),
437 "A", BB->getFirstNonPHI()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000438 }
439};
440
441struct ExtractElementModifier: public Modifier {
442 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
443 Modifier(BB, PT, R) {}
444
Craig Toppere56917c2014-03-08 08:27:28 +0000445 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000446 Value *Val0 = getRandomVectorValue();
447 Value *V = ExtractElementInst::Create(Val0,
448 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000449 getRandom() % cast<VectorType>(Val0->getType())->getNumElements()),
Nadav Rotem78bda892012-02-26 08:35:53 +0000450 "E", BB->getTerminator());
451 return PT->push_back(V);
452 }
453};
454
455struct ShuffModifier: public Modifier {
456 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000457 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000458
459 Value *Val0 = getRandomVectorValue();
460 Value *Val1 = getRandomValue(Val0->getType());
461
462 unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
463 std::vector<Constant*> Idxs;
464
465 Type *I32 = Type::getInt32Ty(BB->getContext());
466 for (unsigned i=0; i<Width; ++i) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000467 Constant *CI = ConstantInt::get(I32, getRandom() % (Width*2));
Nadav Rotem78bda892012-02-26 08:35:53 +0000468 // Pick some undef values.
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000469 if (!(getRandom() % 5))
Nadav Rotem78bda892012-02-26 08:35:53 +0000470 CI = UndefValue::get(I32);
471 Idxs.push_back(CI);
472 }
473
474 Constant *Mask = ConstantVector::get(Idxs);
475
476 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
477 BB->getTerminator());
478 PT->push_back(V);
479 }
480};
481
482struct InsertElementModifier: public Modifier {
483 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
484 Modifier(BB, PT, R) {}
485
Craig Toppere56917c2014-03-08 08:27:28 +0000486 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000487 Value *Val0 = getRandomVectorValue();
488 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
489
490 Value *V = InsertElementInst::Create(Val0, Val1,
491 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000492 getRandom() % cast<VectorType>(Val0->getType())->getNumElements()),
Nadav Rotem78bda892012-02-26 08:35:53 +0000493 "I", BB->getTerminator());
494 return PT->push_back(V);
495 }
496
497};
498
499struct CastModifier: public Modifier {
500 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000501 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000502
503 Value *V = getRandomVal();
504 Type *VTy = V->getType();
505 Type *DestTy = pickScalarType();
506
507 // Handle vector casts vectors.
508 if (VTy->isVectorTy()) {
509 VectorType *VecTy = cast<VectorType>(VTy);
510 DestTy = pickVectorType(VecTy->getNumElements());
511 }
512
Nadav Rotemaeacc172012-04-15 20:17:14 +0000513 // no need to cast.
Nadav Rotem78bda892012-02-26 08:35:53 +0000514 if (VTy == DestTy) return;
515
516 // Pointers:
517 if (VTy->isPointerTy()) {
518 if (!DestTy->isPointerTy())
519 DestTy = PointerType::get(DestTy, 0);
520 return PT->push_back(
521 new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
522 }
523
Nadav Rotemaeacc172012-04-15 20:17:14 +0000524 unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
525 unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
526
Nadav Rotem78bda892012-02-26 08:35:53 +0000527 // Generate lots of bitcasts.
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000528 if ((getRandom() & 1) && VSize == DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000529 return PT->push_back(
530 new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
531 }
532
533 // Both types are integers:
534 if (VTy->getScalarType()->isIntegerTy() &&
535 DestTy->getScalarType()->isIntegerTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000536 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000537 return PT->push_back(
538 new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
539 } else {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000540 assert(VSize < DestSize && "Different int types with the same size?");
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000541 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000542 return PT->push_back(
543 new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
544 return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
545 }
546 }
547
548 // Fp to int.
549 if (VTy->getScalarType()->isFloatingPointTy() &&
550 DestTy->getScalarType()->isIntegerTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000551 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000552 return PT->push_back(
553 new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
554 return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
555 }
556
557 // Int to fp.
558 if (VTy->getScalarType()->isIntegerTy() &&
559 DestTy->getScalarType()->isFloatingPointTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000560 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000561 return PT->push_back(
562 new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
563 return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
564
565 }
566
567 // Both floats.
568 if (VTy->getScalarType()->isFloatingPointTy() &&
569 DestTy->getScalarType()->isFloatingPointTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000570 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000571 return PT->push_back(
572 new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
Nadav Rotemaeacc172012-04-15 20:17:14 +0000573 } else if (VSize < DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000574 return PT->push_back(
575 new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
576 }
Nadav Rotemaeacc172012-04-15 20:17:14 +0000577 // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
578 // for which there is no defined conversion. So do nothing.
Nadav Rotem78bda892012-02-26 08:35:53 +0000579 }
580 }
581
582};
583
584struct SelectModifier: public Modifier {
585 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
586 Modifier(BB, PT, R) {}
587
Craig Toppere56917c2014-03-08 08:27:28 +0000588 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000589 // Try a bunch of different select configuration until a valid one is found.
590 Value *Val0 = getRandomVal();
591 Value *Val1 = getRandomValue(Val0->getType());
592
593 Type *CondTy = Type::getInt1Ty(Context);
594
595 // If the value type is a vector, and we allow vector select, then in 50%
596 // of the cases generate a vector select.
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000597 if (Val0->getType()->isVectorTy() && (getRandom() % 1)) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000598 unsigned NumElem = cast<VectorType>(Val0->getType())->getNumElements();
599 CondTy = VectorType::get(CondTy, NumElem);
600 }
601
602 Value *Cond = getRandomValue(CondTy);
603 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
604 return PT->push_back(V);
605 }
606};
607
608
609struct CmpModifier: public Modifier {
610 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000611 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000612
613 Value *Val0 = getRandomVal();
614 Value *Val1 = getRandomValue(Val0->getType());
615
616 if (Val0->getType()->isPointerTy()) return;
617 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
618
619 int op;
620 if (fp) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000621 op = getRandom() %
Nadav Rotem78bda892012-02-26 08:35:53 +0000622 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
623 CmpInst::FIRST_FCMP_PREDICATE;
624 } else {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000625 op = getRandom() %
Nadav Rotem78bda892012-02-26 08:35:53 +0000626 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
627 CmpInst::FIRST_ICMP_PREDICATE;
628 }
629
630 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
Craig Topper1c3f2832015-12-15 06:11:33 +0000631 (CmpInst::Predicate)op, Val0, Val1, "Cmp",
632 BB->getTerminator());
Nadav Rotem78bda892012-02-26 08:35:53 +0000633 return PT->push_back(V);
634 }
635};
636
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000637} // end anonymous namespace
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000638
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000639static void FillFunction(Function *F, Random &R) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000640 // Create a legal entry block.
641 BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
642 ReturnInst::Create(F->getContext(), BB);
643
644 // Create the value table.
645 Modifier::PieceTable PT;
Nadav Rotem78bda892012-02-26 08:35:53 +0000646
647 // Consider arguments as legal values.
Pawel Bylica23663472015-06-24 11:49:44 +0000648 for (auto &arg : F->args())
649 PT.push_back(&arg);
Nadav Rotem78bda892012-02-26 08:35:53 +0000650
651 // List of modifiers which add new random instructions.
Pawel Bylica23663472015-06-24 11:49:44 +0000652 std::vector<std::unique_ptr<Modifier>> Modifiers;
653 Modifiers.emplace_back(new LoadModifier(BB, &PT, &R));
654 Modifiers.emplace_back(new StoreModifier(BB, &PT, &R));
655 auto SM = Modifiers.back().get();
656 Modifiers.emplace_back(new ExtractElementModifier(BB, &PT, &R));
657 Modifiers.emplace_back(new ShuffModifier(BB, &PT, &R));
658 Modifiers.emplace_back(new InsertElementModifier(BB, &PT, &R));
659 Modifiers.emplace_back(new BinModifier(BB, &PT, &R));
660 Modifiers.emplace_back(new CastModifier(BB, &PT, &R));
661 Modifiers.emplace_back(new SelectModifier(BB, &PT, &R));
662 Modifiers.emplace_back(new CmpModifier(BB, &PT, &R));
Nadav Rotem78bda892012-02-26 08:35:53 +0000663
664 // Generate the random instructions
Pawel Bylica23663472015-06-24 11:49:44 +0000665 AllocaModifier{BB, &PT, &R}.ActN(5); // Throw in a few allocas
666 ConstModifier{BB, &PT, &R}.ActN(40); // Throw in a few constants
Nadav Rotem78bda892012-02-26 08:35:53 +0000667
Pawel Bylica23663472015-06-24 11:49:44 +0000668 for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
669 for (auto &Mod : Modifiers)
670 Mod->Act();
Nadav Rotem78bda892012-02-26 08:35:53 +0000671
672 SM->ActN(5); // Throw in a few stores.
673}
674
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000675static void IntroduceControlFlow(Function *F, Random &R) {
Nadav Rotem0fb74082012-06-21 08:58:15 +0000676 std::vector<Instruction*> BoolInst;
Pawel Bylica23663472015-06-24 11:49:44 +0000677 for (auto &Instr : F->front()) {
678 if (Instr.getType() == IntegerType::getInt1Ty(F->getContext()))
679 BoolInst.push_back(&Instr);
Nadav Rotem78bda892012-02-26 08:35:53 +0000680 }
681
Marshall Clowe9110d72017-02-16 14:37:03 +0000682 std::shuffle(BoolInst.begin(), BoolInst.end(), R);
Nadav Rotem0fb74082012-06-21 08:58:15 +0000683
Pawel Bylica23663472015-06-24 11:49:44 +0000684 for (auto *Instr : BoolInst) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000685 BasicBlock *Curr = Instr->getParent();
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000686 BasicBlock::iterator Loc = Instr->getIterator();
Nadav Rotem78bda892012-02-26 08:35:53 +0000687 BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
688 Instr->moveBefore(Curr->getTerminator());
689 if (Curr != &F->getEntryBlock()) {
690 BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
691 Curr->getTerminator()->eraseFromParent();
692 }
693 }
694}
695
Pawel Bylicaedb02102015-07-10 10:01:47 +0000696}
697
Nadav Rotem78bda892012-02-26 08:35:53 +0000698int main(int argc, char **argv) {
Pawel Bylicaedb02102015-07-10 10:01:47 +0000699 using namespace llvm;
700
Nadav Rotem78bda892012-02-26 08:35:53 +0000701 // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
Pawel Bylica4dd430f2015-07-13 11:25:56 +0000702 PrettyStackTraceProgram X(argc, argv);
Nadav Rotem78bda892012-02-26 08:35:53 +0000703 cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
704 llvm_shutdown_obj Y;
705
Mehdi Amini03b42e42016-04-14 21:59:01 +0000706 auto M = make_unique<Module>("/tmp/autogen.bc", Context);
Nadav Rotem78bda892012-02-26 08:35:53 +0000707 Function *F = GenEmptyFunction(M.get());
Nadav Rotem0fb74082012-06-21 08:58:15 +0000708
709 // Pick an initial seed value
710 Random R(SeedCL);
711 // Generate lots of random instructions inside a single basic block.
712 FillFunction(F, R);
713 // Break the basic block into many loops.
714 IntroduceControlFlow(F, R);
Nadav Rotem78bda892012-02-26 08:35:53 +0000715
716 // Figure out what stream we are supposed to write to...
Ahmed Charles56440fd2014-03-06 05:51:42 +0000717 std::unique_ptr<tool_output_file> Out;
Nadav Rotem78bda892012-02-26 08:35:53 +0000718 // Default to standard output.
719 if (OutputFilename.empty())
720 OutputFilename = "-";
721
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000722 std::error_code EC;
723 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
724 if (EC) {
725 errs() << EC.message() << '\n';
Nadav Rotem78bda892012-02-26 08:35:53 +0000726 return 1;
727 }
728
Chandler Carruth30d69c22015-02-13 10:01:29 +0000729 legacy::PassManager Passes;
Nadav Rotem78bda892012-02-26 08:35:53 +0000730 Passes.add(createVerifierPass());
Chandler Carruth3bdf0432014-01-12 11:39:04 +0000731 Passes.add(createPrintModulePass(Out->os()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000732 Passes.run(*M.get());
Nadav Rotem78bda892012-02-26 08:35:53 +0000733 Out->keep();
734
735 return 0;
736}