blob: 672e4815690d204bcfbc051f081285defa4002d0 [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//===----------------------------------------------------------------------===//
Chandler Carruth9fb823b2013-01-02 11:36:10 +000014#include "llvm/IR/LLVMContext.h"
Matt Arsenaultbceea5d2013-02-26 21:20:35 +000015#include "llvm/ADT/OwningPtr.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000016#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/Analysis/Verifier.h"
18#include "llvm/Assembly/PrintModulePass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/Instruction.h"
21#include "llvm/IR/Module.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000022#include "llvm/PassManager.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000023#include "llvm/Support/Debug.h"
24#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000025#include "llvm/Support/PassNameParser.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000026#include "llvm/Support/PluginLoader.h"
27#include "llvm/Support/PrettyStackTrace.h"
28#include "llvm/Support/ToolOutputFile.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000029#include <algorithm>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000030#include <set>
31#include <sstream>
32#include <vector>
Nadav Rotem78bda892012-02-26 08:35:53 +000033using namespace llvm;
34
35static cl::opt<unsigned> SeedCL("seed",
36 cl::desc("Seed used for randomness"), cl::init(0));
37static cl::opt<unsigned> SizeCL("size",
38 cl::desc("The estimated size of the generated function (# of instrs)"),
39 cl::init(100));
40static cl::opt<std::string>
41OutputFilename("o", cl::desc("Override output filename"),
42 cl::value_desc("filename"));
43
Hal Finkelc9474122012-02-27 23:59:33 +000044static cl::opt<bool> GenHalfFloat("generate-half-float",
45 cl::desc("Generate half-length floating-point values"), cl::init(false));
46static cl::opt<bool> GenX86FP80("generate-x86-fp80",
47 cl::desc("Generate 80-bit X86 floating-point values"), cl::init(false));
48static cl::opt<bool> GenFP128("generate-fp128",
49 cl::desc("Generate 128-bit floating-point values"), cl::init(false));
50static cl::opt<bool> GenPPCFP128("generate-ppc-fp128",
51 cl::desc("Generate 128-bit PPC floating-point values"), cl::init(false));
52static cl::opt<bool> GenX86MMX("generate-x86-mmx",
53 cl::desc("Generate X86 MMX floating-point values"), cl::init(false));
54
Nadav Rotem78bda892012-02-26 08:35:53 +000055/// A utility class to provide a pseudo-random number generator which is
56/// the same across all platforms. This is somewhat close to the libc
57/// implementation. Note: This is not a cryptographically secure pseudorandom
58/// number generator.
59class Random {
60public:
61 /// C'tor
62 Random(unsigned _seed):Seed(_seed) {}
Dylan Noblesmith68f310d2012-04-10 22:44:51 +000063
64 /// Return a random integer, up to a
65 /// maximum of 2**19 - 1.
66 uint32_t Rand() {
67 uint32_t Val = Seed + 0x000b07a1;
Nadav Rotem78bda892012-02-26 08:35:53 +000068 Seed = (Val * 0x3c7c0ac1);
69 // Only lowest 19 bits are random-ish.
70 return Seed & 0x7ffff;
71 }
72
Dylan Noblesmith68f310d2012-04-10 22:44:51 +000073 /// Return a random 32 bit integer.
74 uint32_t Rand32() {
75 uint32_t Val = Rand();
76 Val &= 0xffff;
77 return Val | (Rand() << 16);
78 }
79
80 /// Return a random 64 bit integer.
81 uint64_t Rand64() {
82 uint64_t Val = Rand32();
83 return Val | (uint64_t(Rand32()) << 32);
84 }
Nadav Rotem0fb74082012-06-21 08:58:15 +000085
86 /// Rand operator for STL algorithms.
87 ptrdiff_t operator()(ptrdiff_t y) {
88 return Rand64() % y;
89 }
90
Nadav Rotem78bda892012-02-26 08:35:53 +000091private:
92 unsigned Seed;
93};
94
95/// Generate an empty function with a default argument list.
96Function *GenEmptyFunction(Module *M) {
97 // Type Definitions
98 std::vector<Type*> ArgsTy;
99 // Define a few arguments
100 LLVMContext &Context = M->getContext();
101 ArgsTy.push_back(PointerType::get(IntegerType::getInt8Ty(Context), 0));
102 ArgsTy.push_back(PointerType::get(IntegerType::getInt32Ty(Context), 0));
103 ArgsTy.push_back(PointerType::get(IntegerType::getInt64Ty(Context), 0));
104 ArgsTy.push_back(IntegerType::getInt32Ty(Context));
105 ArgsTy.push_back(IntegerType::getInt64Ty(Context));
106 ArgsTy.push_back(IntegerType::getInt8Ty(Context));
107
108 FunctionType *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, 0);
109 // Pick a unique name to describe the input parameters
110 std::stringstream ss;
111 ss<<"autogen_SD"<<SeedCL;
112 Function *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
113 ss.str(), M);
114
115 Func->setCallingConv(CallingConv::C);
116 return Func;
117}
118
119/// A base class, implementing utilities needed for
120/// modifying and adding new random instructions.
121struct Modifier {
122 /// Used to store the randomly generated values.
123 typedef std::vector<Value*> PieceTable;
124
125public:
126 /// C'tor
Nadav Rotemdc497b62012-02-26 08:59:25 +0000127 Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
Daniel Dunbarbeb34252012-02-29 00:20:33 +0000128 BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {}
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000129
130 /// virtual D'tor to silence warnings.
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000131 virtual ~Modifier();
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000132
Nadav Rotem78bda892012-02-26 08:35:53 +0000133 /// Add a new instruction.
134 virtual void Act() = 0;
135 /// Add N new instructions,
136 virtual void ActN(unsigned n) {
137 for (unsigned i=0; i<n; ++i)
138 Act();
139 }
140
141protected:
142 /// Return a random value from the list of known values.
143 Value *getRandomVal() {
144 assert(PT->size());
145 return PT->at(Ran->Rand() % PT->size());
146 }
147
Nadav Roteme4972dd2012-02-26 13:56:18 +0000148 Constant *getRandomConstant(Type *Tp) {
149 if (Tp->isIntegerTy()) {
150 if (Ran->Rand() & 1)
151 return ConstantInt::getAllOnesValue(Tp);
152 return ConstantInt::getNullValue(Tp);
153 } else if (Tp->isFloatingPointTy()) {
154 if (Ran->Rand() & 1)
155 return ConstantFP::getAllOnesValue(Tp);
156 return ConstantFP::getNullValue(Tp);
157 }
158 return UndefValue::get(Tp);
159 }
160
Nadav Rotem78bda892012-02-26 08:35:53 +0000161 /// Return a random value with a known type.
162 Value *getRandomValue(Type *Tp) {
163 unsigned index = Ran->Rand();
164 for (unsigned i=0; i<PT->size(); ++i) {
165 Value *V = PT->at((index + i) % PT->size());
166 if (V->getType() == Tp)
167 return V;
168 }
169
170 // If the requested type was not found, generate a constant value.
171 if (Tp->isIntegerTy()) {
172 if (Ran->Rand() & 1)
173 return ConstantInt::getAllOnesValue(Tp);
174 return ConstantInt::getNullValue(Tp);
175 } else if (Tp->isFloatingPointTy()) {
176 if (Ran->Rand() & 1)
177 return ConstantFP::getAllOnesValue(Tp);
178 return ConstantFP::getNullValue(Tp);
Nadav Roteme4972dd2012-02-26 13:56:18 +0000179 } else if (Tp->isVectorTy()) {
180 VectorType *VTp = cast<VectorType>(Tp);
181
182 std::vector<Constant*> TempValues;
183 TempValues.reserve(VTp->getNumElements());
184 for (unsigned i = 0; i < VTp->getNumElements(); ++i)
185 TempValues.push_back(getRandomConstant(VTp->getScalarType()));
186
187 ArrayRef<Constant*> VectorValue(TempValues);
188 return ConstantVector::get(VectorValue);
Nadav Rotem78bda892012-02-26 08:35:53 +0000189 }
190
Nadav Rotem78bda892012-02-26 08:35:53 +0000191 return UndefValue::get(Tp);
192 }
193
194 /// Return a random value of any pointer type.
195 Value *getRandomPointerValue() {
196 unsigned index = Ran->Rand();
197 for (unsigned i=0; i<PT->size(); ++i) {
198 Value *V = PT->at((index + i) % PT->size());
199 if (V->getType()->isPointerTy())
200 return V;
201 }
202 return UndefValue::get(pickPointerType());
203 }
204
205 /// Return a random value of any vector type.
206 Value *getRandomVectorValue() {
207 unsigned index = Ran->Rand();
208 for (unsigned i=0; i<PT->size(); ++i) {
209 Value *V = PT->at((index + i) % PT->size());
210 if (V->getType()->isVectorTy())
211 return V;
212 }
213 return UndefValue::get(pickVectorType());
214 }
215
216 /// Pick a random type.
217 Type *pickType() {
218 return (Ran->Rand() & 1 ? pickVectorType() : pickScalarType());
219 }
220
221 /// Pick a random pointer type.
222 Type *pickPointerType() {
223 Type *Ty = pickType();
224 return PointerType::get(Ty, 0);
225 }
226
227 /// Pick a random vector type.
228 Type *pickVectorType(unsigned len = (unsigned)-1) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000229 // Pick a random vector width in the range 2**0 to 2**4.
230 // by adding two randoms we are generating a normal-like distribution
231 // around 2**3.
232 unsigned width = 1<<((Ran->Rand() % 3) + (Ran->Rand() % 3));
Dylan Noblesmith2a592dc2012-04-10 22:44:49 +0000233 Type *Ty;
234
235 // Vectors of x86mmx are illegal; keep trying till we get something else.
236 do {
237 Ty = pickScalarType();
238 } while (Ty->isX86_MMXTy());
239
Nadav Rotem78bda892012-02-26 08:35:53 +0000240 if (len != (unsigned)-1)
241 width = len;
242 return VectorType::get(Ty, width);
243 }
244
245 /// Pick a random scalar type.
246 Type *pickScalarType() {
Hal Finkelc9474122012-02-27 23:59:33 +0000247 Type *t = 0;
248 do {
249 switch (Ran->Rand() % 30) {
250 case 0: t = Type::getInt1Ty(Context); break;
251 case 1: t = Type::getInt8Ty(Context); break;
252 case 2: t = Type::getInt16Ty(Context); break;
253 case 3: case 4:
254 case 5: t = Type::getFloatTy(Context); break;
255 case 6: case 7:
256 case 8: t = Type::getDoubleTy(Context); break;
257 case 9: case 10:
258 case 11: t = Type::getInt32Ty(Context); break;
259 case 12: case 13:
260 case 14: t = Type::getInt64Ty(Context); break;
261 case 15: case 16:
262 case 17: if (GenHalfFloat) t = Type::getHalfTy(Context); break;
263 case 18: case 19:
264 case 20: if (GenX86FP80) t = Type::getX86_FP80Ty(Context); break;
265 case 21: case 22:
266 case 23: if (GenFP128) t = Type::getFP128Ty(Context); break;
267 case 24: case 25:
268 case 26: if (GenPPCFP128) t = Type::getPPC_FP128Ty(Context); break;
269 case 27: case 28:
270 case 29: if (GenX86MMX) t = Type::getX86_MMXTy(Context); break;
271 default: llvm_unreachable("Invalid scalar value");
272 }
273 } while (t == 0);
274
275 return t;
Nadav Rotem78bda892012-02-26 08:35:53 +0000276 }
277
278 /// Basic block to populate
279 BasicBlock *BB;
280 /// Value table
281 PieceTable *PT;
282 /// Random number generator
283 Random *Ran;
284 /// Context
285 LLVMContext &Context;
286};
287
288struct LoadModifier: public Modifier {
Daniel Dunbarbeb34252012-02-29 00:20:33 +0000289 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000290 virtual ~LoadModifier();
Nadav Rotem78bda892012-02-26 08:35:53 +0000291 virtual void Act() {
292 // Try to use predefined pointers. If non exist, use undef pointer value;
293 Value *Ptr = getRandomPointerValue();
294 Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
295 PT->push_back(V);
296 }
297};
298
299struct StoreModifier: public Modifier {
300 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000301 virtual ~StoreModifier();
Nadav Rotem78bda892012-02-26 08:35:53 +0000302 virtual void Act() {
303 // Try to use predefined pointers. If non exist, use undef pointer value;
304 Value *Ptr = getRandomPointerValue();
305 Type *Tp = Ptr->getType();
306 Value *Val = getRandomValue(Tp->getContainedType(0));
Nadav Rotem63ff91d2012-02-26 12:00:22 +0000307 Type *ValTy = Val->getType();
Nadav Rotem78bda892012-02-26 08:35:53 +0000308
309 // Do not store vectors of i1s because they are unsupported
Nadav Rotem115ec822012-02-26 12:34:17 +0000310 // by the codegen.
311 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000312 return;
313
314 new StoreInst(Val, Ptr, BB->getTerminator());
315 }
316};
317
318struct BinModifier: public Modifier {
319 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000320 virtual ~BinModifier();
Nadav Rotem78bda892012-02-26 08:35:53 +0000321
322 virtual void Act() {
323 Value *Val0 = getRandomVal();
324 Value *Val1 = getRandomValue(Val0->getType());
325
326 // Don't handle pointer types.
327 if (Val0->getType()->isPointerTy() ||
328 Val1->getType()->isPointerTy())
329 return;
330
331 // Don't handle i1 types.
332 if (Val0->getType()->getScalarSizeInBits() == 1)
333 return;
334
335
336 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
337 Instruction* Term = BB->getTerminator();
338 unsigned R = Ran->Rand() % (isFloat ? 7 : 13);
339 Instruction::BinaryOps Op;
340
341 switch (R) {
342 default: llvm_unreachable("Invalid BinOp");
343 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
344 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
345 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
346 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
347 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
348 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
349 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
350 case 7: {Op = Instruction::Shl; break; }
351 case 8: {Op = Instruction::LShr; break; }
352 case 9: {Op = Instruction::AShr; break; }
353 case 10:{Op = Instruction::And; break; }
354 case 11:{Op = Instruction::Or; break; }
355 case 12:{Op = Instruction::Xor; break; }
356 }
357
358 PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
359 }
360};
361
362/// Generate constant values.
363struct ConstModifier: public Modifier {
364 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000365 virtual ~ConstModifier();
366
Nadav Rotem78bda892012-02-26 08:35:53 +0000367 virtual void Act() {
368 Type *Ty = pickType();
369
370 if (Ty->isVectorTy()) {
371 switch (Ran->Rand() % 2) {
372 case 0: if (Ty->getScalarType()->isIntegerTy())
373 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
374 case 1: if (Ty->getScalarType()->isIntegerTy())
375 return PT->push_back(ConstantVector::getNullValue(Ty));
376 }
377 }
378
379 if (Ty->isFloatingPointTy()) {
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000380 // Generate 128 random bits, the size of the (currently)
381 // largest floating-point types.
382 uint64_t RandomBits[2];
383 for (unsigned i = 0; i < 2; ++i)
384 RandomBits[i] = Ran->Rand64();
385
386 APInt RandomInt(Ty->getPrimitiveSizeInBits(), makeArrayRef(RandomBits));
Tim Northover98d9b7e2013-01-22 10:18:26 +0000387 APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000388
Nadav Rotem78bda892012-02-26 08:35:53 +0000389 if (Ran->Rand() & 1)
390 return PT->push_back(ConstantFP::getNullValue(Ty));
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000391 return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
Nadav Rotem78bda892012-02-26 08:35:53 +0000392 }
393
394 if (Ty->isIntegerTy()) {
395 switch (Ran->Rand() % 7) {
396 case 0: if (Ty->isIntegerTy())
397 return PT->push_back(ConstantInt::get(Ty,
398 APInt::getAllOnesValue(Ty->getPrimitiveSizeInBits())));
399 case 1: if (Ty->isIntegerTy())
400 return PT->push_back(ConstantInt::get(Ty,
401 APInt::getNullValue(Ty->getPrimitiveSizeInBits())));
402 case 2: case 3: case 4: case 5:
403 case 6: if (Ty->isIntegerTy())
404 PT->push_back(ConstantInt::get(Ty, Ran->Rand()));
405 }
406 }
407
408 }
409};
410
411struct AllocaModifier: public Modifier {
412 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000413 virtual ~AllocaModifier();
Nadav Rotem78bda892012-02-26 08:35:53 +0000414
415 virtual void Act() {
416 Type *Tp = pickType();
417 PT->push_back(new AllocaInst(Tp, "A", BB->getFirstNonPHI()));
418 }
419};
420
421struct ExtractElementModifier: public Modifier {
422 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
423 Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000424 virtual ~ExtractElementModifier();
Nadav Rotem78bda892012-02-26 08:35:53 +0000425
426 virtual void Act() {
427 Value *Val0 = getRandomVectorValue();
428 Value *V = ExtractElementInst::Create(Val0,
429 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
Nadav Rotemaeacc172012-04-15 20:17:14 +0000430 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
Nadav Rotem78bda892012-02-26 08:35:53 +0000431 "E", BB->getTerminator());
432 return PT->push_back(V);
433 }
434};
435
436struct ShuffModifier: public Modifier {
437 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000438 virtual ~ShuffModifier();
439
Nadav Rotem78bda892012-02-26 08:35:53 +0000440 virtual void Act() {
441
442 Value *Val0 = getRandomVectorValue();
443 Value *Val1 = getRandomValue(Val0->getType());
444
445 unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
446 std::vector<Constant*> Idxs;
447
448 Type *I32 = Type::getInt32Ty(BB->getContext());
449 for (unsigned i=0; i<Width; ++i) {
450 Constant *CI = ConstantInt::get(I32, Ran->Rand() % (Width*2));
451 // Pick some undef values.
452 if (!(Ran->Rand() % 5))
453 CI = UndefValue::get(I32);
454 Idxs.push_back(CI);
455 }
456
457 Constant *Mask = ConstantVector::get(Idxs);
458
459 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
460 BB->getTerminator());
461 PT->push_back(V);
462 }
463};
464
465struct InsertElementModifier: public Modifier {
466 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
467 Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000468 virtual ~InsertElementModifier();
Nadav Rotem78bda892012-02-26 08:35:53 +0000469
470 virtual void Act() {
471 Value *Val0 = getRandomVectorValue();
472 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
473
474 Value *V = InsertElementInst::Create(Val0, Val1,
475 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
476 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
477 "I", BB->getTerminator());
478 return PT->push_back(V);
479 }
480
481};
482
483struct CastModifier: public Modifier {
484 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000485 virtual ~CastModifier();
486
Nadav Rotem78bda892012-02-26 08:35:53 +0000487 virtual void Act() {
488
489 Value *V = getRandomVal();
490 Type *VTy = V->getType();
491 Type *DestTy = pickScalarType();
492
493 // Handle vector casts vectors.
494 if (VTy->isVectorTy()) {
495 VectorType *VecTy = cast<VectorType>(VTy);
496 DestTy = pickVectorType(VecTy->getNumElements());
497 }
498
Nadav Rotemaeacc172012-04-15 20:17:14 +0000499 // no need to cast.
Nadav Rotem78bda892012-02-26 08:35:53 +0000500 if (VTy == DestTy) return;
501
502 // Pointers:
503 if (VTy->isPointerTy()) {
504 if (!DestTy->isPointerTy())
505 DestTy = PointerType::get(DestTy, 0);
506 return PT->push_back(
507 new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
508 }
509
Nadav Rotemaeacc172012-04-15 20:17:14 +0000510 unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
511 unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
512
Nadav Rotem78bda892012-02-26 08:35:53 +0000513 // Generate lots of bitcasts.
Nadav Rotemaeacc172012-04-15 20:17:14 +0000514 if ((Ran->Rand() & 1) && VSize == DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000515 return PT->push_back(
516 new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
517 }
518
519 // Both types are integers:
520 if (VTy->getScalarType()->isIntegerTy() &&
521 DestTy->getScalarType()->isIntegerTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000522 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000523 return PT->push_back(
524 new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
525 } else {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000526 assert(VSize < DestSize && "Different int types with the same size?");
Nadav Rotem78bda892012-02-26 08:35:53 +0000527 if (Ran->Rand() & 1)
528 return PT->push_back(
529 new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
530 return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
531 }
532 }
533
534 // Fp to int.
535 if (VTy->getScalarType()->isFloatingPointTy() &&
536 DestTy->getScalarType()->isIntegerTy()) {
537 if (Ran->Rand() & 1)
538 return PT->push_back(
539 new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
540 return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
541 }
542
543 // Int to fp.
544 if (VTy->getScalarType()->isIntegerTy() &&
545 DestTy->getScalarType()->isFloatingPointTy()) {
546 if (Ran->Rand() & 1)
547 return PT->push_back(
548 new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
549 return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
550
551 }
552
553 // Both floats.
554 if (VTy->getScalarType()->isFloatingPointTy() &&
555 DestTy->getScalarType()->isFloatingPointTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000556 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000557 return PT->push_back(
558 new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
Nadav Rotemaeacc172012-04-15 20:17:14 +0000559 } else if (VSize < DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000560 return PT->push_back(
561 new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
562 }
Nadav Rotemaeacc172012-04-15 20:17:14 +0000563 // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
564 // for which there is no defined conversion. So do nothing.
Nadav Rotem78bda892012-02-26 08:35:53 +0000565 }
566 }
567
568};
569
570struct SelectModifier: public Modifier {
571 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
572 Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000573 virtual ~SelectModifier();
Nadav Rotem78bda892012-02-26 08:35:53 +0000574
575 virtual void Act() {
576 // Try a bunch of different select configuration until a valid one is found.
577 Value *Val0 = getRandomVal();
578 Value *Val1 = getRandomValue(Val0->getType());
579
580 Type *CondTy = Type::getInt1Ty(Context);
581
582 // If the value type is a vector, and we allow vector select, then in 50%
583 // of the cases generate a vector select.
584 if (Val0->getType()->isVectorTy() && (Ran->Rand() % 1)) {
585 unsigned NumElem = cast<VectorType>(Val0->getType())->getNumElements();
586 CondTy = VectorType::get(CondTy, NumElem);
587 }
588
589 Value *Cond = getRandomValue(CondTy);
590 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
591 return PT->push_back(V);
592 }
593};
594
595
596struct CmpModifier: public Modifier {
597 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000598 virtual ~CmpModifier();
599
Nadav Rotem78bda892012-02-26 08:35:53 +0000600 virtual void Act() {
601
602 Value *Val0 = getRandomVal();
603 Value *Val1 = getRandomValue(Val0->getType());
604
605 if (Val0->getType()->isPointerTy()) return;
606 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
607
608 int op;
609 if (fp) {
610 op = Ran->Rand() %
611 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
612 CmpInst::FIRST_FCMP_PREDICATE;
613 } else {
614 op = Ran->Rand() %
615 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
616 CmpInst::FIRST_ICMP_PREDICATE;
617 }
618
619 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
620 op, Val0, Val1, "Cmp", BB->getTerminator());
621 return PT->push_back(V);
622 }
623};
624
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000625// Use out-of-line definitions to prevent weak vtables.
626Modifier::~Modifier() {}
627LoadModifier::~LoadModifier() {}
628StoreModifier::~StoreModifier() {}
629BinModifier::~BinModifier() {}
630ConstModifier::~ConstModifier() {}
631AllocaModifier::~AllocaModifier() {}
632ExtractElementModifier::~ExtractElementModifier() {}
633ShuffModifier::~ShuffModifier() {}
634InsertElementModifier::~InsertElementModifier() {}
635CastModifier::~CastModifier() {}
636SelectModifier::~SelectModifier() {}
637CmpModifier::~CmpModifier() {}
638
Nadav Rotem0fb74082012-06-21 08:58:15 +0000639void 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.
648 for (Function::arg_iterator it = F->arg_begin(), e = F->arg_end();
649 it != e; ++it)
650 PT.push_back(it);
651
652 // List of modifiers which add new random instructions.
653 std::vector<Modifier*> Modifiers;
Matt Arsenaultbceea5d2013-02-26 21:20:35 +0000654 OwningPtr<Modifier> LM(new LoadModifier(BB, &PT, &R));
655 OwningPtr<Modifier> SM(new StoreModifier(BB, &PT, &R));
656 OwningPtr<Modifier> EE(new ExtractElementModifier(BB, &PT, &R));
657 OwningPtr<Modifier> SHM(new ShuffModifier(BB, &PT, &R));
658 OwningPtr<Modifier> IE(new InsertElementModifier(BB, &PT, &R));
659 OwningPtr<Modifier> BM(new BinModifier(BB, &PT, &R));
660 OwningPtr<Modifier> CM(new CastModifier(BB, &PT, &R));
661 OwningPtr<Modifier> SLM(new SelectModifier(BB, &PT, &R));
662 OwningPtr<Modifier> PM(new CmpModifier(BB, &PT, &R));
Nadav Rotem78bda892012-02-26 08:35:53 +0000663 Modifiers.push_back(LM.get());
664 Modifiers.push_back(SM.get());
665 Modifiers.push_back(EE.get());
666 Modifiers.push_back(SHM.get());
667 Modifiers.push_back(IE.get());
668 Modifiers.push_back(BM.get());
669 Modifiers.push_back(CM.get());
670 Modifiers.push_back(SLM.get());
671 Modifiers.push_back(PM.get());
672
673 // Generate the random instructions
674 AllocaModifier AM(BB, &PT, &R); AM.ActN(5); // Throw in a few allocas
675 ConstModifier COM(BB, &PT, &R); COM.ActN(40); // Throw in a few constants
676
677 for (unsigned i=0; i< SizeCL / Modifiers.size(); ++i)
678 for (std::vector<Modifier*>::iterator it = Modifiers.begin(),
679 e = Modifiers.end(); it != e; ++it) {
680 (*it)->Act();
681 }
682
683 SM->ActN(5); // Throw in a few stores.
684}
685
Nadav Rotem0fb74082012-06-21 08:58:15 +0000686void IntroduceControlFlow(Function *F, Random &R) {
687 std::vector<Instruction*> BoolInst;
Nadav Rotem78bda892012-02-26 08:35:53 +0000688 for (BasicBlock::iterator it = F->begin()->begin(),
689 e = F->begin()->end(); it != e; ++it) {
690 if (it->getType() == IntegerType::getInt1Ty(F->getContext()))
Nadav Rotem0fb74082012-06-21 08:58:15 +0000691 BoolInst.push_back(it);
Nadav Rotem78bda892012-02-26 08:35:53 +0000692 }
693
Nadav Rotem0fb74082012-06-21 08:58:15 +0000694 std::random_shuffle(BoolInst.begin(), BoolInst.end(), R);
695
696 for (std::vector<Instruction*>::iterator it = BoolInst.begin(),
Nadav Rotem78bda892012-02-26 08:35:53 +0000697 e = BoolInst.end(); it != e; ++it) {
698 Instruction *Instr = *it;
699 BasicBlock *Curr = Instr->getParent();
700 BasicBlock::iterator Loc= Instr;
701 BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
702 Instr->moveBefore(Curr->getTerminator());
703 if (Curr != &F->getEntryBlock()) {
704 BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
705 Curr->getTerminator()->eraseFromParent();
706 }
707 }
708}
709
710int main(int argc, char **argv) {
711 // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
712 llvm::PrettyStackTraceProgram X(argc, argv);
713 cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
714 llvm_shutdown_obj Y;
715
Matt Arsenaultbceea5d2013-02-26 21:20:35 +0000716 OwningPtr<Module> M(new Module("/tmp/autogen.bc", getGlobalContext()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000717 Function *F = GenEmptyFunction(M.get());
Nadav Rotem0fb74082012-06-21 08:58:15 +0000718
719 // Pick an initial seed value
720 Random R(SeedCL);
721 // Generate lots of random instructions inside a single basic block.
722 FillFunction(F, R);
723 // Break the basic block into many loops.
724 IntroduceControlFlow(F, R);
Nadav Rotem78bda892012-02-26 08:35:53 +0000725
726 // Figure out what stream we are supposed to write to...
727 OwningPtr<tool_output_file> Out;
728 // Default to standard output.
729 if (OutputFilename.empty())
730 OutputFilename = "-";
731
732 std::string ErrorInfo;
733 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
Rafael Espindola6d354812013-07-16 19:44:17 +0000734 sys::fs::F_Binary));
Nadav Rotem78bda892012-02-26 08:35:53 +0000735 if (!ErrorInfo.empty()) {
736 errs() << ErrorInfo << '\n';
737 return 1;
738 }
739
740 PassManager Passes;
741 Passes.add(createVerifierPass());
742 Passes.add(createPrintModulePass(&Out->os()));
743 Passes.run(*M.get());
Nadav Rotem78bda892012-02-26 08:35:53 +0000744 Out->keep();
745
746 return 0;
747}