blob: 64624d70a2cf866bc419cdb35292b78591458633 [file] [log] [blame]
Eugene Zelenkofa6434b2017-08-31 21:56:16 +00001//===- llvm-stress.cpp - Generate random LL files to stress-test LLVM -----===//
Nadav Rotem78bda892012-02-26 08:35:53 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Nadav Rotem78bda892012-02-26 08:35:53 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This program is a utility that generates random .ll files to stress-test
10// different components in LLVM.
11//
12//===----------------------------------------------------------------------===//
Ahmed Charles56440fd2014-03-06 05:51:42 +000013
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000014#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/CallingConv.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalValue.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000027#include "llvm/IR/IRPrintingPasses.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000028#include "llvm/IR/InstrTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instruction.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000030#include "llvm/IR/Instructions.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000031#include "llvm/IR/LLVMContext.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000032#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Module.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000034#include "llvm/IR/Type.h"
35#include "llvm/IR/Value.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Verifier.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000037#include "llvm/Support/Casting.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/ErrorHandling.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000040#include "llvm/Support/FileSystem.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000041#include "llvm/Support/ManagedStatic.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000042#include "llvm/Support/PrettyStackTrace.h"
43#include "llvm/Support/ToolOutputFile.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000044#include "llvm/Support/raw_ostream.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000045#include <algorithm>
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000046#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <memory>
50#include <string>
51#include <system_error>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000052#include <vector>
Pawel Bylicaedb02102015-07-10 10:01:47 +000053
54namespace llvm {
Nadav Rotem78bda892012-02-26 08:35:53 +000055
56static cl::opt<unsigned> SeedCL("seed",
57 cl::desc("Seed used for randomness"), cl::init(0));
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000058
Nadav Rotem78bda892012-02-26 08:35:53 +000059static cl::opt<unsigned> SizeCL("size",
60 cl::desc("The estimated size of the generated function (# of instrs)"),
61 cl::init(100));
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000062
Nadav Rotem78bda892012-02-26 08:35:53 +000063static cl::opt<std::string>
64OutputFilename("o", cl::desc("Override output filename"),
65 cl::value_desc("filename"));
66
Mehdi Amini03b42e42016-04-14 21:59:01 +000067static LLVMContext Context;
68
Pawel Bylicaedb02102015-07-10 10:01:47 +000069namespace cl {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000070
Pawel Bylicaedb02102015-07-10 10:01:47 +000071template <> class parser<Type*> final : public basic_parser<Type*> {
72public:
73 parser(Option &O) : basic_parser(O) {}
74
75 // Parse options as IR types. Return true on error.
76 bool parse(Option &O, StringRef, StringRef Arg, Type *&Value) {
Pawel Bylicaedb02102015-07-10 10:01:47 +000077 if (Arg == "half") Value = Type::getHalfTy(Context);
78 else if (Arg == "fp128") Value = Type::getFP128Ty(Context);
79 else if (Arg == "x86_fp80") Value = Type::getX86_FP80Ty(Context);
80 else if (Arg == "ppc_fp128") Value = Type::getPPC_FP128Ty(Context);
81 else if (Arg == "x86_mmx") Value = Type::getX86_MMXTy(Context);
82 else if (Arg.startswith("i")) {
83 unsigned N = 0;
84 Arg.drop_front().getAsInteger(10, N);
85 if (N > 0)
86 Value = Type::getIntNTy(Context, N);
87 }
88
89 if (!Value)
90 return O.error("Invalid IR scalar type: '" + Arg + "'!");
91 return false;
92 }
93
Mehdi Aminie11b7452016-10-01 03:43:20 +000094 StringRef getValueName() const override { return "IR scalar type"; }
Pawel Bylicaedb02102015-07-10 10:01:47 +000095};
Pawel Bylicaedb02102015-07-10 10:01:47 +000096
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000097} // end namespace cl
Pawel Bylicaedb02102015-07-10 10:01:47 +000098
99static cl::list<Type*> AdditionalScalarTypes("types", cl::CommaSeparated,
100 cl::desc("Additional IR scalar types "
101 "(always includes i1, i8, i16, i32, i64, float and double)"));
Hal Finkelc9474122012-02-27 23:59:33 +0000102
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000103namespace {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000104
Nadav Rotem78bda892012-02-26 08:35:53 +0000105/// A utility class to provide a pseudo-random number generator which is
106/// the same across all platforms. This is somewhat close to the libc
107/// implementation. Note: This is not a cryptographically secure pseudorandom
108/// number generator.
109class Random {
110public:
111 /// C'tor
112 Random(unsigned _seed):Seed(_seed) {}
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000113
114 /// Return a random integer, up to a
115 /// maximum of 2**19 - 1.
116 uint32_t Rand() {
117 uint32_t Val = Seed + 0x000b07a1;
Nadav Rotem78bda892012-02-26 08:35:53 +0000118 Seed = (Val * 0x3c7c0ac1);
119 // Only lowest 19 bits are random-ish.
120 return Seed & 0x7ffff;
121 }
122
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000123 /// Return a random 64 bit integer.
124 uint64_t Rand64() {
Simon Pilgrim3d116182017-06-26 13:17:36 +0000125 uint64_t Val = Rand() & 0xffff;
126 Val |= uint64_t(Rand() & 0xffff) << 16;
127 Val |= uint64_t(Rand() & 0xffff) << 32;
128 Val |= uint64_t(Rand() & 0xffff) << 48;
129 return Val;
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000130 }
Nadav Rotem0fb74082012-06-21 08:58:15 +0000131
132 /// Rand operator for STL algorithms.
133 ptrdiff_t operator()(ptrdiff_t y) {
134 return Rand64() % y;
135 }
136
Marshall Clowe9110d72017-02-16 14:37:03 +0000137 /// Make this like a C++11 random device
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000138 using result_type = uint32_t ;
139
Marshall Clowe9110d72017-02-16 14:37:03 +0000140 static constexpr result_type min() { return 0; }
141 static constexpr result_type max() { return 0x7ffff; }
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000142
Simon Pilgrim1158fe92017-06-26 10:16:34 +0000143 uint32_t operator()() {
144 uint32_t Val = Rand();
145 assert(Val <= max() && "Random value out of range");
146 return Val;
147 }
148
Nadav Rotem78bda892012-02-26 08:35:53 +0000149private:
150 unsigned Seed;
151};
152
153/// Generate an empty function with a default argument list.
154Function *GenEmptyFunction(Module *M) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000155 // Define a few arguments
156 LLVMContext &Context = M->getContext();
Pawel Bylica23663472015-06-24 11:49:44 +0000157 Type* ArgsTy[] = {
158 Type::getInt8PtrTy(Context),
159 Type::getInt32PtrTy(Context),
160 Type::getInt64PtrTy(Context),
161 Type::getInt32Ty(Context),
162 Type::getInt64Ty(Context),
163 Type::getInt8Ty(Context)
164 };
Nadav Rotem78bda892012-02-26 08:35:53 +0000165
Pawel Bylica23663472015-06-24 11:49:44 +0000166 auto *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, false);
Nadav Rotem78bda892012-02-26 08:35:53 +0000167 // Pick a unique name to describe the input parameters
Pawel Bylica23663472015-06-24 11:49:44 +0000168 Twine Name = "autogen_SD" + Twine{SeedCL};
169 auto *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage, Name, M);
Nadav Rotem78bda892012-02-26 08:35:53 +0000170 Func->setCallingConv(CallingConv::C);
171 return Func;
172}
173
174/// A base class, implementing utilities needed for
175/// modifying and adding new random instructions.
176struct Modifier {
177 /// Used to store the randomly generated values.
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000178 using PieceTable = std::vector<Value *>;
Nadav Rotem78bda892012-02-26 08:35:53 +0000179
180public:
181 /// C'tor
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000182 Modifier(BasicBlock *Block, PieceTable *PT, Random *R)
183 : BB(Block), PT(PT), Ran(R), Context(BB->getContext()) {}
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000184
185 /// virtual D'tor to silence warnings.
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000186 virtual ~Modifier() = default;
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000187
Nadav Rotem78bda892012-02-26 08:35:53 +0000188 /// Add a new instruction.
189 virtual void Act() = 0;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000190
Nadav Rotem78bda892012-02-26 08:35:53 +0000191 /// Add N new instructions,
192 virtual void ActN(unsigned n) {
193 for (unsigned i=0; i<n; ++i)
194 Act();
195 }
196
197protected:
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000198 /// Return a random integer.
199 uint32_t getRandom() {
200 return Ran->Rand();
201 }
202
Nadav Rotem78bda892012-02-26 08:35:53 +0000203 /// Return a random value from the list of known values.
204 Value *getRandomVal() {
205 assert(PT->size());
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000206 return PT->at(getRandom() % PT->size());
Nadav Rotem78bda892012-02-26 08:35:53 +0000207 }
208
Nadav Roteme4972dd2012-02-26 13:56:18 +0000209 Constant *getRandomConstant(Type *Tp) {
210 if (Tp->isIntegerTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000211 if (getRandom() & 1)
Nadav Roteme4972dd2012-02-26 13:56:18 +0000212 return ConstantInt::getAllOnesValue(Tp);
213 return ConstantInt::getNullValue(Tp);
214 } else if (Tp->isFloatingPointTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000215 if (getRandom() & 1)
Nadav Roteme4972dd2012-02-26 13:56:18 +0000216 return ConstantFP::getAllOnesValue(Tp);
217 return ConstantFP::getNullValue(Tp);
218 }
219 return UndefValue::get(Tp);
220 }
221
Nadav Rotem78bda892012-02-26 08:35:53 +0000222 /// Return a random value with a known type.
223 Value *getRandomValue(Type *Tp) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000224 unsigned index = getRandom();
Nadav Rotem78bda892012-02-26 08:35:53 +0000225 for (unsigned i=0; i<PT->size(); ++i) {
226 Value *V = PT->at((index + i) % PT->size());
227 if (V->getType() == Tp)
228 return V;
229 }
230
231 // If the requested type was not found, generate a constant value.
232 if (Tp->isIntegerTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000233 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000234 return ConstantInt::getAllOnesValue(Tp);
235 return ConstantInt::getNullValue(Tp);
236 } else if (Tp->isFloatingPointTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000237 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000238 return ConstantFP::getAllOnesValue(Tp);
239 return ConstantFP::getNullValue(Tp);
Nadav Roteme4972dd2012-02-26 13:56:18 +0000240 } else if (Tp->isVectorTy()) {
241 VectorType *VTp = cast<VectorType>(Tp);
242
243 std::vector<Constant*> TempValues;
244 TempValues.reserve(VTp->getNumElements());
245 for (unsigned i = 0; i < VTp->getNumElements(); ++i)
246 TempValues.push_back(getRandomConstant(VTp->getScalarType()));
247
248 ArrayRef<Constant*> VectorValue(TempValues);
249 return ConstantVector::get(VectorValue);
Nadav Rotem78bda892012-02-26 08:35:53 +0000250 }
251
Nadav Rotem78bda892012-02-26 08:35:53 +0000252 return UndefValue::get(Tp);
253 }
254
255 /// Return a random value of any pointer type.
256 Value *getRandomPointerValue() {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000257 unsigned index = getRandom();
Nadav Rotem78bda892012-02-26 08:35:53 +0000258 for (unsigned i=0; i<PT->size(); ++i) {
259 Value *V = PT->at((index + i) % PT->size());
260 if (V->getType()->isPointerTy())
261 return V;
262 }
263 return UndefValue::get(pickPointerType());
264 }
265
266 /// Return a random value of any vector type.
267 Value *getRandomVectorValue() {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000268 unsigned index = getRandom();
Nadav Rotem78bda892012-02-26 08:35:53 +0000269 for (unsigned i=0; i<PT->size(); ++i) {
270 Value *V = PT->at((index + i) % PT->size());
271 if (V->getType()->isVectorTy())
272 return V;
273 }
274 return UndefValue::get(pickVectorType());
275 }
276
277 /// Pick a random type.
278 Type *pickType() {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000279 return (getRandom() & 1 ? pickVectorType() : pickScalarType());
Nadav Rotem78bda892012-02-26 08:35:53 +0000280 }
281
282 /// Pick a random pointer type.
283 Type *pickPointerType() {
284 Type *Ty = pickType();
285 return PointerType::get(Ty, 0);
286 }
287
288 /// Pick a random vector type.
289 Type *pickVectorType(unsigned len = (unsigned)-1) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000290 // Pick a random vector width in the range 2**0 to 2**4.
291 // by adding two randoms we are generating a normal-like distribution
292 // around 2**3.
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000293 unsigned width = 1<<((getRandom() % 3) + (getRandom() % 3));
Dylan Noblesmith2a592dc2012-04-10 22:44:49 +0000294 Type *Ty;
295
296 // Vectors of x86mmx are illegal; keep trying till we get something else.
297 do {
298 Ty = pickScalarType();
299 } while (Ty->isX86_MMXTy());
300
Nadav Rotem78bda892012-02-26 08:35:53 +0000301 if (len != (unsigned)-1)
302 width = len;
303 return VectorType::get(Ty, width);
304 }
305
306 /// Pick a random scalar type.
307 Type *pickScalarType() {
Pawel Bylicaedb02102015-07-10 10:01:47 +0000308 static std::vector<Type*> ScalarTypes;
309 if (ScalarTypes.empty()) {
310 ScalarTypes.assign({
311 Type::getInt1Ty(Context),
312 Type::getInt8Ty(Context),
313 Type::getInt16Ty(Context),
314 Type::getInt32Ty(Context),
315 Type::getInt64Ty(Context),
316 Type::getFloatTy(Context),
317 Type::getDoubleTy(Context)
318 });
319 ScalarTypes.insert(ScalarTypes.end(),
320 AdditionalScalarTypes.begin(), AdditionalScalarTypes.end());
321 }
Hal Finkelc9474122012-02-27 23:59:33 +0000322
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000323 return ScalarTypes[getRandom() % ScalarTypes.size()];
Nadav Rotem78bda892012-02-26 08:35:53 +0000324 }
325
326 /// Basic block to populate
327 BasicBlock *BB;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000328
Nadav Rotem78bda892012-02-26 08:35:53 +0000329 /// Value table
330 PieceTable *PT;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000331
Nadav Rotem78bda892012-02-26 08:35:53 +0000332 /// Random number generator
333 Random *Ran;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000334
Nadav Rotem78bda892012-02-26 08:35:53 +0000335 /// Context
336 LLVMContext &Context;
337};
338
339struct LoadModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000340 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R)
341 : Modifier(BB, PT, R) {}
342
Craig Toppere56917c2014-03-08 08:27:28 +0000343 void Act() override {
Alp Tokerf907b892013-12-05 05:44:44 +0000344 // Try to use predefined pointers. If non-exist, use undef pointer value;
Nadav Rotem78bda892012-02-26 08:35:53 +0000345 Value *Ptr = getRandomPointerValue();
346 Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
347 PT->push_back(V);
348 }
349};
350
351struct StoreModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000352 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R)
353 : Modifier(BB, PT, R) {}
354
Craig Toppere56917c2014-03-08 08:27:28 +0000355 void Act() override {
Alp Tokerf907b892013-12-05 05:44:44 +0000356 // Try to use predefined pointers. If non-exist, use undef pointer value;
Nadav Rotem78bda892012-02-26 08:35:53 +0000357 Value *Ptr = getRandomPointerValue();
James Y Knightca22fa32019-01-10 16:43:26 +0000358 PointerType *Tp = cast<PointerType>(Ptr->getType());
James Y Knight62df5ee2019-01-10 16:07:20 +0000359 Value *Val = getRandomValue(Tp->getElementType());
Nadav Rotem63ff91d2012-02-26 12:00:22 +0000360 Type *ValTy = Val->getType();
Nadav Rotem78bda892012-02-26 08:35:53 +0000361
362 // Do not store vectors of i1s because they are unsupported
Nadav Rotem115ec822012-02-26 12:34:17 +0000363 // by the codegen.
364 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000365 return;
366
367 new StoreInst(Val, Ptr, BB->getTerminator());
368 }
369};
370
371struct BinModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000372 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R)
373 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000374
Craig Toppere56917c2014-03-08 08:27:28 +0000375 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000376 Value *Val0 = getRandomVal();
377 Value *Val1 = getRandomValue(Val0->getType());
378
379 // Don't handle pointer types.
380 if (Val0->getType()->isPointerTy() ||
381 Val1->getType()->isPointerTy())
382 return;
383
384 // Don't handle i1 types.
385 if (Val0->getType()->getScalarSizeInBits() == 1)
386 return;
387
Nadav Rotem78bda892012-02-26 08:35:53 +0000388 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
389 Instruction* Term = BB->getTerminator();
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000390 unsigned R = getRandom() % (isFloat ? 7 : 13);
Nadav Rotem78bda892012-02-26 08:35:53 +0000391 Instruction::BinaryOps Op;
392
393 switch (R) {
394 default: llvm_unreachable("Invalid BinOp");
395 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
396 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
397 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
398 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
399 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
400 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
401 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
402 case 7: {Op = Instruction::Shl; break; }
403 case 8: {Op = Instruction::LShr; break; }
404 case 9: {Op = Instruction::AShr; break; }
405 case 10:{Op = Instruction::And; break; }
406 case 11:{Op = Instruction::Or; break; }
407 case 12:{Op = Instruction::Xor; break; }
408 }
409
410 PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
411 }
412};
413
414/// Generate constant values.
415struct ConstModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000416 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R)
417 : Modifier(BB, PT, R) {}
418
Craig Toppere56917c2014-03-08 08:27:28 +0000419 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000420 Type *Ty = pickType();
421
422 if (Ty->isVectorTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000423 switch (getRandom() % 2) {
Craig Topper95d23472017-07-09 07:04:00 +0000424 case 0: if (Ty->isIntOrIntVectorTy())
Nadav Rotem78bda892012-02-26 08:35:53 +0000425 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
Galina Kistanovab6448142017-06-10 18:26:19 +0000426 break;
Craig Topper95d23472017-07-09 07:04:00 +0000427 case 1: if (Ty->isIntOrIntVectorTy())
Nadav Rotem78bda892012-02-26 08:35:53 +0000428 return PT->push_back(ConstantVector::getNullValue(Ty));
429 }
430 }
431
432 if (Ty->isFloatingPointTy()) {
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000433 // Generate 128 random bits, the size of the (currently)
434 // largest floating-point types.
435 uint64_t RandomBits[2];
436 for (unsigned i = 0; i < 2; ++i)
437 RandomBits[i] = Ran->Rand64();
438
439 APInt RandomInt(Ty->getPrimitiveSizeInBits(), makeArrayRef(RandomBits));
Tim Northover98d9b7e2013-01-22 10:18:26 +0000440 APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000441
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000442 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000443 return PT->push_back(ConstantFP::getNullValue(Ty));
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000444 return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
Nadav Rotem78bda892012-02-26 08:35:53 +0000445 }
446
447 if (Ty->isIntegerTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000448 switch (getRandom() % 7) {
David Blaikie30b2c6b2017-06-12 20:09:53 +0000449 case 0:
450 return PT->push_back(ConstantInt::get(
451 Ty, APInt::getAllOnesValue(Ty->getPrimitiveSizeInBits())));
452 case 1:
453 return PT->push_back(ConstantInt::get(
454 Ty, APInt::getNullValue(Ty->getPrimitiveSizeInBits())));
David Blaikie8f9621a2017-06-21 15:20:46 +0000455 case 2:
456 case 3:
457 case 4:
458 case 5:
David Blaikie30b2c6b2017-06-12 20:09:53 +0000459 case 6:
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000460 PT->push_back(ConstantInt::get(Ty, getRandom()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000461 }
462 }
Nadav Rotem78bda892012-02-26 08:35:53 +0000463 }
464};
465
466struct AllocaModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000467 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R)
468 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000469
Craig Toppere56917c2014-03-08 08:27:28 +0000470 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000471 Type *Tp = pickType();
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000472 const DataLayout &DL = BB->getModule()->getDataLayout();
473 PT->push_back(new AllocaInst(Tp, DL.getAllocaAddrSpace(),
474 "A", BB->getFirstNonPHI()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000475 }
476};
477
478struct ExtractElementModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000479 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
480 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000481
Craig Toppere56917c2014-03-08 08:27:28 +0000482 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000483 Value *Val0 = getRandomVectorValue();
484 Value *V = ExtractElementInst::Create(Val0,
485 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000486 getRandom() % cast<VectorType>(Val0->getType())->getNumElements()),
Nadav Rotem78bda892012-02-26 08:35:53 +0000487 "E", BB->getTerminator());
488 return PT->push_back(V);
489 }
490};
491
492struct ShuffModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000493 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R)
494 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000495
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000496 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000497 Value *Val0 = getRandomVectorValue();
498 Value *Val1 = getRandomValue(Val0->getType());
499
500 unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
501 std::vector<Constant*> Idxs;
502
503 Type *I32 = Type::getInt32Ty(BB->getContext());
504 for (unsigned i=0; i<Width; ++i) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000505 Constant *CI = ConstantInt::get(I32, getRandom() % (Width*2));
Nadav Rotem78bda892012-02-26 08:35:53 +0000506 // Pick some undef values.
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000507 if (!(getRandom() % 5))
Nadav Rotem78bda892012-02-26 08:35:53 +0000508 CI = UndefValue::get(I32);
509 Idxs.push_back(CI);
510 }
511
512 Constant *Mask = ConstantVector::get(Idxs);
513
514 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
515 BB->getTerminator());
516 PT->push_back(V);
517 }
518};
519
520struct InsertElementModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000521 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
522 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000523
Craig Toppere56917c2014-03-08 08:27:28 +0000524 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000525 Value *Val0 = getRandomVectorValue();
526 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
527
528 Value *V = InsertElementInst::Create(Val0, Val1,
529 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000530 getRandom() % cast<VectorType>(Val0->getType())->getNumElements()),
Nadav Rotem78bda892012-02-26 08:35:53 +0000531 "I", BB->getTerminator());
532 return PT->push_back(V);
533 }
Nadav Rotem78bda892012-02-26 08:35:53 +0000534};
535
536struct CastModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000537 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R)
538 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000539
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000540 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000541 Value *V = getRandomVal();
542 Type *VTy = V->getType();
543 Type *DestTy = pickScalarType();
544
545 // Handle vector casts vectors.
546 if (VTy->isVectorTy()) {
547 VectorType *VecTy = cast<VectorType>(VTy);
548 DestTy = pickVectorType(VecTy->getNumElements());
549 }
550
Nadav Rotemaeacc172012-04-15 20:17:14 +0000551 // no need to cast.
Nadav Rotem78bda892012-02-26 08:35:53 +0000552 if (VTy == DestTy) return;
553
554 // Pointers:
555 if (VTy->isPointerTy()) {
556 if (!DestTy->isPointerTy())
557 DestTy = PointerType::get(DestTy, 0);
558 return PT->push_back(
559 new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
560 }
561
Nadav Rotemaeacc172012-04-15 20:17:14 +0000562 unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
563 unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
564
Nadav Rotem78bda892012-02-26 08:35:53 +0000565 // Generate lots of bitcasts.
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000566 if ((getRandom() & 1) && VSize == DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000567 return PT->push_back(
568 new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
569 }
570
571 // Both types are integers:
Craig Topper95d23472017-07-09 07:04:00 +0000572 if (VTy->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000573 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000574 return PT->push_back(
575 new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
576 } else {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000577 assert(VSize < DestSize && "Different int types with the same size?");
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000578 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000579 return PT->push_back(
580 new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
581 return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
582 }
583 }
584
585 // Fp to int.
Craig Topper95d23472017-07-09 07:04:00 +0000586 if (VTy->isFPOrFPVectorTy() && DestTy->isIntOrIntVectorTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000587 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000588 return PT->push_back(
589 new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
590 return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
591 }
592
593 // Int to fp.
Craig Topper95d23472017-07-09 07:04:00 +0000594 if (VTy->isIntOrIntVectorTy() && DestTy->isFPOrFPVectorTy()) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000595 if (getRandom() & 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000596 return PT->push_back(
597 new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
598 return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000599 }
600
601 // Both floats.
Craig Topper95d23472017-07-09 07:04:00 +0000602 if (VTy->isFPOrFPVectorTy() && DestTy->isFPOrFPVectorTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000603 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000604 return PT->push_back(
605 new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
Nadav Rotemaeacc172012-04-15 20:17:14 +0000606 } else if (VSize < DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000607 return PT->push_back(
608 new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
609 }
Nadav Rotemaeacc172012-04-15 20:17:14 +0000610 // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
611 // for which there is no defined conversion. So do nothing.
Nadav Rotem78bda892012-02-26 08:35:53 +0000612 }
613 }
Nadav Rotem78bda892012-02-26 08:35:53 +0000614};
615
616struct SelectModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000617 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R)
618 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000619
Craig Toppere56917c2014-03-08 08:27:28 +0000620 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000621 // Try a bunch of different select configuration until a valid one is found.
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000622 Value *Val0 = getRandomVal();
623 Value *Val1 = getRandomValue(Val0->getType());
Nadav Rotem78bda892012-02-26 08:35:53 +0000624
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000625 Type *CondTy = Type::getInt1Ty(Context);
Nadav Rotem78bda892012-02-26 08:35:53 +0000626
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000627 // If the value type is a vector, and we allow vector select, then in 50%
628 // of the cases generate a vector select.
629 if (Val0->getType()->isVectorTy() && (getRandom() % 1)) {
630 unsigned NumElem = cast<VectorType>(Val0->getType())->getNumElements();
631 CondTy = VectorType::get(CondTy, NumElem);
632 }
Nadav Rotem78bda892012-02-26 08:35:53 +0000633
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000634 Value *Cond = getRandomValue(CondTy);
635 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
636 return PT->push_back(V);
Nadav Rotem78bda892012-02-26 08:35:53 +0000637 }
638};
639
Nadav Rotem78bda892012-02-26 08:35:53 +0000640struct CmpModifier: public Modifier {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000641 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R)
642 : Modifier(BB, PT, R) {}
Nadav Rotem78bda892012-02-26 08:35:53 +0000643
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000644 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000645 Value *Val0 = getRandomVal();
646 Value *Val1 = getRandomValue(Val0->getType());
647
648 if (Val0->getType()->isPointerTy()) return;
649 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
650
651 int op;
652 if (fp) {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000653 op = getRandom() %
Nadav Rotem78bda892012-02-26 08:35:53 +0000654 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
655 CmpInst::FIRST_FCMP_PREDICATE;
656 } else {
Simon Pilgrime77df9b2017-06-26 15:41:36 +0000657 op = getRandom() %
Nadav Rotem78bda892012-02-26 08:35:53 +0000658 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
659 CmpInst::FIRST_ICMP_PREDICATE;
660 }
661
662 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
Craig Topper1c3f2832015-12-15 06:11:33 +0000663 (CmpInst::Predicate)op, Val0, Val1, "Cmp",
664 BB->getTerminator());
Nadav Rotem78bda892012-02-26 08:35:53 +0000665 return PT->push_back(V);
666 }
667};
668
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000669} // end anonymous namespace
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000670
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000671static void FillFunction(Function *F, Random &R) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000672 // Create a legal entry block.
673 BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
674 ReturnInst::Create(F->getContext(), BB);
675
676 // Create the value table.
677 Modifier::PieceTable PT;
Nadav Rotem78bda892012-02-26 08:35:53 +0000678
679 // Consider arguments as legal values.
Pawel Bylica23663472015-06-24 11:49:44 +0000680 for (auto &arg : F->args())
681 PT.push_back(&arg);
Nadav Rotem78bda892012-02-26 08:35:53 +0000682
683 // List of modifiers which add new random instructions.
Pawel Bylica23663472015-06-24 11:49:44 +0000684 std::vector<std::unique_ptr<Modifier>> Modifiers;
685 Modifiers.emplace_back(new LoadModifier(BB, &PT, &R));
686 Modifiers.emplace_back(new StoreModifier(BB, &PT, &R));
687 auto SM = Modifiers.back().get();
688 Modifiers.emplace_back(new ExtractElementModifier(BB, &PT, &R));
689 Modifiers.emplace_back(new ShuffModifier(BB, &PT, &R));
690 Modifiers.emplace_back(new InsertElementModifier(BB, &PT, &R));
691 Modifiers.emplace_back(new BinModifier(BB, &PT, &R));
692 Modifiers.emplace_back(new CastModifier(BB, &PT, &R));
693 Modifiers.emplace_back(new SelectModifier(BB, &PT, &R));
694 Modifiers.emplace_back(new CmpModifier(BB, &PT, &R));
Nadav Rotem78bda892012-02-26 08:35:53 +0000695
696 // Generate the random instructions
Pawel Bylica23663472015-06-24 11:49:44 +0000697 AllocaModifier{BB, &PT, &R}.ActN(5); // Throw in a few allocas
698 ConstModifier{BB, &PT, &R}.ActN(40); // Throw in a few constants
Nadav Rotem78bda892012-02-26 08:35:53 +0000699
Pawel Bylica23663472015-06-24 11:49:44 +0000700 for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
701 for (auto &Mod : Modifiers)
702 Mod->Act();
Nadav Rotem78bda892012-02-26 08:35:53 +0000703
704 SM->ActN(5); // Throw in a few stores.
705}
706
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000707static void IntroduceControlFlow(Function *F, Random &R) {
Nadav Rotem0fb74082012-06-21 08:58:15 +0000708 std::vector<Instruction*> BoolInst;
Pawel Bylica23663472015-06-24 11:49:44 +0000709 for (auto &Instr : F->front()) {
710 if (Instr.getType() == IntegerType::getInt1Ty(F->getContext()))
711 BoolInst.push_back(&Instr);
Nadav Rotem78bda892012-02-26 08:35:53 +0000712 }
713
Marshall Clowe9110d72017-02-16 14:37:03 +0000714 std::shuffle(BoolInst.begin(), BoolInst.end(), R);
Nadav Rotem0fb74082012-06-21 08:58:15 +0000715
Pawel Bylica23663472015-06-24 11:49:44 +0000716 for (auto *Instr : BoolInst) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000717 BasicBlock *Curr = Instr->getParent();
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000718 BasicBlock::iterator Loc = Instr->getIterator();
Nadav Rotem78bda892012-02-26 08:35:53 +0000719 BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
720 Instr->moveBefore(Curr->getTerminator());
721 if (Curr != &F->getEntryBlock()) {
722 BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
723 Curr->getTerminator()->eraseFromParent();
724 }
725 }
726}
727
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000728} // end namespace llvm
Pawel Bylicaedb02102015-07-10 10:01:47 +0000729
Nadav Rotem78bda892012-02-26 08:35:53 +0000730int main(int argc, char **argv) {
Pawel Bylicaedb02102015-07-10 10:01:47 +0000731 using namespace llvm;
732
Nadav Rotem78bda892012-02-26 08:35:53 +0000733 // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
Pawel Bylica4dd430f2015-07-13 11:25:56 +0000734 PrettyStackTraceProgram X(argc, argv);
Nadav Rotem78bda892012-02-26 08:35:53 +0000735 cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
736 llvm_shutdown_obj Y;
737
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000738 auto M = llvm::make_unique<Module>("/tmp/autogen.bc", Context);
Nadav Rotem78bda892012-02-26 08:35:53 +0000739 Function *F = GenEmptyFunction(M.get());
Nadav Rotem0fb74082012-06-21 08:58:15 +0000740
741 // Pick an initial seed value
742 Random R(SeedCL);
743 // Generate lots of random instructions inside a single basic block.
744 FillFunction(F, R);
745 // Break the basic block into many loops.
746 IntroduceControlFlow(F, R);
Nadav Rotem78bda892012-02-26 08:35:53 +0000747
748 // Figure out what stream we are supposed to write to...
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000749 std::unique_ptr<ToolOutputFile> Out;
Nadav Rotem78bda892012-02-26 08:35:53 +0000750 // Default to standard output.
751 if (OutputFilename.empty())
752 OutputFilename = "-";
753
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000754 std::error_code EC;
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000755 Out.reset(new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000756 if (EC) {
757 errs() << EC.message() << '\n';
Nadav Rotem78bda892012-02-26 08:35:53 +0000758 return 1;
759 }
760
Chandler Carruth30d69c22015-02-13 10:01:29 +0000761 legacy::PassManager Passes;
Nadav Rotem78bda892012-02-26 08:35:53 +0000762 Passes.add(createVerifierPass());
Chandler Carruth3bdf0432014-01-12 11:39:04 +0000763 Passes.add(createPrintModulePass(Out->os()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000764 Passes.run(*M.get());
Nadav Rotem78bda892012-02-26 08:35:53 +0000765 Out->keep();
766
767 return 0;
768}